14

我正在开发一个在 Glassfish 上运行的应用程序。我应该通过使用 jax-rs 和 jersey 将 servlet 转换为适当的宁静的东西。

我一直在尝试找到 init() 方法的解决方法,但直到现在我失败了。

这是原始部分,使用 servlet:

import javax.servlet.*

public void init(ServletConfig config) throws ServletException {
super.init(config);
 if (!isRunning() == true)) {
     /* Do some stuff here*/
 }

 logger.info("Deamon has started");
}

而这个我正在尝试使用 jax-rs

import javax.ws.rs.*
import javax.servlet.*

public void init(@Context ServletConfig config) throws ServletException {
//uper.init(config);
if (!isRunning() == true)) {
  /* Do some stuff here*/
}

logger.info("Deamon has started");
}

我检查了邮件列表并四处搜索,但找不到适合这种情况的方法。

任何想法如何使用 init 方法的 servlet 实现相同的行为?

4

4 回答 4

11

最后,在谷歌搜索多一点之后,我找到了一个合适的解决方案。

基本上,我已经扩展 了类并实现了加载应用程序时调用public class ContextListener implements ServletContextListener的抽象方法。public void contextInitialized(ServletContextEvent sce)我已将逻辑从 servlet 移至此处以进行初始化和其他配置设置,然后一切顺利。

于 2013-05-31T08:29:35.697 回答
7

使用@PostConstruct;来自 Web 应用程序的示例:

@Context
private ServletContext context;

@PostConstruct
public void init() {
  // init instance
}
于 2013-05-29T09:00:10.543 回答
5

Here is how I implemented an init method in Jersey 2.6/JAX-RS in case it helps anyone. This is using the suggestion of @PostConstruct.

The code below starts the web app, scans for all resources in the package and initialises a static test counter with 3:

package com.myBiz.myWebApp;

import com.sun.net.httpserver.HttpServer;
import java.io.IOException;
import java.net.URI;
import java.util.Set;
import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import javax.ws.rs.core.Application;

public class WebApplication extends Application {
    // Base URI the HTTP server will listen to
    public static final String BASE_URI = "http://localhost:8080/";
     public static int myCounter = 0;

    /**
     * Starts a server, initializes and keeps the server alive
     * @param args
     * @throws IOException
     */
    public static void main(String[] args) throws IOException {
        final HttpServer server = startServer();
        initialize();
        System.out.println("Jersey app started\nHit enter to stop it...");
        System.in.read();
        server.stop(1);
        System.out.println("Server stopped successfully.");
    }

    /**
     * Default constructor
     */
    public WebApplication() {
        super();
    }

    /**
     * Initialize the web application
     */
    @PostConstruct
    public static void initialize() {
        myCounter = myCounter + 3;
    }

    /**
     * Define the set of "Resource" classes for the javax.ws.rs.core.Application
     */
    @Override
    public Set<Class<?>> getClasses() {
        return getResources().getClasses();
    }

    /**
     * Scans the project for REST resources using Jersey
     * @return the resource configuration information
     */
    public static ResourceConfig getResources() {
        // create a ResourceConfig that scans for all JAX-RS resources and providers in defined package
        final ResourceConfig config = new ResourceConfig().packages(com.myBiz.myWebApp);
        return config;
    }

    /**
     * Starts HTTP server exposing JAX-RS resources defined in this application.
     * @return HTTP server.
     */
    public static HttpServer startServer() {
        return JdkHttpServerFactory.createHttpServer(URI.create(BASE_URI), getResources());
    }
}

And here is the associated build.xml, which needs to refer to this class (WebApplication):

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <!-- The following instantiates the class WebApplication, resources are scanned on WebApplication object creation and init is done as well -->
    <servlet>
        <servlet-name>myWebApp</servlet-name>
        <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>
        <init-param>
            <param-name>javax.ws.rs.Application</param-name>
            <param-value>com.myBiz.myWebApp.WebApplication</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>myWebApp</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

From here, just create a "test" resource to check the counter:

package com.myBiz.myWebApp;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import com.myBiz.myWebApp.WebApplication;

@Path("/test")
public class ResourceTest {
    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String getResource() {
        WebApplication.myCounter++;
        return "Counter: " + WebApplication.myCounter;
    }
}

The counter should be initialized with value 3 + 1, and subsequently refreshing the resource will just increase it by 1.

于 2014-02-20T03:47:15.827 回答
2

您可以创建一个标签ServletContextClass并将其<listener>添加到 web.xml

listener 标记在 Web 应用程序启动时加载 ServerContextClass。在contextInitialized方法内部,您可以访问上下文,如下所示:

public void contextInitialized(ServletContextEvent arg0){
    ServletContext context = arg0.getServletContext();
} 

请参阅 此处的类似示例

于 2015-04-09T11:37:15.207 回答