IT TIP

JAX-RS 리소스에서 ServletContext 가져 오기

itqueen 2020. 11. 21. 08:30
반응형

JAX-RS 리소스에서 ServletContext 가져 오기


Tomcat에 배포하는 JAX-RS를 사용하고 있습니다. 기본적으로 다음과 같습니다.

@Path("/hello")
@Produces({"text/plain"})
public class Hellohandler {

    @GET
    public String hello() {
        return "Hello World";
    }

}

ServletContext내 JAX-RS 리소스를 확보 할 수있는 방법이 있습니까?


또한 @Resource주석이 작동하지 않을 수 있습니다. 이 시도

@javax.ws.rs.core.Context 
ServletContext context;

주입은 서비스 방법을 칠 때까지 발생하지 않습니다.

public class MyService {
    @Context ServletContext context;

    public MyService() {
         print("Constructor " + context);  // null here     
    }

    @GET
    @Path("/thing") {               
             print("in  wizard service " + context); // available here

다른 사람들이 언급했듯이 servletContext는 필드 수준에서 삽입 될 수 있습니다. 메서드 수준에서 삽입 할 수도 있습니다.

public static class MyService {
    private ServletContext context;
    private int minFoo;

    public MyService() {
        System.out.println("Constructor " + context); // null here
    }

    @Context
    public void setServletContext(ServletContext context) {
        System.out.println("servlet context set here");
        this.context = context;

        minFoo = Integer.parseInt(servletContext.getInitParameter("minFoo")).intValue();

    }

    @GET
    @Path("/thing")
    public void foo() {
        System.out.println("in wizard service " + context); // available here
        System.out.println("minFoo " + minFoo); 
    }
}

이렇게하면 사용 가능한 servletContext로 추가 초기화를 수행 할 수 있습니다.

명백한 참고 사항-메소드 이름 setServletContext 를 사용할 필요가 없습니다 . setter에 대한 표준 Java Bean 이름 지정 패턴 인 void setXXX (Foo foo) 를 따르고 @Context 주석을 사용하는 한 원하는 모든 메소드 이름을 사용할 수 있습니다 .


The servlet context is also available when you implement the ServletContextListener. This makes it easy to load parameters such as connection string at start-up. You can define the listener class in web.xml that loads you ServletContextListener at startup of your web application.

Inside the web.xml file, add the <listener>and <context-param> tags. The <listener> specifies the class that is called at startup. The <context-param> tag defines context parameter that is available within your web application.

First, include the <listener>and <context-param> tags in the web.xml file:

<web-app>
  <!-- ... -->
  <listener>
    <listener-class>com.your.package.ServletContextClass</listener-class>
  </listener>

  <!-- Init parameters for db connection -->
  <context-param>
    <param-name>your_param</param-name>
    <param-value>your_param_value</param-value>
  </context-param>
  <!-- ... -->
</web-app>

Now create the servlet context class as follows.

public class ServletContextClass implements ServletContextListener
{
  public void contextInitialized(ServletContextEvent arg0) 
   {
    //use the ServletContextEvent argument to access the 
    //parameter from the context-param
    String my_param = arg0.getServletContext().getInitParameter("your_param");
   }//end contextInitialized method

  @Override
  public void contextDestroyed(ServletContextEvent arg0) 
  { }//end constextDestroyed method
}

You can now choose which static variable to assign the parameter you have read. This allows you to read the parameter once at start-up, and reuse many time through the static variable that you assign it to.


Just use resource injection like this,

@Resource ServletContext servletContext;

Check out: http://markmail.org/message/isy6mdpoh66vyi6k#query:jersey%20getservletcontext%20-spring+page:1+mid:sa7n465kfgdoskv5+state:results

참고URL : https://stackoverflow.com/questions/1814517/get-servletcontext-in-jax-rs-resource

반응형