2013-05-29 26 views
10

我正在Glassfish上运行的应用程序上工作。我应该通过使用jax-rs和球衣来将servlet转换为适当的安静的东西。在JAX-RS中相当于Servlet的init()方法

我一直在试图找到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的init方法相同的行为?

回答

6

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

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

+0

这绝对是最好的解决方案,尤其是如果您想在服务器关闭时写入文件。我的评论的主要目的是感谢您提供这个优秀的答案,并帮助未来的Google员工更轻松地找到这个简洁的解决方案。 这是一个很棒的[example-SSCCE](https://www.mkyong.com/servlet/what-is-listener-servletcontextlistener-example/)。 – Casper

+0

实际上,如果你在球衣上,你可以使用'ApplicationEventListener' – svarog

6

使用@PostConstruct;从一个Web应用程序的例子:

@Context 
private ServletContext context; 

@PostConstruct 
public void init() { 
    // init instance 
} 
+0

没有工作......而初始化应用程序不调用方法。这可能是因为玻璃鱼内部的东西?还是我缺少一些其他配置? – stephanruhl

+0

这对我使用提供的Jersey实现的Glassfish 3.1.1有效。如果您使用NetBeans,请使用_Samples > Java Web Services > REST:Hello World(Java EE 6)_创建一个新项目,并将您的描述符(web.xml等)与那里使用的描述符(web.xml等)进行比较。 – McDowell

+0

我找到了解决问题的另一种方法,谢谢 – stephanruhl

2

下面是我如何在泽西岛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()); 
    } 
} 

这里是相关的build.xml,这需要参照这个类(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> 

从这里出发,只需创建一个 “测试” 的资源来检查计数器:

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; 
    } 
} 

计数器应值3 + 1被初始化,随后刷新资源将只是增加它由1

0

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

监听器标签在您的Web应用程序启动时加载ServerContextClass。里面的contextInitialized方法,你可以访问下面的背景:

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

参考similar example here

相关问题