Java Servlet Configuring programmatically.

Servlet Configuring programmatically

  • Servlet 3.0 allows us to configure our web applications programmatically at runtime.
  • The ServletContext class has new methods to configure servlets, filters, and listeners programmatically.
  • This programming is best to do in the implemented contextInitialized() method of the ServletContextListener.
    The ServletContext object can be retrieved as follow:
    @WebListener()
    public class ContextListenerImpl implements ServletContextListener {
      @Override
      public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext servletContext = servletContextEvent.getServletContext();
    ...

Setting up configurations for a servlet programmatically.

  • You must use one of the addServlet() methode to register the Servlet with the Servlet context.
  • ServletContext methods for servlet registration :
    Method Description
    public ServletRegistration addServlet(String servletName, Class<? extends Servlet> servletClass) Adds the servlet with the given name and class type to this servlet context.
    public ServletRegistration addServlet(String servletName, Servlet servlet) Registers the given servlet instance with this ServletContext under the given servletName.
    public ServletRegistration addServlet(String servletName, String className) Adds the servlet with the given name and class name to this servlet context.
  • All the above methods returns a ServletRegistration object containing addMapping (String ... urlPattern) method.
  • Using this method one can associate multiple url to a same servlet.
  • An example of configure a servlet programmatically can be found further down on this page.

Setting up configurations for a filter programmatically

  • You must use one of the addFilter() methode to register our the Filter with the Servlet context.
  • ServletContext methods for filter registration :
    Method Description
    public FilterRegistration addFilter(String filterName, Class<? extends Class> filterClass) Adds the filter with the given name and class type to this servlet context.
    public FilterRegistration addFilter(String filterName, Filter filter) Registers the given filter instance with this ServletContext under the given filterName.
    public FilterRegistration addFilter(String filterName, String className) Adds the filter with the given name and class name to this servlet context.
  • All the above methods returns a FilterRegistration object containing two methods for mapping the filter to a servlet.
  • FilterRegistration methods for filter mapping to servlets:
    Method Description
    void addMappingForServletNames( EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... servletNames)
    • dispatcherTypes - the dispatcher types of the filter mapping, or null if the default DispatcherType.REQUEST is to be used.
    • isMatchAfter - true if the given filter mapping should be matched after any declared filter mappings, and false if it is supposed to be matched before any declared filter mappings of the ServletContext from which this FilterRegistration was obtained.
    • servletNames - the servlet names of the filter mapping.
    void addMappingForUrlPatterns( EnumSet<DispatcherType> dispatcherTypes, boolean isMatchAfter, String... urlPatterns)
    • dispatcherTypes - the dispatcher types of the filter mapping, or null if the default DispatcherType.REQUEST is to be used.
    • isMatchAfter - true if the given filter mapping should be matched after any declared filter mappings, and false if it is supposed to be matched before any declared filter mappings of the ServletContext from which this FilterRegistration was obtained.
    • urlPatterns - the url patterns of the filter mapping.
  • Filter mappings are matched in the order in which they were added (isMatchAfter has an effect on the filter chain as well).
  • An example of configure a filter programmatically can be found further down on this page.

Setting up configurations for a servlet Listeners programmatically

  • You must use one of the addListener() methode to register the Listener on a servlet with the Servlet context.
  • ServletContext methods for Listener registration :
    Method Description
    void addListener(Class<? extends EventListener> listenerClass) Adds a listener of the given class type to this ServletContext.
    void addListener(String className) Adds the listener with the given class name to this ServletContext.
    <T extends EventListener> void addListener(T t) Adds the given listener to this ServletContext.

Example of Servlet Configuring programmatically.

As selected we use Netbeans IDE and Glassfish Server.

You can download this example here (needed tools can be found in the right menu on this page).

If you like to participate in the review of this example you must first create a Web project in Netbeans (the project name is ServletProgrammatically).

In this example we need 4 java files:

  1. A servlet, ProgServlet.java, to be configured.
  2. A servlet filter, ProgFilter.java, to be configured.
  3. A servlet listener, ProgListener.java, to be configured.
  4. A java file, ContextListenerImpl.java, where we make the configuration of the three previous.
  • Here is the servlet to be configured:
    package web.app;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class ProgServlet extends HttpServlet {
    
      @Override
      protected void doPost(HttpServletRequest request,
              HttpServletResponse response)
              throws ServletException, IOException {
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
        writer.println(request.getAttribute("initListener") + "<br/>");
        writer.println(request.getAttribute("fromFilter") + "<br/>");
        writer.println("Request Servlet at " + date + "<br/>");
        writer.println(" Servlet - doGet: username=" + request.getParameter("username")
                + ", password=" + request.getParameter("password") + "<br/>");
        writer.println("This is a servlet that was configured programmatically.<br/>");
        System.out.println("Servlet at " + date);
      }
    }

    For those who participate in the review: create a Servlet in Netbeans and replace generated code for the servlet with that shown above (the servlet name is ProgServlet).

    Here is the servlet filter to be configured:
    package web.app;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    
    public class ProgFilter implements Filter {
      @Override
      public void init(FilterConfig filterConfig) throws ServletException {
      }
    
      @Override
      public void doFilter(ServletRequest req, ServletResponse res,
              FilterChain chain) throws IOException, ServletException {
        
        String date= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
        System.out.println("Filter request at "+ date);
        req.setAttribute("fromFilter", " Request Filter at: "+ date);
        chain.doFilter(req, res);
        date= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
        PrintWriter writer = res.getWriter();
        writer.println("Response Filter at: "+ date+"<br/>");   
        writer.println("<br/>Look as well into the server log.<br/>");  
        System.out.println("Response request at "+ date);
      }
    
      @Override
      public void destroy() {
      }
    }

    For those who participate in the review: create a Servlet filter in Netbeans and replace generated code for the filter with that shown above (the filter name is ProgServlet).

    Here is the servlet listener to be configured:
    package web.app;
    
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletRequestEvent;
    import javax.servlet.ServletRequestListener;
    
    public class ProgListener implements ServletRequestListener {
    
      @Override
      public void requestDestroyed(ServletRequestEvent sre) {
        ServletContext servletContext = sre.getServletContext();
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
        servletContext.log("Request destroyed at " + date);
      }
    
      @Override
      public void requestInitialized(ServletRequestEvent sre) {
         ServletContext servletContext = sre.getServletContext();
        String date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
        sre.getServletRequest().setAttribute("initListener", " Init Request Listener at: " + date);
        servletContext.log("Init Request Listener at: " + date);
      }
    
    }

    For those who participate in the review: create a Java class in Netbeans and replace generated code for the class with that shown above (the class name is ProgListener).

    Here is the configuration java file:
    package web.app;
    
    import javax.servlet.*;
    import javax.servlet.annotation.WebListener;
    
    @WebListener()
    public class ContextListenerImpl implements ServletContextListener {
    
      @Override
      public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("ProgrammaticallyConfigured start");
        ServletContext servletContext = servletContextEvent.getServletContext();
        try {
    // Setting up configurations for a servlet programmatically   
          ServletRegistration servletRegistration
                  = servletContext.addServlet("ProgServlet", "web.app.ProgServlet");
          servletRegistration.addMapping("/login");
          System.out.println(ProgServlet.class.getName());
    
    // Setting up configurations for a filteer programmatically     
          FilterRegistration filterRegistration
                  = servletContext.addFilter("ProgFilter", "web.app.ProgFilter");
          filterRegistration.addMappingForServletNames(null, true, "ProgServlet");
    
    // Setting up configurations for a Listenerr programmatically   
          ProgListener listener = servletContext.createListener(ProgListener.class);
          servletContext.addListener(listener);
    
        } catch (ServletException servletException) {
          servletContext.log(servletException.getMessage());
        }
        System.out.println("ProgrammaticallyConfigured done");
      }
    
      @Override
      public void contextDestroyed(ServletContextEvent servletContextEvent) {
      }
    }

    For those who participate in the review: create a Java class in Netbeans and replace generated code for the class with that shown above (the class name is ContextListenerImpl).

  • As you can see the servlet has been configured with the url /login, the filter is connected in the front of the servlet and the request listener i added to the servlet context.
    The html startup file, login.html, for the browser can be like this:
    <!DOCTYPE HTML>
    <html>
      <head>
        <title>Login</title>
      </head>
      <body>
        <h1>Login</h1>
        Please enter your username and password
        <form action="/ServletProgrammatically/login" method="POST">
          <p><input type="text" name="username" value="abcde" style="width: 100px;" ></p>
          <p><input type="password" name="password" value="admin" style="width: 100px;"></p>
          <p><input type="submit" value="Submit"></p>
        </form>
      </body>
    </html>

    For those who participate in the review: create a HTML page in Netbeans and replace generated code for the html file with that shown above (the name of the html should be login and places in the folder web).

