Java JAX-RS中等效的Servlet init()方法

Java JAX-RS中等效的Servlet init()方法,java,servlets,glassfish,jersey,jax-rs,Java,Servlets,Glassfish,Jersey,Jax Rs,我正在开发一个在Glassfish上运行的应用程序。我应该使用jax-rs和jersey将servlet转换为适当的restful内容 我一直在尝试为init()方法找到一个解决方法,但到现在为止我失败了 以下是使用servlet的原始部分: import javax.servlet.* public void init(ServletConfig config) throws ServletException { super.init(config); if (!isRunning() =

我正在开发一个在Glassfish上运行的应用程序。我应该使用jax-rs和jersey将servlet转换为适当的restful内容

我一直在尝试为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");
}
我查了邮件列表,在谷歌上搜索了一下,但找不到一个适合这个案子的方法

有没有办法用servlet for init方法实现相同的行为

使用;来自web应用程序的示例:

@Context
private ServletContext context;

@PostConstruct
public void init() {
  // init instance
}
<?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>

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

基本上,我已经扩展了
公共类ContextListener实现了ServletContextListener
类,并实现了加载应用程序时调用的抽象方法
public void contextInitialized(ServletContextEvent sce)
。我已经将servlet中的逻辑移到这里来进行初始化和其他配置设置,然后一切都很顺利。

下面是我如何在Jersey 2.6/JAX-RS中实现init方法的,以防它对任何人都有帮助。这是使用@PostConstruct的建议

下面的代码启动web应用程序,扫描包中的所有资源,并用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());
    }
}

计数器应使用值3+1初始化,随后刷新资源只会将其增加1。

您可以创建
ServletContextClass
并将
标记添加到web.xml

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

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

请参阅“未工作”。。。初始化应用程序时未调用该方法。可能是因为玻璃鱼的内部物质吗?或者我缺少了一些其他配置?这对我来说在Glassfish 3.1.1上使用提供的Jersey实现是可行的。如果您使用的是NetBeans,请使用示例Java Web服务REST:Hello World(Java EE 6)创建一个新项目,并将您的描述符(Web.xml等)与其中使用的描述符进行比较。@PostConstruct方法无法抛出选中的异常,这很麻烦。RESTEasy(部署到JBoss EAP 6.2)对我不起作用@在Wildfly10.1.0中未调用PostConstruct这绝对是最好的解决方案,尤其是如果您希望在服务器关闭时写入文件。我的评论的主要目的是感谢你们给出了这个伟大的答案,并帮助未来的谷歌用户更容易地找到这个简洁的解决方案。这是一个很好的例子。事实上,如果你在泽西岛,你可以使用
ApplicationEventListener
insteadDaemon=后台进程做有用的工作;恶魔=恶魔,执事不存在。
public void contextInitialized(ServletContextEvent arg0){
    ServletContext context = arg0.getServletContext();
}