19 - Servlet 3.0 Examples

19.1 Overview

We have discussed the new features and annotations introduced in Servlet 3.0. Now it is the time to implement all the new features using small examples.

19.2 Examples

Create a new web application (using Dynamic Project in eclipse) similar to HelloWorld web application. Lets name it Servlet3Examples.

Note- Do not create any web.xml because we will use annotation in examples.

19.2.1 @WebServlet-

Write a servlet using @WebServlet annotation that-

  1.  implement both doGet() and doPost() method.
  2. Maps to multiple URLs (WelcomeServlet and HelloWorld)
  3. There should be no configuration in web.xml

Solution:

package com.servlet3.tutorial;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(
    name="WelcomeServlet",
    description="Servlet with Annotation",
    urlPatterns={"/WelcomeServlet","/HelloWorld"}
    )
public class WelcomeServlet extends HttpServlet{
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println("Get method of Welcome Servlet");
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        System.out.println("Post method of Welcome Servlet");
    }
}

Testing:

Hit the url

http://localhost:8080/Servlet3Examples/WelcomeServlet

http://localhost:8080/Servlet3Examples/HelloWorld

19.2.2 @WebInitParam

Use the @WebInitParam annotation in servlet created in above example to define two init parameters. Update the servlet code to read and display the param names and value on user screen. There should be no configuration in web.xml.

Solution :

package com.servlet3.tutorial;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(
    name="WelcomeServlet",
    description="Servlet with Annotation",
    initParams={@WebInitParam(name="param1",value="value1"),
        @WebInitParam(name="param2",value="value2")},
    urlPatterns={"/WelcomeServlet","/HelloWorld"}
    )
public class WelcomeServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
        ServletConfig config= getServletConfig();
        Enumeration<String> paramEnumeration= config.getInitParameterNames();
        StringBuffer buffer = new StringBuffer();
        while(paramEnumeration.hasMoreElements())
        {
            String paramName= paramEnumeration.nextElement();
            String paramValue =config.getInitParameter(paramName);
            buffer.append(paramName + ":" + paramValue);
            buffer.append("<br/>");
        }
        response.setContentType("text/html");
        PrintWriter writer = response.getWriter();
        writer.println(buffer.toString());
    }                                     
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
    {
        doGet(req, resp);
    }                    
}

Testing :

Hit the url  http://localhost:8080/Servlet3Examples/WelcomeServlet OR http://localhost:8080/Servlet3Examples/HelloWorld

19.2. 3 @WebFilter

Write a filter using @WebFilter annotation which

  1. uses @WebInitParams
  2. Displays all the init params defined
  3. applies on WelcomeServlet created in above examples
  4. There should be no configuration in web.xml

Solution

package com.servlet3.tutorial;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
@WebFilter(
    filterName="DisplayInitParam",
    urlPatterns={"/WelcomeServlet","/HelloWorld"},
    initParams={
    @WebInitParam(name="FilterParam1",value="FilterParamValue1"),
    @WebInitParam(name="FilterParam2",value="FilterParamValue2")
    }
)
public class DisplayInitParamFilter implements Filter {
    private FilterConfig filterConfig=null;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter  initialized...");
        this.filterConfig = filterConfig;
    }
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException
 {
        Enumeration<String> initParams= filterConfig.getInitParameterNames();
        StringBuffer buffer = new StringBuffer();
        while(initParams.hasMoreElements())
        {
            String initParamName = initParams.nextElement();
            String initParamValue =filterConfig.getInitParameter(initParamName);
            buffer.append(initParamName+"::" + initParamValue);
            buffer.append(" <br/> ") ;
        }   
        PrintWriter writer = response.getWriter();
        writer.println(buffer.toString());
    }
    @Override
    public void destroy() {
        System.out.println("Filter  Destroyed..");
    }
}

Testing :

Hit the url  http://localhost:8080/Servlet3Examples/WelcomeServlet OR http://localhost:8080/Servlet3Examples/HelloWorld

Refer below figure for Server Console

19.2.4 @WebListener

Write a HttpSessionAttributeListener using @WebServlet annotation and create one servlet using @WebServlet to verify the listener is working or not. There should be no configuration in web.xml

Solution

  1. Create a TestWebListenerAnnotation listener for HttpSessionAttributeListener which will print the messages on server console when any object is added , replaced or removed from session
