Servlet Wrappers 

Servlet Wrappers with Examples

In this article, I am going to discuss Servlet Wrappers with Examples. Please read our previous article where we discussed Java Servlet Events and Listeners. At the end of this article, you will understand the following pointers in detail.

  1. Why Servlet Wrappers?
  2. Types of Servlet Wrappers.
  3. Servlet RequestWrapper Example
  4. Servlet ResponseWrapper Example
Why Servlet Wrappers?

The main purpose of Servlet Wrappers in web applications is used for the customization of request and response objects. In general, in web application execution when we send a request from the client to the server for a particular servlet then the container will pick up the request, identify the requested servlet, perform servlet life cycle stages like servlet loading, servlet instantiation, servlet initialization, request processing, and servlet de-instantiation.

As part of the request, the processing container has no access service (_,_)method, for this container has to prepare servlet request and servlet response objects. As part of the application requirement, we need to use our own request and response objects in the servlets instead of using container-provided request and response objects.

To achieve this requirement, we have to perform the customization of request and response objects. In general, the servlet is an abstraction i.e. collection of interfaces provided by Sun Microsystems and whose implementations could be provided by all the server vendors. Similarly, if we want to customize request and response objects, we have to implement ServletRequest and ServletResponse interfaces by taking implementation classes.

Why Servlet Wrappers?

To perform request and response object customization if we use the above approach then we must implement directly ServletRequest and ServletResponse interfaces i.e. we must provide an implementation for each and every method declared in ServletRequest and ServletResponse interfaces. This approach will increase the burden to the developers.

To overcome the above problem Servlet API has provided an alternative in the form of a set of predefined classes called Wrapper classes. All the Servlet Wrapper classes are direct implementation classes to the respective ServletRequest and ServletResponse and so on.

Servlet Wrapper classes is an idea provided by a design pattern called Adapter Design Pattern. If we want to prepare our own request and response classes, we have to extend the respective Servlet Wrapper class and override the required method.

Servlet Wrappers with Examples

where Xxxxx may be a particular Wrapper class.

Types of Wrapper Class in Servlet

There are two types of Wrapper classes in Servlet API:

Types of Wrapper Class in Servlet

Request Wrapper is used to wrap the ServletRequest/HttpServletRequest. It is also used to perform many tasks within a web application such as – request validation, change, or add more data to the request before it reaches the requested Servlet.

Response Wrapper is used to wrap the ServletResponse/HttpServletResponse. It is used to change or add more data to the response object.

Note: To customize the request and response objects we have to use a Filter in order to prepare our own request and response objects and to pass our own request and response objects to the service(_,_) method.

Servlet RequestWrapper Example

In this example, we are creating a webpage Webpage1.jsp which asks the user to enter his/her name and city and click on the “Submit” button which will call a servlet. But before this Servlet is executed, a filter MyFilter1.java associated with it will be executed. MyServlet1.java is a servlet class that is associated with the filter.

Webpage1.jsp
<html>
    <head>
        <title>ServletRequest Wrapper Demo</title>
    </head>

    <body>
        <b> Please enter your name : ? </b>
        <br />
        <br />
        <br />

        <form action="MyServ">
            Name : <input type="text" name="username" /> City : <input type="text" name="cityname" />
            <input type="submit" name="submit" />
        </form>
    </body>
</html>
MyFilter1.java
import java.io.*;
import javax.servlet.*;
public class MyFilter1 implements Filter
{
    public void init (FilterConfig filterConfig)
    {
    }

    public void destroy ()
    {
    }

    //This method is called each time a client requests for a web resource i.e. preprocessing request
    public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException
    {
        response.setContentType ("text/html");
        PrintWriter out = response.getWriter ();
        out.println("<b> <i>Filtering request and passing it to Wrapper class</i> </b> <br/>");

        //Calling the constructor of request wrapper class 
        RequestWrapper1 requestWrapper = new RequestWrapper1 (request);

        //This method calls the next filter in the chain
        chain.doFilter (requestWrapper, response);
    }
}
RequestWrapper1.java
import java.io.*;
import javax.servlet.*;
public class RequestWrapper1 extends ServletRequestWrapper
{
    public RequestWrapper1 (ServletRequest req)
    {
        //calls the ServletRequestWrapper superclass's constructor i.e. ServletRequest.
        super (req);
    }