Creating Deployment descriptor.

  • To run this web application you have to deploy it to a web-server or a Application server. To deploy means to install the Servlet with some instruction to a such server.
  • The instructions are mainly defined to be deployment descriptors. The standard part of the deployment descriptor should be in an XML-file with the name web.xml.

    You may need to create a Deployment descriptor file, web.xml in Netbeans.

  • The contents of the web.xml should look like this:
    <?xml version="1.0" encoding="UTF-8"?>
    
    <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    	 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	 xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee 
    http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    	 version="3.1">
        <session-config>
            <session-timeout>
                30
            </session-timeout>
        </session-config>
        <welcome-file-list>
            <welcome-file>/login.html</welcome-file>
        </welcome-file-list>    
    </web-app>
  • This file starts with the normal xml tag for a XML file and the root tag for the deployment descriptor is web-app. Every ting inside the last tag is to tell the server about our application.
  • If no session-timeout (the server ends the service of the application after this time) is given a standard timeout for the server is used as timeout for the application.
  • The welcome-file tag specifies the startup for our application, which in this case and our application is the welcome file login.html. Reorganize the welcome-file-list to what is shown above.

Creating Web-server Deployment descriptor.

  • The context-root (in example /ServletProgrammatically) for the application will in most cases be specified by a server vendor deployment descriptor.

    For those who participate in the review: create a deployment descriptor in Netbeans.

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE sun-web-app PUBLIC "-//Sun Microsystems, 
    Inc.//DTD GlassFish Application Server 3.0 Servlet 3.0//EN" 
    "http://www.sun.com/software/appserver/dtds/sun-web-app_3_0-0.dtd">
    <sun-web-app error-url="">
      <context-root>/ServletProgrammatically</context-root>
      <class-loader delegate="true"/>
      <jsp-config>
        <property name="keepgenerated" value="true">
          <description>
            Keep a copy of the generated servlet class' java code.
          </description>
        </property>
      </jsp-config>
    </sun-web-app>

Run the application.

  • For those who participate in the review: right click the Web-project and select Run.
  • This results in that the application will be deployed to the server and started.
  • The browser will display:

    Login

    Please enter your username and password

    Enter username, password and press the submit button.

    The web application will response with a text something like this :
    Init Request Listener at: 2015-11-05 10:04:58.002
    Request Filter at: 2015-11-05 10:04:58.005
    Request Servlet at 2015-11-05 10:04:58.006
    Servlet - doGet: username=abcde, password=admin
    This is a servlet that was configured programmatically.
    Response Filter at: 2015-11-05 10:04:58.011

    Look as well into the server log.
© 2010 by Finnesand Data. All rights reserved.
This site aims to provide FREE programming training and technics.
Finnesand Data as site owner gives no warranty for the correctness in the pages or source codes.
The risk of using this web-site pages or any program codes from this website is entirely at the individual user.