Jersey 2: How to pass parameters from web.xml to the application?

My web container knows if my application is running in debug or release mode. I would like to pass this information to my ResourceConfig / Application class, but it is not clear how to read this information.

Is it possible to transmit information using servlet / filter parameters? If so, how?

+4
source share
3 answers

This has been fixed in Jersey 2.5: https://java.net/jira/browse/JERSEY-2184

Now you can enter @Context ServletContextinto the constructor Application.

Here is an example of how this should work:

public class MyApplication extends Application
{
  private final String myInitParameter;

  public MyApplication(@Context ServletContext servletContext)
  {
    this.myInitParameter = servletContext.getInitParameter("myInitParameter");
  }
}

You can also call ServiceLocator.getService(ServletContext.class)to get ServletContextfrom anywhere in the application.

+1

:

web.xml:

<context-param>
  <description>When set to true, all operations include debugging info</description>
  <param-name>com.example.DEBUG_API_ENABLED</param-name>
  <param-value>true</param-value>
</context-param>

Application:

@ApplicationPath("api")
public class RestApplication extends Application {
  @Context
  protected ServletContext sc;

  @Override
  public Set<Class<?>> getClasses() {
    Set<Class<?>> set = new HashSet<Class<?>>();
    boolean debugging = Boolean.parseBoolean(sc
            .getInitParameter("com.example.DEBUG_API_ENABLED"));

    if (debugging) {
        // enable debugging resources
+3

In Jersey 1, you could pass it to @Context ServletContext servletContextthe class constructor Application, but in Jersey 2 it no longer works. It seems that Jersey 2 will only enter at the time of the request.

To get around this on Jersey-2, use anonymous ContainerRequestFilterto access the ServletContext during the request and pass the necessary init parameters to the class Application.

public class MyApplication extends Application {
  @Context protected ServletContext servletContext;
  private String myInitParameter;

  @Override
  public Set<Object> getSingletons() {
    Set<Object> singletons = new HashSet<Object>();
    singletons.add(new ContainerRequestFilter() {
      @Override
      public void filter(ContainerRequestContext containerRequestContext) throws IOException {
        synchronized(MyApplication.this) {
          if(myInitParameter == null) {
            myInitParameter = servletContext.getInitParameter("myInitParameter");
            // do any initialisation based on init params here
          }
        }
      }
      return singletons;
    });
  };
}
0
source

All Articles