What Is A Servlet?
What Is A Servlet?
What Is A Servlet?
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?
Servlet can be described in many ways, depending on the context.
Disadvantages of CGI
There are many problems in CGI technology:
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:
HTTP is TCP/IP based communication protocol, which is used to deliver the data like
image files, query results, HTML files etc on the World Wide Web (WWW) with the
default port is TCP 80. It provides the standardized way for computers to
communicate with each other.
HTTP Requests
The request sent by the computer to a web server, contains all sorts of potentially
interesting information; it is known as HTTP requests.
The HTTP client sends the request to the server in the form of request message which
includes following information:
o The Request-line
o The analysis of source IP address, proxy and port
o The analysis of destination IP address, protocol, port and host
o The Requested URI (Uniform Resource Identifier)
o The Request method and Content
o The User-Agent header
o The Connection control header
o The Cache control header
The HTTP request method indicates the method to be performed on the resource
identified by the Requested URI (Uniform Resource Identifier). This method is
case-sensitive and should be used in uppercase.
1) In case of Get request, only limited In case of post request, large amount
amount of data can be sent because data of data can be sent because data is
is sent in header. sent in body.
2) Get request is not secured because data Post request is secured because data
is exposed in URL bar. is not exposed in URL bar.
5) Get request is more efficient and used Post request is less efficient and used
more than Post. less than get.
1. GET/RegisterDao.jsp?name1=value1&name2=value2
As we know that data is sent in request header in case of get request. It is the default
request type. Let's see what information is sent to the server.
POST/RegisterDao.jsp HTTP/1.1
Host: www. javatpoint.com
name1=value1&name2=value2
As we know, in case of post request original data is sent in message body. Let's see
how information is passed to the server in case of post request.
Servlet Container
It provides the runtime environment for JavaEE (j2ee) applications. The client/user
can request only a static WebPages from the server. If the user wants to read the web
pages as per input then the servlet container is used in java.
The servlet container is the part of web server which can be run in a separate
process. We can classify the servlet container states in three types:
The servlet container is the part of web server which can be run in a separate
process. We can classify the servlet container states in three types:
The Servlet Container performs many operations that are given below:
Web Server
Web server contains only web or servlet container. It can be used for servlet, jsp,
struts, jsf etc. It can't be used for EJB.
It is a computer where the web content can be stored. In general web server can be
used to host the web sites but there also used some other web servers also such as
FTP, email, storage, gaming etc.
o If the requested web page at the client side is not found, then web server will
sends the HTTP response: Error 404 Not found.
o When the web server searching the requested page if requested page is found
then it will send to the client with an HTTP response.
o If the client requests some other resources then web server will contact to
application server and data is store for constructing the HTTP response.
Application Server
Application server contains Web and EJB containers. It can be used for servlet, jsp,
struts, jsf, ejb etc. It is a component based product that lies in the middle-tier of a
server centric architecture.
It provides the middleware services for state maintenance and security, along with
persistence and data access. It is a type of server designed to install, operate and
host associated services and applications for the IT services, end users and
organizations.
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)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)
Servlet Interface
Servlet interface provides commonbehaviorto all the servlets.Servlet interface
defines methods that all servlets must implement.
Servlet interface needs to be implemented for creating any servlet (either directly or
indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to
service the requests, and to destroy the servlet and 2 non-life cycle methods.
Method Description
public void init(ServletConfig config) initializes the servlet. It is the life cycle
method of servlet and invoked by the
web container only once.
File: First.java
import java.io.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");
}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}
Here, we are going to use apache tomcat server in this example. The steps are as
follows:
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
{
res.setContentType("text/html");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
The web container uses the Parser to get the information from the web.xml file. There
are many xml parsers such as SAX, DOM and Pull.
There are many elements in the web.xml file. Here is given some necessary elements
to run the simple servlet program.
web.xml file
<web-app>
<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to invoke the
servlet.
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.
Method Description
public abstract String Returns the host name of the server that
getServerName() received the request.
index.html
<form action="DemoServ" method="get">
Enter your name<input type="text" name="name"><br>
<input type="submit" value="login">
</form>
DemoServ.java
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class DemoServ extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();
pw.close();
}}
RequestDispatcher in Servlet
The Request Dispatcher 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 can see in the above figure, response of second servlet is included in the response of
to the client.
index.html
<form action="Login" method="post">
Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPass"/><br/>
<input type="submit" value="login"/>
</form>
Login.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("userPass");
if(p.equals("servlet"){
RequestDispatcher rd=request.getRequestDispatcher("WelcomeServlet");
rd.forward(request, response);
}
else{
out.print("Sorry UserName or Password Error!");
RequestDispatcher rd=request.getRequestDispatcher("/index.html");
rd.include(request, response);
}
}
WelcomeServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class WelcomeServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse response)
8. throws ServletException, IOException {
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. String n=request.getParameter("userName");
14. out.print("Welcome "+n);
15. }
16.
17.}
web.xml
1. <web-app>
2. <servlet>
3. <servlet-name>Login</servlet-name>
4. <servlet-class>Login</servlet-class>
5. </servlet>
6. <servlet>
7. <servlet-name>WelcomeServlet</servlet-name>
8. <servlet-class>WelcomeServlet</servlet-class>
9. </servlet>
10.
11.
12. <servlet-mapping>
13. <servlet-name>Login</servlet-name>
14. <url-pattern>/Login</url-pattern>
15. </servlet-mapping>
16. <servlet-mapping>
17. <servlet-name>WelcomeServlet</servlet-name>
18. <url-pattern>/WelcomeServlet</url-pattern>
19. </servlet-mapping>
20.
21. <welcome-file-list>
22. <welcome-file>index.html</welcome-file>
23. </welcome-file-list>
24.</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 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.
Difference between forward() and sendRedirect()
forward() method sendRedirect() method
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
Example: Example:
request.getRequestDispacher("servlet2").forward(request,response);
response.sendRedirect("servlet2");
method
There are many differences between the forward() method of RequestDispatcher and
sendRedirect() method of HttpServletResponse interface. They are given below:
sendRedirect method works at client side, that is why we can our request to
anywhere. We can send our request within and outside the server.
DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.sendRedirect("http://www.google.com");
pw.close();
}}
index.html
<html>
<head>
<title>sendRedirect example</title>
</head>
<body>
<form action="MySearcher">
<input type="text" name="name">
<input type="submit" value="Google Search">
</form>
</body>
</html>
MySearcher.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
String name=request.getParameter("name");
response.sendRedirect("https://www.google.co.in/#q="+name);
}
}
Session Tracking in Servlets
Session simply means a particular interval of time.
HTTP is stateless that means each request is considered as the new request. It is
shown in the figure given below:
Why use Session Tracking?
To recognize the user It is used to recognize the particular user.
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.
How Cookie works
By default, each request is considered as a new request. In cookies technique, we add
cookie with response from the servlet. So cookie is stored in the cache of the browser.
After that if request is sent by the user, cookie is added with request by default. Thus,
we recognize the user as the old user.
Types of Cookie
There are 2 types of cookies in servlets.
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.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It
provides a lot of useful methods for cookies.
Constructor of Cookie class
Constructor Description
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
public String getName() Returns the name of the cookie. The name cannot
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++){
out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of c
ookie
}
Simple example of Servlet Cookies
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
1. <form action="servlet1" method="post">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>
servlet1.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class servlet1 extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. Cookie ck=new Cookie("uname",n);//creating cookie object
18. response.addCookie(ck);//adding cookie in the response
19.
20. //creating submit button
21. out.print("<form action='servlet2'>");
22. out.print("<input type='submit' value='go'>");
23. out.print("</form>");
24.
25. out.close();
26.
27. }catch(Exception e){System.out.println(e);}
28. }
29.}
Servlet2.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class servlet2 extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse response){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. Cookie ck[]=request.getCookies();
14. out.print("Hello "+ck[0].getValue());
15.
16. out.close();
17.
18. }catch(Exception e){System.out.println(e);}
19. }
20.
21.
22.}
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>servlet1</servlet-name>
5. <servlet-class>servlet1</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>servlet1</servlet-name>
10.<url-pattern>/servlet1</url-pattern>
11.</servlet-mapping>
12.
13.<servlet>
14.<servlet-name>servlet2</servlet-name>
15.<servlet-class>servlet2</servlet-class>
16.</servlet>
17.
18.<servlet-mapping>
19.<servlet-name>servlet2</servlet-name>
20.<url-pattern>/servlet2</url-pattern>
21.</servlet-mapping>
22.
23.</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.
1. index.html
2. link.html
3. login.html
4. LoginServlet.java
5. LogoutServlet.java
6. ProfileServlet.java
7. web.xml
<html>
<head>
<title>Servlet Login Example</title>
</head>
<body>
<h1>Welcome to Login App by Cookie</h1>
<a href="login.html">Login</a>|
<a href="LogoutServlet">Logout</a>|
<a href="ProfileServlet">Profile</a>
</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 respo
nse)
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 respo
nse)
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 respo
nse)
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>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>
Hidden Form Field
In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining
the state of an user.
In such case, we store the information in the hidden field and get it from another
servlet. This approach is better if we have to submit form in all the pages and we
don't want to depend on the browser.
Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.
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.*;
String n=request.getParameter("userName");
out.print("Welcome "+n);
}catch(Exception e){System.out.println(e);}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
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:
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);}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
1.
<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.
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
<html>
<head>
<title>Servlet Login Example</title>
</head>
<body>
<h1>Login App using HttpSession</h1>
<a href="login.html">Login</a>|
<a href="LogoutServlet">Logout</a>|
<a href="ProfileServlet">Profile</a>
</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
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 respo
nse)
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 res
ponse)
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 respo
nse)
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
<?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>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>