package com.servlet3.tutorial;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
@WebListener
public class TestWebServletAnnotationListener  implements HttpSessionAttributeListener {
/**
 * Default constructor. 
 */
public TestWebServletAnnotationListener() 
{
}
@Override
public void attributeAdded(HttpSessionBindingEvent httpSessionBindingEvent) {
    System.out.println("Attribute has been added");
    String attributeName = httpSessionBindingEvent.getName();
    Object attributeValue = httpSessionBindingEvent.getValue();
    System.out.println("Attribute Name ::" + attributeName);
    System.out.println("Attribute Value ::" + attributeValue.toString());
}
@Override
public void attributeRemoved(HttpSessionBindingEvent httpSessionBindingEvent)
 {
        System.out.println("Attribute has been Removed");
        String attributeName = httpSessionBindingEvent.getName();
        Object attributeValue = httpSessionBindingEvent.getValue();
        System.out.println("Attribute Name ::" + attributeName);
        System.out.println("Attribute Value ::" + attributeValue.toString());
}
@Override
public void attributeReplaced(HttpSessionBindingEvent httpSessionBindingEvent) 
{
        System.out.println("Attribute has been Replaced");
        String attributeName = httpSessionBindingEvent.getName();
        Object attributeValue = httpSessionBindingEvent.getValue();
        System.out.println("Attribute Name ::" + attributeName);
        System.out.println("Attribute Value ::" + attributeValue.toString());       
}                                                                                   
}

  1. Create a SessionAttributeTestServlet which will add , replace and remove the object from session.
package com.servlet3.tutorial;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet(
    name="SessionAttributeTestServlet",
    description="Servlet with Annotation",
    urlPatterns={"/SessionAttributeTestServlet"}
    )
public class SessionAttributeTestServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)    throws ServletException, IOException
 {
        HttpSession session = request.getSession();
        String attributeName="SessionAttribute";
        String attributeValue="Initial Value";
        session.setAttribute(attributeName, attributeValue);
        attributeValue="New Value";
        session.setAttribute(attributeName, attributeValue);
        session.removeAttribute(attributeName);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException
{
        doGet(req, resp);
}
}

 

Testing :

Hit the url  http://localhost:8080/Servlet3Examples/SessionAttributeTestServlet

19.2.5 Web Fragments

Think of the situation where third party framework is available which provides a functionality of printing message when context is created and destroyed. (Yes you guessed right. I am talking of ServletContextListener)

We can have such listener in our Servlet3Examples web application because the scenario I discussed is very simple but we may need to integrate other framework functionality which we do not want to develop.

Servlet 3 introduces the feature of web fragment where we can include the third party jar files in WEB-INF\lib directory of  our web application and we will get the advantage of that functionality. We need not even add any configuration in web.xml

Now lets create a another project which will have a listener and we will add this jar file in our web application.

  1. You can create a web fragment project using Eclipse “ Newà Projectà Web à Web Fragment Project” and name it a TestWebFragment

You will see a little different structure of this project and main thing is web-fragment-xml in META-INF

    

  1. Create one listener TestServletContextListener which implements ServletContextListener In TestWebFragment project
package com.webfragment.tutorial;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
@WebListener
public class TestServletContextListener  implements ServletContextListener {
    /**
     * Default constructor. 
     */
 public TestServletContextListener() {
   }
   public void contextInitialized(ServletContextEvent servletContextEvent)
   {
    System.out.println("Context Initialized.. Called from Test Web Fragment");
   }
    public void contextDestroyed(ServletContextEvent servletContextEvent)
    {
           System.out.println("Context Destroyed.. Called from Test Web Fragment");
    }
}

 

  1. Create a jar file of TestWebFragment project and place it in WEB-INF\lib directory of Servlet3Examples project
  2. Deploy the Servlet3Examples web application and see the server console (highlighted in blue) .

We have third party functionality by just placing jar file

You must be wondering what is the use of web-fragment.xml. web-fragment.xml is similar to web.xml but keeps relevant information and since we used @WebListener annotation on the listener we need not to do corresponding entry in web-fragment.xml.

If we remove @WebListener annotation then we need to add below entry between  <web-fragment> </web-fragment> 

  <listener>
  <listener-class>
com.webfragment.tutorial.TestServletContextListener
</listener-class>
  </listener>  

19.3 Conclusion

In this chapter we have learned how to use annotation and can get rid of web.xml in Servlet using annotation with the help of examples.

Like us on Facebook