    public String getParameter (String str)
    {
        //Calling the superclass method i.e. ServletRequest's getParameter(String) method.
        String name = super.getParameter (str);
        if (name.equals (""))
        {
         name = "Please, enter your name in the form";
        }
        return name;
    }
}
MyServlet1.java
import javax.servlet.*;
import java.io.*;
public class MyServlet1 extends GenericServlet
{
    public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException
    {
        response.setContentType ("text/html");
        String name = request.getParameter ("username");
        PrintWriter out = response.getWriter ();
        out.println (name);
    }
}
web.xml
<?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_4_0.xsd"
  version="4.0"
  metadata-complete="true">
    <display-name>Welcome tomcat</display-name>
    <description>
     Welcome tomcat
  </description>
    <filter>
        <filter-name>Filter1</filter-name>
        <filter-class>MyFilter1</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Filter1</filter-name>
        <url-pattern>/MyServ</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>Servlet</servlet-name>
        <servlet-class>MyServlet1</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Servlet</servlet-name>
        <url-pattern>/MyServ</url-pattern>
    </servlet-mapping>
</web-app>

Output

Servlet RequestWrapper Example

Servlet ResponseWrapper Example

In this example, we are creating a webpage Webpage1.jsp which asks the user to enter his/her name and city and click on the “Submit” button which will call a servlet MyServlet1.java. But before this Servlet is executed, a filter MyFilter1.java associated with it will be executed. MyServlet1.java is a servlet class that is associated with the filter.

Webpage1.jsp
<html>
    <head>
        <title>ServletResponse Wrapper Demo</title>
    </head>
    <body>
        <b> Please enter your name : ? </b>
        <br />
        <br />
        <br />
        <form action="MyServ">
            Name : <input type="text" name="username" /> City : <input type="text" name="cityname" />
            <input type="submit" name="submit" />
        </form>
    </body>
</html>
MyFilter1.java
import java.io.*;
import javax.servlet.*;
public class MyFilter1 implements Filter
{
    public void init (FilterConfig filterConfig)
    {
    }

    public void destroy ()
    {
    }

    //This method is called each time a client requests for a web resource i.e. preprocessing request
    public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException
    {
        response.setContentType ("text/html");
        PrintWriter out = response.getWriter ();
        out.println("<b> <i>Filter is filtering the response and passing it to Wrapper class</i> </b> <br/>");

        //Calling the constructor of response wrapper class 
        ResponseWrapper1 responseWrapper = new ResponseWrapper1 (response);

        //This method calls the next filter in the chain
        chain.doFilter (request, responseWrapper);
    }
}
ResponseWrapper1.java
import java.io.*;
import javax.servlet.*;
import java.util.*;
public class ResponseWrapper1 extends ServletResponseWrapper
{
    public ResponseWrapper1 (ServletResponse res)
    {
        //Calling the ServletResponseWrapper superclass constructor i.e. ServletResponse interface.
        super (res);
    }

    public Locale getLocale ()
    {
        System.out.println ("Wrapper class called by Filter");

        //Calling the superclass method i.e. ServletResponse's getLocale() method.
        Locale loc = super.getLocale ();

        String country = loc.getCountry ();
        String language = loc.getLanguage ();

        if (!country.equals ("US"))
        {
         Locale loc1 = new Locale ("English, US");
         loc = loc1;
        }

        System.out.println (country);
        System.out.println (language);
        return loc;
    }
}
MyServlet1.java
import javax.servlet.*;
import java.io.*;
import java.util.*;
public class MyServlet1 extends GenericServlet
{
    public void service (ServletRequest request, ServletResponse response) throws ServletException, IOException
    {
        response.setContentType ("text/html");
        PrintWriter out = response.getWriter ();
        System.out.println ("Servlet is called");
        Locale loc = response.getLocale ();
        out.println ("Locale set for this application is " + loc.toString ());
    }
}
web.xml
<?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_4_0.xsd"
  version="4.0"
  metadata-complete="true">
    <display-name>Welcome tomcat</display-name>
    <description>
     Welcome tomcat
  </description>
    <filter>
        <filter-name>Filter1</filter-name>
        <filter-class>MyFilter1</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>Filter1</filter-name>
        <url-pattern>/MyServ</url-pattern>
    </filter-mapping>
    <servlet>
        <servlet-name>Servlet</servlet-name>
        <servlet-class>MyServlet1</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>Servlet</servlet-name>
        <url-pattern>/MyServ</url-pattern>
    </servlet-mapping>
</web-app>

Output

Servlet ResponseWrapper Example

In the next article, I am going to discuss Servlet Filter with Examples. Here, in this article, I try to explain Servlet Wrappers with Examples. I hope you enjoy this Servlet Wrappers article.

Leave a Reply

Your email address will not be published. Required fields are marked *