Servlets Advance Java by Biswajit Saha
Servlets Advance Java by Biswajit Saha
Servlet technology is used to create a web application (resides at server side and generates a dynamic web page).
Servlet technology is robust and scalable because of java language. Before Servlet, CGI (Common Gateway Interface)
scripting language was common as a server-side programming language. However, there were many disadvantages to this
technology. We have discussed these disadvantages below.
There are many interfaces and classes in the Servlet API such as Servlet, GenericServlet, HttpServlet, ServletRequest,
ServletResponse, etc.
What is a Servlet?
A web application is an application accessible from the web. A web application is composed of web components like Servlet,
JSP, Filter, etc. and other elements such as HTML, CSS, and JavaScript. The web components typically execute in Web Server
and respond to the HTTP request.
CGI technology enables the web server to call an external program and pass HTTP request information to the external
program to process the request. For each request, it starts a new process.
Disadvantages of CGI
1. If the number of clients increases, it takes more time for sending the response.
2. For each request, it starts a process, and the web server is limited to start processes.
3. It uses platform dependent language e.g. C, C++, perl.
Advantages of Servlet
There are many advantages of Servlet over CGI. The web container creates threads for handling the multiple requests to the
Servlet. Threads have many benefits over the Processes such as they share a common memory area, lightweight, cost of
communication between the threads are low. The advantages of Servlet are as follows:
1. Better performance: because it creates a thread for each request, not process.
2. Portability: because it uses Java language.
3. Robust: JVM manages Servlets, so we don't need to worry about the memory leak, garbage collection, etc.
4. Secure: because it uses java language.
Servlet API
The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
The javax.servlet package contains many interfaces and classes that are used by the servlet or web container. These are not
specific to any protocol.
The javax.servlet.http package contains interfaces and classes that are responsible for http requests only.
1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener
12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener
1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException
1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
GenericServlet class
GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It provides the implementation of all
the methods of these interfaces except the service method.
You may create a generic servlet by inheriting the GenericServlet class and providing the implementation of the service
method.
HttpServlet class
The HttpServlet class extends the GenericServlet class and implements Serializable interface. It provides http specific
methods such as doGet, doPost, doHead, doTrace etc.
1. public void service(ServletRequest req,ServletResponse res) dispatches the request to the protected service
method by converting the request and response object into http type.
2. protected void service(HttpServletRequest req, HttpServletResponse res) receives the request from the service
method, and dispatches the request to the doXXX() method depending on the incoming http request type.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the GET request. It is invoked
by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the POST request. It is
invoked by the web container.
5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles the HEAD request. It is
invoked by the web container.
6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles the OPTIONS request. It
is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the PUT request. It is invoked
by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles the TRACE request. It is
invoked by the web container.
9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles the DELETE request. It is
invoked by the web container.
Life Cycle of a Servlet (Servlet Life Cycle)
The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the servlet:
As displayed in the above diagram, there are three states of a servlet: new, ready and end. The servlet is in new state if servlet
instance is created. After invoking the init() method, Servlet comes in the ready state. In the ready state, servlet performs all
the tasks. When the web container invokes the destroy() method, it shifts to the end state.
The classloader is responsible to load the servlet class. The servlet class is loaded when the first request for the servlet is
received by the web container.
The web container creates the instance of a servlet after loading the servlet class. The servlet instance is created only once in
the servlet life cycle.
The web container calls the service method each time when request for the servlet is received. If servlet is not initialized, it
follows the first three steps as described above then calls the service method. If servlet is initialized, it calls the service
method. Notice that servlet is initialized only once. The syntax of the service method of the Servlet interface is given below:
The web container calls the destroy method before removing the servlet instance from the service. It gives the servlet an
opportunity to clean up any resource for example memory, thread etc. The syntax of the destroy method of the Servlet
interface is given below:
The HttpServlet class is widely used to create the servlet because it provides methods to handle http requests such as
doGet(), doPost, doHead() etc.
In this example we are going to create a servlet that extends the HttpServlet class. In this example, we are inheriting
the HttpServlet class and providing the implementation of the doGet() method. Notice that get request is the default
request.
DemoServlet.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServlet extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
The server checks if the servlet is requested for the first time.
else
The web container calls the destroy method when it needs to remove the servlet such as at time of stopping server or
undeploying the project.
welcome-file-list in web.xml
The welcome-file-list element of web-app, is used to define a list of welcome files. Its sub element is welcome-file that is
used to define the welcome file.
A welcome file is the file that is invoked automatically by the server, if you don't specify any file name.
1. welcome-file-list in web.xml
2. index.html
3. index.htm
4. index.jsp
If you have specified welcome-file in web.xml, and all the files index.html, index.htm and index.jsp exists, priority goes to
welcome-file.
If welcome-file-list entry doesn't exist in web.xml file, priority goes to index.html file then index.htm and at last index.jsp file.
ServletRequest Interface
An object of ServletRequest is used to provide the client request information to a servlet such as content type, content
length, parameter names and values, header informations, attributes etc.
There are many methods defined in the ServletRequest interface. Some of them are as follows:
Method Description
public String getParameter(String name) is used to obtain the value of a parameter by name.
public String[] getParameterValues(String returns an array of String containing all values of given parameter
name) name. It is mainly used to obtain values of a Multi select list box.
public int getContentLength() Returns the size of the request entity data, or -1 if not known.
public String getCharacterEncoding() Returns the character set encoding for the input of this request.
public String getContentType() Returns the Internet Media Type of the request entity data, or null
if not known.
public ServletInputStream getInputStream() Returns an input stream for reading binary data in the request
throws IOException body.
public abstract String getServerName() Returns the host name of the server that received the request.
public int getServerPort() Returns the port number on which this request was received.
RequestDispatcher in Servlet
The RequestDispatcher interface provides the facility of dispatching the request to another resource it may be html, servlet
or jsp. This interface can also be used to include the content of another resource also. It is one of the way of servlet
collaboration.
As you see in the above figure, response of second servlet is sent to the client. Response of the first servlet is not displayed
to the user.
As you can see in the above figure, response of second servlet is included in the response of the first servlet that is
being sent to the client.
The getRequestDispatcher() method of ServletRequest interface returns the object of RequestDispatcher. Syntax:
In this example, we are validating the password entered by the user. If password is servlet, it will forward the request to the
WelcomeServlet, otherwise will show an error message: sorry username or password error!. In this program, we are cheking
for hardcoded information. But you can check it to the database also that we will see in the development chapter. In this
example, we have created following files:
Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
}
web.xml
<web-app>
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>Login</servlet-class>
</servlet>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
SendRedirect in servlet
The sendRedirect() method of HttpServletResponse interface can be used to redirect response to another resource, it may
be servlet, jsp or html file.It accepts relative as well as absolute URL.It works at client side because it uses the url bar of the
browser to make another request. So, it can work inside and outside the server.
The forward() method works at server side. The sendRedirect() method works at
client side.
It sends the same request and response objects to another servlet. It always sends a new request.
It can work within the server only. It can be used within and outside the
server.
Example: Example:
request.getRequestDispacher("servlet2").forward(request,response); response.sendRedirect("servlet2");
Syntax of sendRedirect() method
public void sendRedirect(String URL)throws IOException;
DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.sendRedirect("http://www.google.com");
pw.close();
}}
ServletConfig Interface
An object of ServletConfig is created by the web container for each servlet. This object can be used to get configuration
information from web.xml file.
If the configuration information is modified from the web.xml file, we don't need to change the servlet. So it is easier to
manage the web application if any specific content is modified from time to time.
Advantage of ServletConfig
The core advantage of ServletConfig is that you don't need to edit the servlet file if information is modified from the web.xml
file.
ServletConfig config=getServletConfig();
The init-param sub-element of servlet is used to specify the initialization parameter for a servlet.
<web-app>
1. <servlet>
2. ......
3.
4. <init-param>
5. <param-name>parametername</param-name>
6. <param-value>parametervalue</param-value>
7. </init-param>
8. ......
9. </servlet>
10. </web-app>
In this example, we are getting the one initialization parameter from the web.xml file and printing this information in the
servlet.
DemoServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class DemoServlet extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse response)
7. throws ServletException, IOException {
8.
9. response.setContentType("text/html");
10. PrintWriter out = response.getWriter();
11.
12. ServletConfig config=getServletConfig();
13. String driver=config.getInitParameter("driver");
14. out.print("Driver is: "+driver);
15.
16. out.close();
17. }
18.
19. }
web.xml
<web-app>
<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
</web-app>
ServletContext Interface
If any information is shared to many servlet, it is better to provide it from the web.xml
file using the <context-param> element.
Advantage of ServletContext
Easy to maintain if any information is shared to all the servlet, it is better to make it
available for all the servlet. We provide this information from the web.xml file, so if the
information is changed, we don't need to modify the servlet. Thus it removes
maintenance problem.
There can be a lot of usage of ServletContext object. Some of them are as follows:
1. public String getInitParameter(String name):Returns the parameter value for the specified parameter
name.
2. public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters.
3. public void setAttribute(String name,Object object):sets the given object in the application scope.
4. public Object getAttribute(String name):Returns the attribute for the specified name.
5. public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters as an Enumeration of String objects.
6. public void removeAttribute(String name):Removes the attribute with the given name from the servlet
context.
<web-app>
......
<context-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</context-param>
......
</web-app>
DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
pw.close();
}}
web.xml
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>
Attribute in Servlet
An attribute in servlet is an object that can be set, get or removed from one of the following scopes:
1. request scope
2. session scope
3. application scope
The servlet programmer can pass informations from one servlet to another using attributes. It is just like passing object from
one class to another so that we can reuse the same object again and again.
1. public void setAttribute(String name,Object object):sets the given object in the application scope.
2. public Object getAttribute(String name):Returns the attribute for the specified name.
3. public Enumeration getInitParameterNames():Returns the names of the context's initialization
parameters as an Enumeration of String objects.
4. public void removeAttribute(String name):Removes the attribute with the given name from the servlet
context.
Example of ServletContext to set and get attribute
In this example, we are setting the attribute in the application scope and getting that value from another servlet.
DemoServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet1 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletContext context=getServletContext();
context.setAttribute("company","IBM");
}catch(Exception e){out.println(e);}
}}
DemoServlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet2 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletContext context=getServletContext();
String n=(String)context.getAttribute("company");
out.println("Welcome to "+n);
out.close();
}catch(Exception e){out.println(e);}
}}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>DemoServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>DemoServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
ServletConfig ServletContext
ServletConfig is servlet specific ServletContext is for whole application
Each servlet has got its own ServletContext object is only one and used
ServletConfig object. by different servlets of the application.
Session Tracking is a way to maintain state (data) of an user. It is also known as session management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time user requests to the
server, server treats the request as the new request. So we need to maintain the state of an user to recognize to particular
user.
HTTP is stateless that means each request is considered as the new request. It is shown in the figure given below:
1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age,
and a version number.
Types of Cookie
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It is removed only if user logout
or signout.
Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.
Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of useful methods for cookies.
Cookie(String name, String value) constructs a cookie with a specified name and value.
There are given some commonly used methods of the Cookie class.
Method Description
public void setMaxAge(int expiry) Sets the maximum age of the cookie in seconds.
public String getName() Returns the name of the cookie. The name cannot be changed after creation.
Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
4. }
In this example, we are storing the name of the user in the cookie object and accessing it in another servlet. As we know well
that session corresponds to the particular user. So if you access it from too many browsers with different values, you will get
the different value.
index.html
<form action="servlet1" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());
out.close();
}catch(Exception e){System.out.println(e);}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
Servlet Login and Logout Example using Cookies
A cookie is a kind of information that is stored at client side.
In the previous page, we learned a lot about cookie e.g. how to create cookie, how to delete cookie, how to get cookie etc.
Here, we are going to create a login and logout example using servlet cookies.
In this example, we are creating 3 links: login, logout and profile. User can't go to profile page until he/she is logged in. If
user is logged out, he need to login again to visit profile.
242.2K
1. index.html
2. link.html
3. login.html
4. LoginServlet.java
5. LogoutServlet.java
6. ProfileServlet.java
7. web.xml
File: index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Servlet Login Example</title>
</head>
<body>
</body>
</html>
File: link.html
<a href="login.html">Login</a> |
<a href="LogoutServlet">Logout</a> |
<a href="ProfileServlet">Profile</a>
<hr>
File: login.html
<form action="LoginServlet" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>
File: LoginServlet.java
package com.javatpoint;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
String name=request.getParameter("name");
String password=request.getParameter("password");
if(password.equals("admin123")){
out.print("You are successfully logged in!");
out.print("<br>Welcome, "+name);
out.close();
}
File: LogoutServlet.java
package com.javatpoint;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
File: ProfileServlet.java
package com.javatpoint;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ProfileServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
Cookie ck[]=request.getCookies();
if(ck!=null){
String name=ck[0].getValue();
if(!name.equals("")||name!=null){
out.print("<b>Welcome to Profile</b>");
out.print("<br>Welcome, "+name);
}
}else{
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request, response);
}
out.close();
}
}
File: web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>com.javatpoint.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>ProfileServlet</display-name>
<servlet-name>ProfileServlet</servlet-name>
<servlet-class>com.javatpoint.ProfileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ProfileServlet</servlet-name>
<url-pattern>/ProfileServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>LogoutServlet</display-name>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.javatpoint.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
</web-app>
3)URL Rewriting
In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next resource. We can send parameter
name/value pairs using the following format:
url?name1=value1&name2=value2&??
A name and a value is separated using an equal = sign, a parameter name/value pair is separated from another parameter
using the ampersand(&). When the user clicks the hyperlink, the parameter name/value pairs will be passed to the server.
From a Servlet, we can use getParameter() method to obtain a parameter value.
In this example, we are maintaning the state of the user using link. For this purpose, we are appending the name of the user
in the query string and getting the value from the query string in another page.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.close();
}catch(Exception e){System.out.println(e);}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
HttpSession interface
In such case, container creates a session id for each user.The container uses this id to identify the particular user.An object of
HttpSession can be used to perform two tasks:
1. bind objects
2. view and manipulate information about a session, such as the session identifier, creation time, and last accessed
time.
How to get the HttpSession object ?
The HttpServletRequest interface provides two methods to get the object of HttpSession:
1. public HttpSession getSession():Returns the current session associated with this request, or if the request does
not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current HttpSession associated with this request or,
if there is no current session and create is true, returns a new session.
In this example, we are setting the attribute in the session scope in one servlet and getting that value from the session scope
in another servlet. To set the attribute in the session scope, we have used the setAttribute() method of HttpSession interface
and to get the attribute, we have used the getAttribute method.
index.html
<form action="servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href='servlet2'>visit</a>");
out.close();
}catch(Exception e){System.out.println(e);}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
1. }
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
In the previous page, we have learnt about what is HttpSession, How to store and get data from session object etc.
Here, we are going to create a real world login and logout application without using database code. We are assuming that
password is admin123.1
In this example, we are creating 3 links: login, logout and profile. User can't go to profile page until he/she is logged in. If
user is logged out, he need to login again to visit profile.
1. index.html
2. link.html
3. login.html
4. LoginServlet.java
5. LogoutServlet.java
6. ProfileServlet.java
7. web.xml
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Servlet Login Example</title>
</head>
<body>
</body>
</html>
File: link.html
<a href="login.html">Login</a> |
<a href="LogoutServlet">Logout</a> |
<a href="ProfileServlet">Profile</a>
<hr>
File: login.html
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
String name=request.getParameter("name");
String password=request.getParameter("password");
if(password.equals("admin123")){
out.print("Welcome, "+name);
HttpSession session=request.getSession();
session.setAttribute("name",name);
}
else{
out.print("Sorry, username or password error!");
request.getRequestDispatcher("login.html").include(request, response);
}
out.close();
}
}
File: LogoutServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LogoutServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession();
session.invalidate();
out.close();
}
}
File: ProfileServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class ProfileServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession(false);
if(session!=null){
String name=(String)session.getAttribute("name");
File: web.xml
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>ProfileServlet</display-name>
<servlet-name>ProfileServlet</servlet-name>
<servlet-class>ProfileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ProfileServlet</servlet-name>
<url-pattern>/ProfileServlet</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>LogoutServlet</display-name>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/LogoutServlet</url-pattern>
</servlet-mapping>
</web-app>
A filter is an object that is invoked at the preprocessing and postprocessing of a request.
It is mainly used to perform filtering tasks such as conversion, logging, compression, encryption and decryption, input
validation etc.
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove the entry of filter from the web.xml
file, filter will be removed automatically and we don't need to change the servlet.
29.8M
602
HTML Tutorial
Note: Unlike Servlet, One filter doesn't have dependency on another filter.
Usage of Filter
o recording all incoming requests
o logs the IP addresses of the computers from which the requests originate
o conversion
o data compression
o encryption and decryption
o input validation etc.
Advantage of Filter
1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance
Filter API
Like servlet filter have its own API. The javax.servlet package contains the three interfaces of Filter API.
1. Filter
2. FilterChain
3. FilterConfig
1) Filter interface
For creating any filter, you must implement the Filter interface. Filter interface provides the life cycle methods for a filter.
Method Description
public void init(FilterConfig config) init() method is invoked only once. It is used to initialize the
filter.
public void doFilter(HttpServletRequest doFilter() method is invoked every time when user request
request,HttpServletResponse response, FilterChain to any resource, to which the filter is mapped.It is used to
chain) perform filtering tasks.
public void destroy() This is invoked only once when filter is taken out of the
service.
2) FilterChain interface
The object of FilterChain is responsible to invoke the next filter or resource in the chain.This object is passed in the doFilter
method of Filter interface.The FilterChain interface contains only one method:
1. public void doFilter(HttpServletRequest request, HttpServletResponse response): it passes the control to the
next filter or resource.
We can define filter same as servlet. Let's see the elements of filter and filter-mapping.
1. <web-app>
2.
3. <filter>
4. <filter-name>...</filter-name>
5. <filter-class>...</filter-class>
6. </filter>
7.
8. <filter-mapping>
9. <filter-name>...</filter-name>
10. <url-pattern>...</url-pattern>
11. </filter-mapping>
12.
13. </web-app>
For mapping filter we can use, either url-pattern or servlet-name. The url-pattern elements has an advantage over servlet-
name element i.e. it can be applied on servlet, JSP or HTML.
In this example, we are simply displaying information that filter is invoked automatically after the post processing of the
request.
index.html
MyFilter.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
PrintWriter out=resp.getWriter();
out.print("filter is invoked before");
HelloServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<br>welcome to servlet<br>");
web.xml
For defining the filter, filter element of web-app must be defined just like servlet.
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>
Authentication Filter
We can perform authentication in filter. Here, we are going to check to password given by the user in filter class, if given
password is admin, it will forward the request to the WelcomeAdmin servlet otherwise it will display error message.
o index.html
o MyFilter.java
o AdminServlet.java
o web.xml
index.html
<form action="servlet1">
Name:<input type="text" name="name"/><br/>
Password:<input type="password" name="password"/><br/>
</form>
MyFilter.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
PrintWriter out=resp.getWriter();
String password=req.getParameter("password");
if(password.equals("admin")){
chain.doFilter(req, resp);//sends request to next resource
}
else{
out.print("username or password error!");
RequestDispatcher rd=req.getRequestDispatcher("index.html");
rd.include(req, resp);
}
}
public void destroy() {}
AdminServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("welcome ADMIN");
out.close();
}
}
web.xml
<web-app>
<servlet>
<servlet-name>AdminServlet</servlet-name>
<servlet-class>AdminServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AdminServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>
FilterConfig
An object of FilterConfig is created by the web container. This object can be used to get the configuration information from
the web.xml file.
1. public void init(FilterConfig config): init() method is invoked only once it is used to initialize the filter.
2. public String getInitParameter(String parameterName): Returns the parameter value for the specified
parameter name.
3. public java.util.Enumeration getInitParameterNames(): Returns an enumeration containing all the parameter
names.
4. public ServletContext getServletContext(): Returns the ServletContext object.
Example of FilterConfig
In this example, if you change the param-value to no, request will be forwarded to the servlet otherwise filter will create the
response with the message: this page is underprocessing. Let's see the simple example of FilterConfig. Here, we have created
4 files:
o index.html
o MyFilter.java
o HelloServlet.java
o web.xml
index.html
<a href="servlet1">click here</a>
MyFilter.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
PrintWriter out=resp.getWriter();
String s=config.getInitParameter("construction");
if(s.equals("yes")){
out.print("This page is under construction");
}
else{
chain.doFilter(req, resp);//sends request to next resource
}
}
public void destroy() {}
}
HelloServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<br>welcome to servlet<br>");
}
web.xml
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
<init-param>
<param-name>construction</param-name>
<param-value>no</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>
Simple.java
import java.io.IOException;
import java.io.PrintWriter;
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("/Simple")
public class Simple extends HttpServlet {
private static final long serialVersionUID = 1L;
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.print("<html><body>");
out.print("<h3>Hello Servlet</h3>");
out.print("</body></html>");
}
}