In this article, we are going to understand how to use Wrappers in a web application.
Wrappers are placed between the Servlet and the Servlet Container, due to which the interaction with Servlet is done using wrappers. There are two kinds of wrappers -
Request Wrappers, used to wrap the ServletRequest/HttpServletRequest.
Response Wrappers, used to wrap the ServletResponse/HttpServletResponse.
Using the request and response wrappers, we can 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,
change or add more data to the response object.
Today, we are going to create a wrapper class which extends ServletRequestWrapper class(which has implemented ServletRequest interface).
Using this wrapper class we will be able to wrap the ServletRequest object and hence we will be able to
manipulate, check any request sent to a Servlet by the user.
To do this, we will create a Filter class which will be associated with the requested Servlet and this
Filter class will also call the wrapper class to perform the check on any request sent to Servlet by the user.
Creating a webpage which calls the Servlet
We are creating a webpage which asks the user to enter her/his name, city and click the submit button,
which when clicked, will call a Servlet, but before this Servlet is executed, a filter associated with it will be executed(
mentioned in the deployment descriptor file(web.xml).
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>
Creating a Filter class
We are creating a Filter class by implementing the Filter interface and by implementing its three methods
This Filter class creates an object of ServletRequest wrapper class, which is wrapped around the object of ServletRequest. Eventually doFilter() method
of FilterChain is called and passed
with this request wrapper object as an argument, which makes sure there is a filtering over the request and response object, using the wrapper class.
MyFilter1.java
package decodejava;
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);
}
}
This wrapper class has extended the ServletRequestWrapper(which has implemented ServletRequest interface). This wrapper class
and has overidden its getParameter(String) method of ServletRequestWrapper class, which is
invoked when there is a call to getParameter(String) method of ServletRequest in the requested Servlet.
This class creates a ServletRequest wrapper object.
RequestWrapper1.java
package decodejava;
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 is a Servlet class, which is associated with the filter.
MyServlet1.java
package decodejava;
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);
}
}
Advertisement
Directory Structure of Servlet files
The diagram above depicts how to arrange the Servlet files in a specific directory structure, as per Java Servlet Specification-
Project Folder - We have created a project folder named ServletRequestWrapperEx within
the webapps folder of Tomcat installation folder. This folder contains the Servlet class(.java) file and WEB-INF folder.
WEB-INF - Within your project folder, you create another folder named WEB-INF and this folder should contain the deployment descriptor file(web.xml) of your Java Servlet program.
classes - Within the WEB-INF folder you should create a folder named classes. This folder should contain the compiled(.class) form of your Java Servlet class.
Creating the Deployment Descriptor file
As per the Java Servlet specifications, every web application based on Servlet must have a Deployment Descriptor file(an XML file) named web.xml.
So, let's create one and this time, associate our filter class with our Servlet class -
In deployment descriptor file, The <filter> has two child tags <filter-name> and <filter-class>.
<filter-name> tag is used to specify a unique name for our filter class, we have given it a unique name Filter1.
<filter-class> tag is used to specify the full qualified name of the filter class and in our example our filter class is named decodejava.MyFilter1.
<servlet> has two child tags <servlet-name> and <servlet-class> :
<servlet-name> tag is used to specify a unique name for our Servlet class, we have given it a unique name Servlet.
<servlet-class> tag is used to specify the full qualified name of the Servlet class and in our example our Servlet class is named decodejava.MyServlet1.
Note
The child tag <filter-name> of <filter> tag is matched with the <filter-name> child tag of
<filter-mapping>. The
<url-pattern> child tag of <filter-mapping>should be the same
as the <url-pattern> for our servlet i.e. MyServ.
The child tag <servlet-name> of <servlet> tag is matched with the <servlet-name> child tag of
<servlet-mapping>. The
<url-pattern> child tag is used to specify the URL to access Servlet and we have named this URL MyServ.
Setting the classpath
Much of the support for developing the web applications based on the Java Servlet technology does not come with the core Java.
Hence, in order to compile the Servlet programs, we have to set the classpath to a jar file named
servlet-api.jar.
This jar file provides all the classes that are required for the Servlet programming and it comes within the lib Folder of
Tomcat installation folder.
For example, in our case we have installed Tomcat Web Server within the C: Drive, hence the path to our lib folder containing the servlet-api.jar is - C:\apache-tomcat-9.0.2\lib
There are two ways to set the classpath -
You could set the classpath by entering this command at the Command Prompt, but this only temporarily sets the classpath to the path of servlet-api.jar file. If you restart your system, you will have to set the classpath again.
set classpath=C:\apache-tomcat-9.0.2\lib\servlet-api.jar
In order to set the classpath permanently, you need to set your classpath system variables. A simple tutorial on how to permanently set the classpath system variables, you may read
How to permanently set the classpath system variable
Compiling the Servlet class
After setting the classpath, you need to compile the filter and the Servlet class by entering the command at the folder where you've stored the Servlet class file.
First we execute the webpage containing the form, asking the user to enter the name, city and press the submit button. Let's say this user does not enter the name and submits the form as shown below.
On submitting the form, three activities takes place in the following order -
The requested servlet is called
but before this Servlet is executed, a filter associated with this Servlet will be executed, to filter the user request.
This Filter calls the ServletRequestWrapper class, which checks if the user has entered his name in form or not. If not, an appropriate message is displayed
Finally, the request Servlet is executed.
Hence, because the user did not enter the name, hence the following messages are displayed to the user.
To see the workflow of this web application or how the classes were called, please take a look at the Tomcat Web Server window. This proves the order of
operations we described earlier.
These messages are displayed in Tomcat window due to the call of System.out.println() method in Filter, Wrapper and Servlet class.
Finally, let's see what happens if the user enters his name and city on the form and submits it.
As user entered the name and city, hence a personalised welcome message is displayed to the user.