2013-05-29 24 views
10

Tôi đang làm việc trên một ứng dụng đang chạy trên Glassfish. Tôi có nghĩa vụ phải chuyển đổi các servlet để các công cụ yên tĩnh thích hợp, bằng cách sử dụng jax-rs và jersey.Servlet init() phương pháp tương đương trong JAX-RS

Tôi đã cố gắng tìm cách giải quyết cho phương thức init(), nhưng cho đến bây giờ tôi đã thất bại.

Dưới đây là phần gốc, sử dụng servlets:

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

và điều này mà tôi đang cố gắng sử dụng 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"); 
} 

Tôi đã kiểm tra danh sách gửi thư và googled xung quanh nhưng couldnt tìm một cách có thể làm việc cho trường hợp này.

bất kỳ ý tưởng nào để đạt được cùng một hành vi với servlet cho phương pháp init?

Trả lời

6

cuối cùng, sau khi tìm kiếm thêm một chút, tôi đã tìm được giải pháp thích hợp.

về cơ bản, tôi đã mở rộng public class ContextListener implements ServletContextListener lớp và triển khai phương thức trừu tượng public void contextInitialized(ServletContextEvent sce) được gọi khi ứng dụng được tải. Tôi đã chuyển logic từ servlet đến đây để thực hiện khởi tạo và các thiết lập cấu hình khác, sau đó nó đã được mịn màng.

+0

Đây chắc chắn là giải pháp tốt nhất, đặc biệt là nếu bạn muốn ghi vào tập tin trên máy chủ tắt máy. Mục đích chính của nhận xét của tôi là cảm ơn Bạn vì câu trả lời tuyệt vời này và để giúp các nhân viên Google trong tương lai tìm thấy giải pháp gọn gàng này dễ dàng hơn. Đây là một [ví dụ-SSCCE] tuyệt vời (https://www.mkyong.com/servlet/what-is-listener-servletcontextlistener-example/). – Casper

+0

thực sự nếu bạn đang ở trên áo, bạn có thể sử dụng 'ApplicationEventListener' thay thế – svarog

6

Sử dụng @PostConstruct; ví dụ từ ứng dụng web:

@Context 
private ServletContext context; 

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

didnt làm việc ... Phương pháp này không được gọi trong khi ứng dụng được khởi tạo. có thể vì một số thứ bên trong với cá kình? hoặc tôi thiếu một số cấu hình khác? – stephanruhl

+0

Điều này làm việc cho tôi trên Glassfish 3.1.1 bằng cách sử dụng thực hiện Jersey cung cấp.Nếu bạn đang sử dụng NetBeans, hãy tạo một dự án mới bằng cách sử dụng _Samples > Dịch vụ Web Java > REST: Hello World (Java EE 6) _ và so sánh các mô tả của bạn (web.xml, v.v.) với các mô tả được sử dụng ở đó. – McDowell

+0

tôi đã tìm thấy một cách khác để giải quyết vấn đề, cảm ơn bạn – stephanruhl

2

Đây là cách tôi đã triển khai phương pháp init trong Jersey 2.6/JAX-RS trong trường hợp nó giúp mọi người. Điều này đang sử dụng đề xuất của @PostConstruct.

Đoạn code dưới đây bắt đầu ứng dụng web, quét mọi nguồn lực trong gói và khởi một thử nghiệm truy cập tĩnh với 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()); 
    } 
} 

Và đây là build.xml liên quan, mà cần phải tham khảo này lớp (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> 

Từ đây, chỉ cần tạo một "test" tài nguyên để kiểm tra các cập:

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

Bộ đếm nên được khởi tạo với giá trị 3 + 1, và sau đó làm mới các tài nguyên sẽ chỉ tăng nó bằng 1.

0

Bạn có thể tạo một ServletContextClass và thêm thẻ <listener> vào web.xml

Người nghe thẻ tải ServerContextClass khi khởi động ứng dụng web của bạn. Bên trong phương pháp contextInitialized bạn có thể truy cập vào bối cảnh như sau:

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

Tham khảo similar example here

Các vấn đề liên quan