Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

My web container knows whether my application is running in debug or release mode. I'd like to pass this information to my ResourceConfig/Application class, but it's not clear how to read this information back out.

Is it possible to pass information by way of servlet/filter parameters? If so, how?

like image 413
Gili Avatar asked Oct 25 '13 18:10

Gili


2 Answers

Here's how I'm doing it:

in 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>

and in my Application subclass:

@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
like image 80
dkoper Avatar answered Dec 26 '22 02:12

dkoper


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

You should now be able to inject @Context ServletContext into the Application constructor.

Here is an example of how this is expected to work:

public class MyApplication extends Application
{
  private final String myInitParameter;

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

You can also invoke ServiceLocator.getService(ServletContext.class) to get the ServletContext from any point in the application.

like image 39
Gili Avatar answered Dec 26 '22 01:12

Gili