1

I wrote a controller class for my webapp, which inherits from HttpServlet.

public abstract class BaseController extends HttpServlet {
protected ClientsProvider clientsProvider;

@Override
public void init() throws ServletException {
    clientsProvider = (ClientsProvider) getServletContext().getAttribute(
        "clientsProvider");
    if (clientsProvider == null) {
        clientsProvider = new ClientsProvider();
        getServletContext().setAttribute("clientsProvider", clientsProvider);
    }
    super.init();
}

CommonsProvider is another class in which I initialized all the clients I used in this project.

Now I want to use web.xml to do the init() work, instead of writing such init() code here. Like this:

<servlet>
    <servlet-name>BaseController</servlet-name>
    <servlet-class>myproject.controller.BaseController</servlet-class>
    <load-on-startup>1</load-on-startup>

    <context-param>
        <param-name>clientsProvider</param-name>
        <param-value>clientsProvider</param-value>
    </context-param>
</servlet>

The above code does not work because the param values are not set property. What I need in the param-value is a new ClientsProvider() object. In this case, is it still possible to do the init() work in web.xml? Thanks!

Emile
  • 187
  • 5
  • 17
  • 1
    You cannot do that declarative in web.xml but you can have a lifecycle listener or filter for such cross cutting concerns. DI frameworks use the same mechanism. – eckes Aug 25 '17 at 21:42

1 Answers1

1

The web.xml cannot do this, because there will be no instance of the ClientProvider at startup time. You can use a DI container like the Spring Framework to do that. If you dont want to use any framework, you could pass the full qualified class name as a String and use Class.forName(...) in your servlet.

<context-param>
    <param-name>clientsProvider</param-name>
    <param-value>your.package.ClientsProvider</param-value>
    <!--<param-value>your.package.AnotherClientsProvider</param-value>-->
</context-param>
Stefan
  • 12,108
  • 5
  • 47
  • 66