4servlet Development1
4servlet Development1
Java Applications
Eg:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
2|P ag e
3) Web Application
It is a three tier architecture
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
3|P ag e
4) Enterprise Application:
It is a N-Tier Architecture:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
4|P ag e
Client :
Server:
Server is a device or a computer program that accepts and responds to the request made by
other program, known as client. It is used to manage the network resources and for running the
program or software that provides services.
1. Web Server
2. Application Server
Web Server
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
5|P ag e
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.
It can respond to the client request in either of the following two possible ways:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
6|P ag e
If the requested web page at the server side is not found, then web server will sends the
HTTP response: Error 404 Not found.
When the web server searching the requested page if requested page is found then it
will send to the client with an HTTP response.
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.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
7|P ag e
Database Servers:
1) Oracle
2) MYSQL
3) MS-SQL
4) DB2
5) PostGrey
6) Informics
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
8|P ag e
It is a light weight process as only one process is created for any no of requests and
Thread to Thread communication is not expensive.
Eg:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
9|P ag e
Disadvantages of CGI
The problems with CGI/PERL were studied by Microsoft and released ASPas a
replacement to CGI.
One IIS (Internet Information Server) server software is enough to honor any number of
client requests.
It was most wanted in those days. But it comes with many drawbacks (the drawbacks of
almost every earlier Microsoft product; one product is designed to be dependable on
other Microsoft product).
Drawbacks of ASP
1. ASP works on Windows OS only. But maximum servers on Web work, even as-on-
today also, on LINUX. They placed a separate system for Windows and loaded IIS.
Now the request comes for a LINUX server, the request is routed to Windows server.
The response is routed back to client through Windows and LINUX. Routing is extra
process overhead.
2. ASP works on IIS server only, developed by Microsoft only.
3. Written in VBScript, another Microsoft product.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
10 | P a g e
These drawbacks were fully overcome in Servlets. Servlets come with lot of advantages and
most demanded in the market as-on-today.
Advantages of Servlets
All the drawbacks of earlier technologies CGI/PRRL and ASP are overcome in Servlets.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
11 | P a g e
14. Support for Sessions. Due to stateless and connectionless HTTP protocol, the Servlets
come with its own API like HttpSession interface to support session tracking.
15. Support for new frameworks like MVC Struts and Spring. Lot of frameworks are
existing in now-a-days market that makes Servlets simple to practice.
Disadvantages of Servlets
1. You are required to know an OOPs language Java indepth. Learning Java being object-
oriented, will be cumbersome compared to object-based PERL and VBScript.
2. With complex business logic, sometimes Servlets become difficult to read and
understand for others.
3. Servlets are language dependent and should be written in Java only whereas CGI is
language independent; ofcourse, PERL is preferred mostly due to text manipulation
regular expressions.
4. Business logic and present logic should be developed together. These logics can not be
separated.
Later JSP was released by Sun Microsystems. JSP is still easier than Servlets. Infact, JSP is
internally converted to a Servlet and executed.
With JSP we can separate the presentation logic from business logic.
Advantage 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 a lot of benefits over the Processes such as
they share a common memory area, lightweight, cost of communication between the threads
are low. The basic benefits 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: Servlets are managed by JVM so we don't need to worry about memory leak,
garbage collection etc.
4. Secure: because it uses java language..
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
12 | P a g e
Servlets
What are Servlets?
Java Servlets are programs that run on a Web or Application server and act as a middle layer
between a request coming from a Web browser or other HTTP client and databases or
applications on the HTTP server.
Using Servlets, you can collect input from users through web page forms, present records from
a database or another source, and create web pages dynamically.
Java Servlets often serve the same purpose as programs implemented using the Common
Gateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.
Advantages:
Servlets execute within the address space of a Web server. It is not necessary to create a
separate process to handle each client request.
Java security manager on the server enforces a set of restrictions to protect the resources on a
server machine. So servlets are trusted.
Servlets Architecture:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
13 | P a g e
Servlets Tasks:
Read the explicit data sent by the clients (browsers). This includes an HTML form on a Web
page or it could also come from an applet or a custom HTTP client program.
Read the implicit HTTP request data sent by the clients (browsers). This includes cookies,
media types and compression schemes the browser understands, and so forth.
Process the data and generate the results. This process may require talking to a database
Send the explicit data (i.e., the document) to the clients (browsers). This document can be sent
in a variety of formats, including text (HTML or XML), binary (GIF images), Excel, etc.
Send the implicit HTTP response to the clients (browsers). This includes telling the browsers
or other clients what type of document is being returned (e.g., HTML), setting cookies and
caching parameters, and other such tasks.
===========================
apache-tomcat-8.5.39
apache.mirrors.tds.net/
apache-tomcat-8.5.39-windows-x64.zip
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
14 | P a g e
2) Environment setup:
=================
set PATH=%PATH%;%JAVA_HOME%\bin;%CATALINA_HOME%\bin
Go to system properties
Go to environment variables and add a new variable with the name JAVA_HOME and
provide variable value as C:\ "top level directory of your java install"
Go to environment variables and add a new variable with the name CATALINA_HOME
and provide variable value as C:\ "top level directory of your Tomcat install"
eg:
================================================
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
15 | P a g e
Value : C:\apache-tomcat-8.5.39
=======================================
Value :
%PATH%;C:\app\nagaswarao\product\11.2.0\dbhome_1\bin;%SystemRoot%\system32;%Syst
emRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerS
hell\v1.0\;C:\Program Files
(x86)\Skype\Phone\;%JAVA_HOME%\bin;%CATALINA_HOME%\bin
================================================
Value : %CLASSPATH%;C:\apache-tomcat-7.0.73\lib\servlet-api.jar
c:>startup
http://localhost:8080/manager/html
<role rolename="manager-gui"/>
goto
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
16 | P a g e
War file to deploy --> select browse and browse for your .war and open
click on deploy.
Step1:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
17 | P a g e
For creating a dynamic web project click on File Menu -> New -> Project..-> Web ->
dynamic web project -> write your project name e.g. test -> Finish.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
18 | P a g e
Click on “Next”
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
19 | P a g e
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
20 | P a g e
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
21 | P a g e
For Eg:
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org
/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"id="WebApp_ID"version="3.1">
<display-name>sample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Developing HelloServlet:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
22 | P a g e
LoginServlet Example:
Index.html coding :
<!DOCTYPEhtml>
<html>
<head>
<title>login form</title>
</head>
<body>
<formaction="mylogin"method="post">
User ID:<inputtype="text"name="uid"/><br/>
Password:<inputtype="password"name="pwd"/><br/>
<inputtype="submit"value="login"/>
</form>
</body>
</html>
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org
/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"id="WebApp_ID"version="3.1">
<display-name>first</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.nrit.mnrao.log.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/mylogin</url-pattern>
</servlet-mapping>
</web-app>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
23 | P a g e
Create package:
Create LoginServlet.java:
package com.nrit.mnrao.log;
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;
privatestaticfinallongserialVersionUID = 1L;
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
24 | P a g e
@Override
protectedvoid doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
resp.setContentType("text/html");
if(userId.equalsIgnoreCase("nrit") &&password.equals("java"))
{
out.println("<h1> Welcome to User"+ userId+ "</h1>" );
}
else
{
out.println("<h1>Invalid user </h1>");
}
@Override
protectedvoid doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
}
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
25 | P a g e
Click on “Next”
In below wizard select name of the project and click on “add” it moves right side
Click on “Finish”
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
26 | P a g e
Servlets Packages:
These classes implement the Java Servlet and JSP specifications, the versions are Java
Servlet 2.5 and JSP 2.1
3) public void destroy()is invoked only once and indicates that servlet is being
destroyed.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
27 | P a g e
import javax.servlet.*;
import java.io.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest req, ServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/plain");
PrintWriter out = resp.getWriter();
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
28 | P a g e
D:>testapp>notepad HelloServlet.java
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/myhello</url-pattern>
</servlet-mapping>
</web-app>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
29 | P a g e
in the above :
http browser protocol
localhost is a location where tomcat is running
hello is a name of .war file
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
30 | P a g e
===================================================================
=
HttpServlet class:
The HttpServlet class is an extension of GenericServlet that includes methods
for handling HTTP-specific data.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloServletTest extends HttpServlet
{
public void service(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>This is second example?</TITLE></HEAD>");
out.println("<BODY><H1>Hello,World!</H1><H6>Again.</H6></BODY></HTML
>");
}
}
These methods are called by the default implementation of the service() method, which figures
out what kind of request is being made and then invokes the appropriate method.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
31 | P a g e
A servlet life cycle can be defined as the entire process from its creation till the destruction.
The following are the paths followed by a servlet
The init method is designed to be called only once. It is called when the servlet is first created,
and not called again for each user request. So, it is used for one-time initializations. Such data
base connection opening, tcp sockets opening etc.
The servlet is normally created when a user first invokes a URL corresponding to the servlet,
but you can also specify that the servlet be loaded when the server is first started.
When a user invokes a servlet, a single instance of each servlet gets created, with each user
request resulting in a new thread that is handed off to doGet or doPost as appropriate. The init()
method simply creates or loads some data that will be used throughout the life of the servlet.
The service() method is the main method to perform the actual task. The servlet container (i.e.
web server) calls the service() method to handle requests coming from the client( browsers)
and to write the formatted response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and calls
service. The service() method checks the HTTP request type (GET, POST, PUT, DELETE,
etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
32 | P a g e
The service () method is called by the container and service method invokes doGet, doPost,
doPut, doDelete, etc. methods as appropriate. So you have nothing to do with service() method
but you override either doGet() or doPost() depending on what type of request you receive
from the client.
The doGet() and doPost() are most frequently used methods with in each service request. Here
is the signature of these two methods.
A GET request results from a normal request for a URL or from an HTML form that has no
METHOD specified and it should be handled by doGet() method.
A POST request results from an HTML form that specifically lists POST as the METHOD and
it should be handled by doPost() method.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
33 | P a g e
The destroy() method is called only once at the end of the life cycle of a servlet. This method
gives your servlet a chance to close database connections, halt background threads, write
cookie lists or hit counts to disk, and perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection.
publicvoid destroy()
{
// Finalization code...
}
Architecture Digram:
First the HTTP requests coming to the server are delegated to the servlet container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple threads, each
thread executing the service() method of a single instance of the servlet.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
34 | P a g e
Servlets are Java classes which service HTTP requests and implement the
javax.servlet.Servlet interface.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
35 | P a g e
counter=0;
counter++;
res.setContentType("text/html");
out.println("<HTML>");
out.println("<HEAD>");
out.println("<TITLE>Counter</TITLE>");
out.println("</HEAD>");
out.println("<BODY>");
out.println("</BODY>");
out.println("</HTML>");
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
36 | P a g e
GET method:
The GET method sends the encoded user information appended to the page request. The page
and the encoded information are separated by the ? character as follows:
http://www.gmail.com/login?uid=value1&pwd=value2
The GET method is the default method to pass information from browser to web server and it
produces a long string that appears in your browser's Location:box.
GET method is not recommended, if you have password or other sensitive information to pass
to the server.
The GET method has size limtation: only 1024 characters can be in a request string.
POST method:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
37 | P a g e
This packages the information in exactly the same way as GET methods, but instead of sending
it as a text string after ( ? ) in the URL it sends it as a separate message.
This message comes to the backend program in the form of the standard input which you can
parse and use for your processing.
Servlets handles form data parsing automatically using the following methods depending on
the situation:
getParameter():
request .getParameterValues() use this method if the parameter appears more than
once and returns multiple values, for example checkbox.
getParameterNames():use this method if you want a complete list of all parameters in
the current request.
http://localhost:8080/logonproj/mylogin?uid=mnrao&pwd=admin12345
Project Hierarchy:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
38 | P a g e
LoginForm.html :
<html>
<body>
<form action="./mylogin" method="GET">
User Id: <input type="text" name="uid">
<br/>
Password: <input type="text" name="pwd" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
39 | P a g e
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userId=request.getParameter("uid");
String password=request.getParameter("pwd");
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
40 | P a g e
else
{
out.println("<H1>Invalid Userid and password : "+userId+"</H1>");
}
}
}
Web.xml:
==========
<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/mylogin</url-pattern>
</servlet-mapping>
</web-app>
Go to tomacat manager:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
41 | P a g e
http://localhost:8080/manager/html
at bottom click on button “Browse” --- browse for loginproj.war select it and click on
“open” and then deploy.
Open another tab in browser and send following request:
http://localhost:8080/loginproj/html/LoginForm.html
Step1:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
42 | P a g e
For creating a dynamic web project click on File Menu -> New -> Project..-> Web ->
dynamic web project -> write your project name e.g. test -> Finish.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
43 | P a g e
Click on “Next”
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
44 | P a g e
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
45 | P a g e
Click on Finish:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
46 | P a g e
Index.html coding :
<!DOCTYPEhtml>
<html>
<head>
<metacharset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Hello World</h1>
</body>
</html>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
47 | P a g e
For Eg:
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org
/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"id="WebApp_ID"version="3.1">
<display-name>sample</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
LoginServlet Example:
Index.html coding :
<!DOCTYPEhtml>
<html>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
48 | P a g e
<head>
<title>login form</title>
</head>
<body>
<formaction="mylogin"method="post">
User ID:<inputtype="text"name="uid"/><br/>
Password:<inputtype="password"name="pwd"/><br/>
<inputtype="submit"value="login"/>
</form>
</body>
</html>
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org
/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"id="WebApp_ID"version="3.1">
<display-name>first</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.nrit.mnrao.log.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/mylogin</url-pattern>
</servlet-mapping>
</web-app>
Create package:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
49 | P a g e
Create LoginServlet.java:
package com.nrit.mnrao.log;
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;
privatestaticfinallongserialVersionUID = 1L;
@Override
protectedvoid doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
resp.setContentType("text/html");
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
50 | P a g e
if(userId.equalsIgnoreCase("nrit") &&password.equals("java"))
{
out.println("<h1> Welcome to User"+ userId+ "</h1>" );
}
else
{
out.println("<h1>Invalid user </h1>");
}
@Override
protectedvoid doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
}
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
51 | P a g e
Click on “Next”
In below wizard select name of the project and click on “add” it moves right side
Click on “Finish”
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
52 | P a g e
Observe the hierarchy and understand the relationship between the three (involved in
multilevel inheritance). With the observation, a conclusion can be arrived, to write a Servlet
three ways exist.
The disadvantage of the first way is, all the 5 abstract methods of the interface Servlet should
be overridden eventhough Programmer is not interested in all
A smart approach is inheriting GenericServletand overriding its only one abstract method
service(). It is enough to the programmer to override only this method. It is a callback method
(called implicitly)
extending HttpServlet( like inheriting from adapter classes) and need not to override any
methods as HttpServlet contains no abstract methods. Eventhough the HttpServlet does not
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
53 | P a g e
contain any abstract methods, it is declared as abstract class by the Designers to not to allow
the Programmer to create an object directly because a Servlet object is created by the system
(here system is Servlet Container).
1. Servlet interface
It is the super interface for the remaining two – GenericServlet and HttpServlet. It contains 5
abstract methods and all inherited by GenericServlet and HttpServlet. Programmers implement
Servlet interface who would like to develop their own container.
2. GenericServlet
It is the immediate subclass of Servlet interface. In this class, only one abstract method
service() exist. Other 4 abstract methods of Servlet interface are given implementation (given
body). Anyone who extends this GenericServlet should override service() method. It was used
by the Programmers when the Web was not standardized to HTTP protocol. It is protocol
independent; it can be used with any protocol, say, SMTP, FTP, CGI including HTTP etc.
Signature:
3. HttpServlet
When HTTP protocol was developed by W3C people to suit more Web requirements, the
Servlet designers introduced HttpServlet to suit more for HTTP protocol. HttpServlet is
protocol dependent and used specific to HTTP protocol only.
With HttpServlet extension, service() method can be replaced by doGet() or doPost() with the
same parameters of service() method.
Signature:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
54 | P a g e
Similarities :
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
55 | P a g e
CheckBoxForm.html:
<html>
<body>
<form action="./myCheckBox" method="POST" target="_blank">
<input type="checkbox" name="maths" checked="checked" /> Maths
<br/>
<input type="checkbox" name="physics" /> Physics
<br/>
Web.xml:
===========
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
56 | P a g e
<web-app>
<servlet>
<servlet-name>cb</servlet-name>
<servlet-class>CheckBoxServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>cb</servlet-name>
<url-pattern>/myCheckBox</url-pattern>
</servlet-mapping>
</web-app>
CheckBoxServlet.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
57 | P a g e
response.setContentType("text/html");
String mathsFlag=request.getParameter("maths");
String physicsFlag=request.getParameter("physics");
String chemistryFlag=request.getParameter("chemistry");
out.println("<h>"+result+"</h>");
doGet(request, response);
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
58 | P a g e
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.
It is the protocol that allows web servers and browsers to exchange data over the web.
It is a request and response protocol.
It uses the reliable TCP connections by default on TCP port 80.
It is stateless means each request is considered as the new request. In other words,
server doesn't recognize the user by default
There are three fundamental features that make the HTTP a simple and powerful protocol used
for communication:
HTTP is media independent: It refers to any type of media content can be sent by
HTTP as long as both the server and the client can handle the data content.
HTTP is connectionless: It is a connectionless approach in which HTTP client i.e., a
browser initiates the HTTP request and after the request is sends the client disconnects
from server and waits for the response.
HTTP is stateless: The client and server are aware of each other during a current
request only. Afterwards, both of them forget each other. Due to the stateless nature of
protocol, neither the client nor the server can retain the information about different
request across the web pages.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
59 | P a g e
The developer should specify to the Browser in what style the data is to be sent to the server.
The most commonly used styles and available are GET and POST. These styles are to be
written in METHOD attribute of <FORM> tag as follows. Let us see their differences and
when to use them in GET vs POST.
In GET style, the data is appended to the URL (written in action attribute in the above
statement) and sent to the server and in POST style, the client data is sent separately as
message body.
Eg:
Browser Request:
http://locahost:8080/myproject/html/Login.html
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
60 | P a g e
http://localhost:8888/myproject/login?uid=MNRAO&pwd=MNRAO12345
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
61 | P a g e
It depends on your application need. If client data includes only ASCII characters, no secrecy
and limited to 2KB length (depends on the browser), then prefer GET, else POST
ReadParams.html:
<html>
<body>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
62 | P a g e
</form>
</body>
</html>
while(paramNames.hasMoreElements())
{
String paramName = (String)paramNames.nextElement();
if (paramValue.length() == 0)
out.println("<i>No Value</i>");
else
out.println(paramValue);
}
else
{
// Read multiple valued data
out.println("<ul>");
out.println("</ul>");
}
}
out.println("</tr>\n</table>\n</body></html>");
}
Web.xml:
=======
<web-app>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
64 | P a g e
<servlet>
<servlet-name>mp</servlet-name>
<servlet-class>ReadAllParams</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mp</servlet-name>
<url-pattern>/myparams</url-pattern>
</servlet-mapping>
</web-app>
1) String getMethod()
Returns the name of the HTTP method with which this request was made, for example, GET,
POST, or PUT.
Returns the value of a request parameter as a String, or null if the parameter does not exist.
3) String[]getParameterValues(String name)
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
65 | P a g e
Returns an array of String objects containing all of the values the given request parameter has,
or null if the parameter does not exist.
4) Enumeration getParameterNames()
Returns an Enumeration of String objects containing the names of the parameters contained
in this request.
Enumerationnames = request.getParameterNames();
while(names.hasMoreElements())
{
String name = (String) names.nextElement();
out.println("param name : "+name);
5) String getQueryString()
Returns the query string that is contained in the request URL after the path.
Eg:
http://localhost:8888/myproject/login?uid=MNRAO&pwd=MNRAO12345
queryStringvalue is following.
uid=MNRAO&pwd=MNRAO12345
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
66 | P a g e
6) int getContentLength()
Returns the length, in bytes, of the request body and made available by the input stream, or -1
if the length is not known.
7) String getContentType()
Returns the MIME (Multipurpose Internet Mail Extensions) type of the body of the request (
non ASCII Chars ) , or null if the type is not known.
8) String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client,that sent the request.
9) String getRemoteHost()
Returns the fully qualified name of the client,that sent the request.
Returns the login of the user making this request, if the user has been authenticated,or null if
the user has not been authenticated.
Returns the part of this request's URL from the protocol name up to the query string in the first
line of the HTTP request.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
67 | P a g e
Eg:
http://localhost:8888/myproject/login?uid=MNRAO&pwd=MNRAO12345
url http://localhost:8888/myproject/login
uri http://localhost:8888/myproject
Returns the part of this request's URL that calls the JSP.
Returns any extra path information associated with the URL the client sent when it made this
request ( pathname inside the claees folder)
Returns the port number on which this request was received ( 8080 )
Returns the name and version of the protocol the request ( default http )
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
68 | P a g e
Returns the value of the named attribute as an Object, or null if no attribute of the given name
exists.
Returns an Enumeration containing the names of the attributes available to this request.
while(names.hasMoreElements())
{
String name = (String) names.nextElement();
out.println("param name : "+name);
String value = request.getAttribute(name);
}
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
69 | P a g e
while(names.hasMoreElements())
{
String name = (String) names.nextElement();
out.println("param name : "+name);
String value = request.getHeader (name);
}
Returns the current session associated with this request, or if the request does not have a
session, creates one.
Returns the current HttpSession associated with this request or, if there is no current session
and create is true, returns a new session.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
70 | P a g e
Returns the name of the authentication scheme used to protect the servlet, for example,
"BASIC" or "SSL," or null if the JSP was not protected.
Returns a boolean indicating whether this request was made using a secure channel, such as
HTTPS.
Returns an array containing all of the Cookie objects the client sent with this request.
Returns the preferred Locale that the client will accept content in, based on the Accept-
Language header.
Returns the name of the character encoding used in the body of this request.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
71 | P a g e
Returns the portion of the request URI that indicates the context of the request.
Request http://localhost:8888/myproject/login?uid=MNRAO&pwd=MNRAO12345
url http://localhost:8888/myproject/login
uri http://localhost:8888/myproject
conextPathmyproject/login
Content Type
Content Type is also known as MIME (Multipurpose internet Mail Extension) Type. It is a
HTTP header that provides the description about what are you sending to the browser.
MIME is an internet standard that is used for extending the limited capabilities of email by
allowing the insertion of sounds, images and text in a message.
The features provided by MIME to the email services are as given below:
There are many content types. The commonly used content types are given below:
text/html
text/plain
application/msword
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
72 | P a g e
application/vnd.ms-excel
application/jar
application/pdf
application/octet-stream
application/x-zip
images/jpeg
images/png
images/gif
audio/mp3
video/mp4
video/quicktime etc.
LoginForm.html :
=================
<html>
<body>
<form action="./mylogin" method="GET">
User Id: <input type="text" name="uid">
<br/>
Password: <input type="text" name="pwd" />
import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
out.println("<HTML>" );
out.println("<h1>");
Enumerationnames = request.getParameterNames();
while(names.hasMoreElements())
{
String name = (String) names.nextElement();
out.println("param name : "+name);
}
intlen = request.getContentLength();
out.println("Content Length :"+len);
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
74 | P a g e
intremotePort = request.getRemotePort();
out.println("Remote Port :"+remotePort);
intserverPort = request.getServerPort();
out.println("Server Port :"+serverPort);
out.println("Protocol :"+protocol);
out.println("</h1>");
out.println("</HTML>" );
O/p:
METHOD :GET
User Id : nrit
Password :java
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
75 | P a g e
Protocol :HTTP/1.1
Register Form.
register.html:
<!DOCTYPEhtml>
<html>
<head>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
76 | P a g e
<title>Register</title>
</head>
<body>
<formaction="./register"method="post">
userid<inputtype="text"name="uid"/><br/>
password <inputtype="password"name="pwd"/><br/>
Retype Password <inputtype="password"name="rpwd"/><br/>
First Name <inputtype="text"name="firstname"><br/>
Last Name <inputtype="text"name="lastname"><br/>
Birth Date <inputtype="text"name="birthdate"><br/>
Gender <inputtype="text"name="gender"><br/>
<inputtype="submit"value="Submit"/>
</form>
</body>
</html>
Web.xml:
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org
/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"id="WebApp_ID"version="3.1">
<display-name>user</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>com.nrit.user.register.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>register </servlet-name>
<url-pattern>/register </url-pattern>
</servlet-mapping>
</web-app>
RegisterServlet.java
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
77 | P a g e
package com.nrit.user.register;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
publicclassRegisterServletextends HttpServlet {
/**
*
*/
privatestaticfinallongserialVersionUID = 1L;
@Override
publicvoid init() throws ServletException {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
con.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
78 | P a g e
@Override
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
try
{
String userId = request.getParameter("uid");
String password = request.getParameter("pwd");
String retypePassword = request.getParameter("rpwd");
String firstName = request.getParameter("firstname");
String lastName = request.getParameter("lastname");
String date = request.getParameter("birthdate");
String gender = request.getParameter("gender");
if(!password.equalsIgnoreCase(retypePassword))
{
out.println("<h1>retype not matched</h1>");
return;
}
pst.setString(1, userId);
pst.setString(2, password);
pst.setString(3, firstName);
pst.setString(4, lastName);
pst.setString(5, date);
pst.setString(6, gender);
pst.executeUpdate();
out.println("<h1>Successfully Register</h1>");
con.commit();
}
catch(Exception e)
{
e.printStackTrace();
out.println("<h1>Server busy</h1>");
try {
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
79 | P a g e
con.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
@Override
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
@Override
publicvoid destroy() {
try
{
con.close();
}
catch(Exception e)
{
e.printStackTrace();
}
Login Check:
login.html:
<!DOCTYPEhtml>
<html>
<head>
<title>Login</title>
</head>
<body>
<formaction="./login"method="post">
userid<inputtype="text"name="uid"/><br/>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
80 | P a g e
password <inputtype="password"name="pwd"/><br/>
<inputtype="submit"value="Submit"/>
</form>
</body>
</html>
Web.xml:
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org
/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"id="WebApp_ID"version="3.1">
<display-name>userlogin</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.nrit.user.login.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login </servlet-name>
<url-pattern>/login </url-pattern>
</servlet-mapping>
</web-app>
LoginServlet.java
package com.nrit.user.login;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
importjava.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
81 | P a g e
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
*/
privatestaticfinallongserialVersionUID = 1L;
PreparedStatementpst = null;
@Override
publicvoid init() throws ServletException {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl", "scott", "tiger");
con.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
@Override
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
82 | P a g e
try {
pst.setString(1, userId);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
intcount = rs.getInt(1);
if (count == 1) {
out.println("<h1>Valid User </h1>");
} else {
out.println("<h1>In Valid User </h1>");
}
}
} catch (Exception e) {
e.printStackTrace();
}
@Override
protectedvoid doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
}
@Override
publicvoid destroy() {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
83 | P a g e
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.
Main purpose is to read external configuration parameters, which are changed dynamically.
Advantage of ServletConfig
The main advantage of ServletConfig is that you don't need to edit the servlet file if
information is modified from the web.xml file.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
84 | P a g e
Signature :
eg:
ServletConfig config=getServletConfig();
<web-app>
<servlet>
.....
<init-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</init-param>
......
</servlet>
</web-app>
Web.xml:
================
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
85 | P a g e
/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"id="WebApp_ID"version="3.1">
<display-name>user</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>com.nrit.user.register.RegisterServlet</servlet-class>
<init-param>
<param-name>driver</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</init-param>
<init-param>
<param-name>dbhost</param-name>
<param-value>localhost</param-value>
</init-param>
<init-param>
<param-name>port</param-name>
<param-value>1521</param-value>
</init-param>
<init-param>
<param-name>sid</param-name>
<param-value>orcl</param-value>
</init-param>
<init-param>
<param-name>uid</param-name>
<param-value>scott</param-value>
</init-param>
<init-param>
<param-name>pwd</param-name>
<param-value>tiger</param-value>
</init-param>
</servlet>
<servlet-mapping>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
86 | P a g e
<servlet-name>register </servlet-name>
<url-pattern>/register </url-pattern>
</servlet-mapping>
</web-app>
package com.nrit.user.register;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
*/
privatestaticfinallongserialVersionUID = 1L;
@Override
publicvoid init() throws ServletException {
try {
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
87 | P a g e
Class.forName(jdbcDriver);
con =
DriverManager.getConnection("jdbc:oracle:thin:@"+dbHost+":"+dbPortNum+":"+dbsid,
userId, password);
con.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
@Override
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
try
{
String userId = request.getParameter("uid");
String password = request.getParameter("pwd");
String retypePassword = request.getParameter("rpwd");
String firstName = request.getParameter("firstname");
String lastName = request.getParameter("lastname");
String date = request.getParameter("birthdate");
String gender = request.getParameter("gender");
if(!password.equalsIgnoreCase(retypePassword))
{
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
88 | P a g e
pst.setString(1, userId);
pst.setString(2, password);
pst.setString(3, firstName);
pst.setString(4, lastName);
pst.setString(5, date);
pst.setString(6, gender);
pst.executeUpdate();
out.println("<h1>Successfully Register</h1>");
con.commit();
}
catch(Exception e)
{
e.printStackTrace();
out.println("<h1>Server busy</h1>");
try {
con.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
@Override
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
89 | P a g e
ServletContext Interface
An object of ServletContext is created by the web container at time of deploying the project.
This object can be used to get context information from web.xml file. There is only one
ServletContext object per web application.
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. The object of ServletContext provides an interface between the container and servlet.
2. The ServletContext object can be used to get configuration information from the
web.xml file.
3. The ServletContext object can be used to set, get or remove attribute from the web.xml
file.
4. The ServletContext object can be used to provide inter-application communication.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
90 | P a g e
Signature:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
91 | P a g e
ServletConfig config=getServletConfig();
<web-app>
......
<context-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</context-param>
......
</web-app>
Index.html
<!DOCTYPEhtml>
<html>
<head>
<title>Register</title>
</head>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
92 | P a g e
<body>
<formaction="./register"method="post">
userid<inputtype="text"name="uid"/><br/>
password <inputtype="password"name="pwd"/><br/>
Retype Password <inputtype="password"name="rpwd"/><br/>
First Name <inputtype="text"name="firstname"><br/>
Last Name <inputtype="text"name="lastname"><br/>
Birth Date <inputtype="text"name="birthdate"><br/>
Gender <inputtype="text"name="gender"><br/>
<inputtype="submit"value="Submit"/>
</form>
</body>
</html>
Login.html
<!DOCTYPEhtml>
<html>
<head>
<title>Login</title>
</head>
<body>
<formaction="./login"method="post">
userid<inputtype="text"name="uid"/><br/>
password <inputtype="password"name="pwd"/><br/>
<inputtype="submit"value="Submit"/>
</form>
</body>
</html>
Web.xml:
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appxmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"xmlns="http://xmlns.jcp.org/xml/ns/javaee"xsi:schemaLocation="http://xmlns.jcp.org
/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd"id="WebApp_ID"version="3.1">
<display-name>user</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
93 | P a g e
<context-param>
<param-name>driver</param-name>
<param-value>oracle.jdbc.driver.OracleDriver</param-value>
</context-param>
<context-param>
<param-name>dbhost</param-name>
<param-value>localhost</param-value>
</context-param>
<context-param>
<param-name>port</param-name>
<param-value>1521</param-value>
</context-param>
<context-param>
<param-name>sid</param-name>
<param-value>orcl</param-value>
</context-param>
<context-param>
<param-name>uid</param-name>
<param-value>scott</param-value>
</context-param>
<context-param>
<param-name>pwd</param-name>
<param-value>tiger</param-value>
</context-param>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.nrit.user.register.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login </servlet-name>
<url-pattern>/login </url-pattern>
</servlet-mapping>
<servlet>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
94 | P a g e
<servlet-name>register</servlet-name>
<servlet-class>com.nrit.user.register.RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>register </servlet-name>
<url-pattern>/register </url-pattern>
</servlet-mapping>
</web-app>
RegisterServlet.java:
package com.nrit.user.register;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
publicclassRegisterServletextends HttpServlet {
/**
*
*/
privatestaticfinallongserialVersionUID = 1L;
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
95 | P a g e
@Override
publicvoid init() throws ServletException {
try {
Class.forName(jdbcDriver);
con =
DriverManager.getConnection("jdbc:oracle:thin:@"+dbHost+":"+dbPortNum+":"+dbsid,
userId, password);
con.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
@Override
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
96 | P a g e
try
{
String userId = request.getParameter("uid");
String password = request.getParameter("pwd");
String retypePassword = request.getParameter("rpwd");
String firstName = request.getParameter("firstname");
String lastName = request.getParameter("lastname");
String date = request.getParameter("birthdate");
String gender = request.getParameter("gender");
if(!password.equalsIgnoreCase(retypePassword))
{
out.println("<h1>retype not matched</h1>");
return;
}
pst.setString(1, userId);
pst.setString(2, password);
pst.setString(3, firstName);
pst.setString(4, lastName);
pst.setString(5, date);
pst.setString(6, gender);
pst.executeUpdate();
out.println("<h1>Successfully Register</h1>");
con.commit();
}
catch(Exception e)
{
e.printStackTrace();
out.println("<h1>Server busy</h1>");
try {
con.rollback();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
97 | P a g e
@Override
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
LoginServlet.java
package com.nrit.user.register;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
*/
privatestaticfinallongserialVersionUID = 1L;
@Override
publicvoid init() throws ServletException {
try {
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
98 | P a g e
Class.forName(jdbcDriver);
con =
DriverManager.getConnection("jdbc:oracle:thin:@"+dbHost+":"+dbPortNum+":"+dbsid,
userId, password);
con.setAutoCommit(false);
} catch (Exception e) {
e.printStackTrace();
}
@Override
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
try {
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
99 | P a g e
pst.setString(1, userId);
pst.setString(2, password);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
intcount = rs.getInt(1);
if (count == 1) {
out.println("<h1>Valid User </h1>");
} else {
out.println("<h1>In Valid User </h1>");
}
}
} catch (Exception e) {
e.printStackTrace();
}
@Override
protectedvoid doPost(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {
// TODO Auto-generated method stub
doGet(req, resp);
}
@Override
publicvoid destroy() {
try {
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
100 | P a g e
import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
publicclassConextInitAllParamsServletextends HttpServlet
{
publicvoid doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletContext context=getServletContext();
Enumeration<String>e=context.getInitParameterNames();
String str="";
while(e.hasMoreElements())
{
str=e.nextElement();
out.print("<br> "+context.getInitParameter(str));
}
}
Servlet Collaboration:
The Servlet collaboration is all about sharing information among the servlets. Collaborating
servlets is to pass the common information that is to be shared directly by one servlet to
another through various invocations of the methods. To perform these operations, each servlet
need to know the other servlet with which it is collaborated.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
101 | P a g e
1) Using RequestDispatcher
2) Using SendRedirect
Servlet RequestDispatcher :
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.
ServletException,
java.io.IOException
ServletException,java.io.IOException
RequestDispatcher forward()
how to pass data between two servlets (one-to-one) and for this Servlet API comes with
javax.servlet.RequestDispatcher interface.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
102 | P a g e
1. To include the response (output) of one Servlet into another (that is, client gets the
response of both Servlets).
2. To forward the client request to another Servlet to honour (that is, client calls a Servlet
but response to client is given by another Servlet).
Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given
path.
A RequestDispatcher object can be used to forward a request to the resource or to include the
resource in a response. The resource can be dynamic or static.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
103 | P a g e
Client calls a Servlet for some information. But the Servlet cannot honour the request because
it is incapable. But it knows that another Servlet exists which can do the job of the client. Then
how the first Servlet (called by the client) can send (forward) the request to another Servlet.
Here, forward() method of RequestDispatcher is used.
That is, client calls one FirstServlet but response goes from another SecondServlet. but the
client is not aware of all this transactions happening on the server.
To place (include) the response content (ouput) of one servlet into another servlet’s response.
That is here, client gets the response of both servlets. Or simply to say, to put the output of one
servlet into another.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
104 | P a g e
Observe the figure. Client request (or calls) the servlet FirstServlet .
FirstServlet sends to client its response (of FirstServlet ) and also of SecondServlet
In this example, we are validating the password entered by the user. If password is valid, 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.
LoginForm.html:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
105 | P a g e
LoginForm.html:
<formaction="./mylogin"method="post">
Name:<inputtype="text"name="uid"/><br/>
Password:<inputtype="password"name="pwd"/><br/>
<inputtype="submit"value="login"/>
</form>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
106 | P a g e
LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publicclassLoginServletextends HttpServlet
{
response.setContentType("text/html");
String userName=request.getParameter("uid");
String userPassword=request.getParameter("pwd");
if(userName.equals("MNRAO")&&userPassword.equals("java"))
{
RequestDispatcher welcomeServletRD
=request.getRequestDispatcher("mywcservlet");
welcomeServletRD.forward(request, response);
}
else
{
out.print("Sorry UserName or Password Error!");
RequestDispatcher
loginForm=request.getRequestDispatcher("/LoginForm.html");
loginForm.include(request, response);
}
}
}
WelcomeServlet.java
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
107 | P a g e
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publicclassWelcomeServletextends HttpServlet
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String userName=request.getParameter("uid");
out.print("Welcome "+userName);
}
Web.xml:
<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>wcs</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/mylogin</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>wcs</servlet-name>
<url-pattern>/mywcservlet</url-pattern>
</servlet-mapping>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
108 | P a g e
<welcome-file-list>
<welcome-file>LoginForm.html</welcome-file>
</welcome-file-list>
</web-app>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
109 | P a g e
Servlet SendRedirect :
It works at client side because it uses the url to make another request. So, it can work inside
and outside the server.
Signature :
eg:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
110 | P a g e
response.sendRedirect("http://www.google.com");
in this, we are redirecting the request to the google server. Notice that 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.
SearchForm.html:
<html>
<head><title>sendRedirect example</title></head>
<body>
<formaction="./MySearcher">
<inputtype="text"name="name">
<inputtype="submit"value="search">
</form>
</body>
</html>
SearchServlet.java:
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
publicclassSearchServletextends HttpServlet
{
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
String searchText=request.getParameter("name");
response.sendRedirect("https://www.google.co.in/#q="+searchText);
}
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
111 | P a g e
<web-app>
<servlet>
<servlet-name>search</servlet-name>
<servlet-class>SearchServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>search</servlet-name>
<url-pattern>/MySearcher</url-pattern>
</servlet-mapping>
</web-app>
RedirectServlet.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.sendRedirect("http://www.google.com");
out.close();
}
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
112 | P a g e
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
113 | P a g e
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
114 | P a g e
3. In frameworks like Struts, the Controller can decide, at the end of request processing,
which one to use of either forward or redirect operation.
4. The Controller also can decide with forward() method, to what resource the forward
should be made, depending on different conditions of client request requirements.
If you would like to forward the client request to a new resource on the same
server for further process, prefer forward() where data of the original resource
can be passed to the new resource.
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 used in java for dynamically generate the web pages on the server side.
Therefore the servlet container is the part of a web server that interacts with the servlet for
handling the dynamic web pages from the client.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
115 | P a g e
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:
Standalone: It is typical Java-based servers in which the servlet container and the web
servers are the integral part of a single program. For example:- Tomcat running by itself
In-process: It is separated from the web server, because a different program is runs
within the address space of the main server as a plug-in. For example:- Tomcat running
inside the JBoss.
Out-of-process: The web server and servlet container are different programs which are
run in a different process. For performing the communications between them, web
server uses the plug-in provided by the servlet container.
The Servlet Container performs many operations that are given below:
Servlet Attributes:
1. request scope
2. session scope
3. application scope
The servlet programmer can pass informations from one servlet to another using attributes
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
116 | P a g e
Removes the attribute with the given name from the servlet context.
Example :
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publicclassContextAttribTestServlet1extends HttpServlet
{
publicvoid doGet(HttpServletRequest req,HttpServletResponse res) throws
IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
try
{
ServletContext context=getServletContext();
context.setAttribute("name","MNRAO");
}
catch(Exception e)
{
out.println(e);
}
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publicclassContextAttribTestServlet2extends HttpServlet
{
publicvoid doGet(HttpServletRequest req,HttpServletResponse res) throws
IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
try
{
ServletContext context=getServletContext();
String myName=(String)context.getAttribute("name");
out.println("Welcome to "+myName);
out.close();
}
catch(Exception e)
{
out.println(e);
}
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
118 | P a g e
Web.xml:
<web-app>
<servlet>
<servlet-name>ca1</servlet-name>
<servlet-class>ContextAttribTestServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ca1</servlet-name>
<url-pattern>/contextattrib1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>ca2</servlet-name>
<servlet-class>ContextAttribTestServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ca2</servlet-name>
<url-pattern>/contextattrib2</url-pattern>
</servlet-mapping>
</web-app>
The servletconfig object refers to the single servlet whereas servletcontext object refers to the
whole web application.
A session refers to the entire interaction between a client and a server from the time of the
client’s first request, which generally begins the session, to the time the session is terminated.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
119 | P a g e
The session could be terminated by the client’s request, or the server could automatically close
it after a certain period of time.
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 used by client to request the server for some information over the Web. The client
establishes a connection with the server before sending a request. Over this connection only,
the server returns the response to client. When the response is delivered, the connection
between client and server is destroyed. By chance, if the same client would like to contact the
same server again, the client should establish altogether a new connection. To put in a simple
way, if the client would like to request the same server 100 times, the client should establish a
new connection 100 times as the server closes the connection for each request when the
response is delivered.
Once response is delivered, the server simply forgets the client. If the client wants the same
data, it must again establish a new connection, send request and receive response and the same
earlier process is to be repeated. For this reason, HTTP protocol is treated as stateless
protocol.
each request is treated as a separate and independent transaction that is not related at all with
any previous requests.
HTTP Protocol, which is once the most advantageous being connectionless and stateless, now
became a minus point over the time. With this nature of HTTP Protocol, it is not possible to
develop e-commerce applications where on a single connection, lot of data should be
transferred between Client and Server multiple times. To overcome this in Servlets and JSP,
there comes session, session management, session tracking etc. in Servlets.
Session begins when the client logs in to a Web site and ends when the user logs out.
Session is a conversional state between client and server and it can consists of multiple request
and response between client and server. Since HTTP and Web Server both are stateless, the
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
120 | P a g e
only way to maintain a session is when some unique information about the session (session id)
is passed between server and client in every request and response.
The interactive time between client and server on a single connection is known as a session.
(Or)
The period of time between connection establishment and connection closing between client
and server is known as a session.
(Or)
Session starts when the connection is established at both ends (client and server) and
terminates when the connection (communication) is ended (closed by server).
A connection is well maintained by the Servlet container while the client and server are
conversing back and forth in a session (with some duration).
A session includes a lot of interactions, where data will be exchanged, between client and
server, of course on a single connection. Once the server accepts the client connection, the
client and server talk together and keep with them lot of data exchanged that includes commits,
questions, answers and alike. Keeping the data of session intact (preserve) so that the data
can be reused later is known as session tracking or session management.
A session can temporarily store information related to the activities of the user while logged in.
A servlet should be capable to store temporary information pertaining to the activities of the
user in a session.
how to maintain session with HTTP protocol nature of stateless and connectionless?
The first two ways are almost discarded by the programming world as they increase lot of
network traffic and processing load of each request on the Web server.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
121 | P a g e
Container creates a session id for each user. The container uses this id to identify the particular
user
Servlet API provides Session management through HttpSession interface. We can get session
from HttpServletRequest object using following methods.
HttpSession allows us to set objects as attributes that can be retrieved in future requests.
1. HttpSession getSession() –
This method always returns a HttpSession object. It returns the session object attached
with the request, if the request has no session attached, then it creates a new session and
return it.
This method returns HttpSession object if request has session else it returns null.
Returns the time when this session was created, measured in milliseconds since
midnight January 1, 1970 GMT.
Returns the last time the client sent a request associated with this session, as the number
of milliseconds since midnight January 1, 1970 GMT.
4. int getMaxInactiveInterval():
Returns maximum inactive interval time in seconds as an int value. Inactive interval
indicates the period which the client does not do any activity on the site like adding or
deleting etc. That is, this much time in seconds, the server does not close the session
even if the client does not interact with the site.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
122 | P a g e
The inactive interval can be set by the Programmer with this method.
Binds an object to this session, using the name str. If an object of the same name is
already bound to the session, the object is replaced. str is treated as the key and value as
obj. The setAttribute() method takes always key/value pairs where key is always a
string and value can be an object of any Java class. With this method, the Programmer
can store session data with the session object.
Returns the object attached to the session on the name str which is set earlier with
setAttribute() method.
Removes the object attached with session object with the name str. If the session does
not have an object bound with the specified name, this method does nothing.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
123 | P a g e
We can bind the objects on HttpSession instance and get the objects by using setAttribute and
getAttribute methods.
Real world login and logout application without using database code
Index.html:
<!DOCTYPEhtml>
<html>
<head>
<metacharset="ISO-8859-1">
<title>Servlet Login Example</title>
</head>
<body>
<h1>Login App using HttpSession</h1>
<ahref="Login.html">Login</a>|
<ahref="logout">Logout</a>|
<ahref="profile">Profile</a>
</body>
</html>
WebLink.html:
<!DOCTYPEhtml>
<ahref="Login.html">Login</a> |
<ahref="logout">Logout</a> |
<ahref="profile">Profile</a>
<hr>
Login.html:
<formaction="login"method="post">
Name:<inputtype="text"name="uid"><br>
Password:<inputtype="password"name="pwd"><br>
<inputtype="submit"value="login">
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
124 | P a g e
</form>
Web.xml:
<web-app>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>logout</servlet-name>
<servlet-class>LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>logout</servlet-name>
<url-pattern>/logout</url-pattern>
</servlet-mapping>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
125 | P a g e
<servlet>
<servlet-name>profile</servlet-name>
<servlet-class>ProfileServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>profile</servlet-name>
<url-pattern>/profile</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
LoginServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
publicclassLoginServletextends HttpServlet
{
protectedvoid doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
126 | P a g e
PrintWriter out=response.getWriter();
RequestDispatcher linkRequestDispatcher =
request.getRequestDispatcher("WebLink.html");
linkRequestDispatcher.include(request, response);
String userName=request.getParameter("uid");
String userPassword=request.getParameter("pwd");
if(userName.equals("MNRAO")&&userPassword.equals("java"))
{
out.print("Welcome, "+userName);
HttpSession session=request.getSession();
session.setAttribute("uid",userName);
}
else
{
out.print("Sorry, username or password error!");
RequestDispatcher loginRequestDispatcher =
request.getRequestDispatcher("Login.html");
loginRequestDispatcher.include(request, response);
}
out.close();
}
LogoutServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
127 | P a g e
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
publicclassLogoutServletextends HttpServlet
{
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
RequestDispatcher
loginRequestDispatcher=request.getRequestDispatcher("WebLink.html");
loginRequestDispatcher.include(request, response);
HttpSession session=request.getSession();
session.invalidate();
out.close();
}
}
ProfileServlet.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
publicclassProfileServletextends HttpServlet
{
protectedvoid doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
128 | P a g e
RequestDispatcher
linkRequestDispatcher=request.getRequestDispatcher("WebLink.html");
linkRequestDispatcher.include(request, response);
HttpSession session=request.getSession(false);
if(session!=null)
{
String userName=(String)session.getAttribute("uid");
}
out.close();
}
}
http://localhost:8080/vrnda:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
129 | P a g e
Here :
Click on “Login”
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
130 | P a g e
Click on “Profile”
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
131 | P a g e
Click on Logout:
Cookies in Servlet:
A cookie is a small piece of information that is persisted between the multiple requests of the
client.
Servlet Cookie stores small strings of data. Cookies stay all through the session. Programmer
can store the session data with Cookie object. It is another way of tracking session data.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
132 | P a g e
Servlet Cookies are created on the server (by Servlet container) and sent to the client’s
browser for temporary storage. The cookies can be sent to and fro between client and server in
their conversation. Client is not aware of the entire process of Cookie management as
everything is done by the server and client is kept completely transparent.
The Cookie object created on the server is attached to response object and sent to client. The
Cookie carries implicitly the client information like name, path, host and connection type etc.
and the combination of this information is used by server to know cookie is coming from
which client.
Cookies are used mainly for tracking different types of client’s information. That is, the Web
server can store data on the client browser in the form of Cookie objects.
Advantage of Cookies
Disadvantage of Cookies
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
133 | P a g e
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
134 | P a g e
Keep until:
they expire: Each cookie will be removed when it reaches its expiration date, which is
set by the site that sent the cookie.
I close Firefox: The cookies that are stored on your computer will be removed when
Firefox is closed.
There are two types of cookies and they are differentiated on their life span.
Session cookies get expired and deleted from browser when the browser closes,
thereby, they do not carry any expiration time constraint parameter. They are stored
temporarily (just for the usage of session) in the RAM memory.
2. Persistent Cookies:
As the name indicates, they persist long time on the client browser. The time of
expiration can be set programmatically for each Cookie. These Cookies are stored on
hard disk. The Cookie gets deleted automatically when the time or age expires.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
135 | P a g e
Cookie is a class from javax.servlet.http package to created and handle the cookies :
Constructor:
3) void setValue(String newValue): In the previous Cookie, the value set is MNRAO.
If the user would like to modify to new values, this method is useful.
The domainName indicates the domains (servers) in which the cookie should be made
available. For example, the parameter ("www.gmail.com") is visible to server
www.gmail.com.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
136 | P a g e
path for the cookie to which the client should return the cookie. General practice is, the
cookie is returned to the same server which sent them.
The cookie is visible to all subpaths or subdirectories on the server. For example, the
path "/finance" makes cookie visible to finance directory and also all its subdirectories.
11) getPath(): Returns the path on the server to which the browser returns the cookie. For
example, /finance.
Dictates how the browser should return the cookie to server. If true, it must be secure
protocol like HTTPS (HyperText Transfer Protocol Secured) or SSL (Secured Socket
Layer). If this is not set, the default is false indicating general protocol like HHTP.
14) public int getVersion(): Returns the version of the protocol this cookie is set to work.
Returns 1 if RFC 2109 version is set or 0 when uses Netscape specifications.
15) public void setVersion(int version): Sets the version of the cookie protocol. Set with
1 if RFC 2109 is used and 0 when Netscape cookie specification is used.
16) public Object clone(): Returns a clone copy of the Cookie when the original clone()
method of Object class is overridden.
2. response.addCookie(uidCookie);
Deleting a Cookie:
2. response.addCookie(uidCookie);
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
137 | P a g e
Cookie cookies[]=request.getCookies();
for(int i=0;i<cookies.length;i++)
out.print("<br>"+cookies[i].getName()+" "+cookies[i].getValue);
Index.html:
<formaction="validate"method="post">
Name:<inputtype="text"name="uid"/><br/>
Password:<inputtype="text"name="pwd"><br/>
<inputtype="submit"value="submit">
</form>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
138 | P a g e
Web.xml:
<web-app>
<servlet>
<servlet-name>validate</servlet-name>
<servlet-class>ValidateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>validate</servlet-name>
<url-pattern>/validate</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Index.html</welcome-file>
</welcome-file-list>
</web-app>
ValidateServlet.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
139 | P a g e
if(name.equals("MNRAO") &&pass.equals("1234"))
{
Cookie ck = new Cookie("username",name);
response.addCookie(ck);
response.sendRedirect("first");
}
}
}
FirstServlet.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publicclassFirstServletextends HttpServlet
{
If the client has disabled cookies in the browser then session management using cookie wont
work. In that case URL Rewriting can be used as a backup. URL rewriting will always work.
In URL rewriting, a token(parameter) is added at the end of the URL. The token consist of
name/value pair seperated by an equal(=) sign.
For Example:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
140 | P a g e
When the User clicks on the URL having parameters, the request goes to the Web Container
with extra bit of information at the end of URL. The Web Container will fetch the extra part
of the requested URL and use it for session management.
The getParameter() method is used to get the parameter value at the server side.
Index.html:
<formaction="validate"method="post">
Name:<inputtype="text"name="uid"/><br/>
Password:<inputtype="text"name="pwd"/><br/>
<inputtype="submit"value="submit"/>
</form>
Web.xml:
<web-app>
<servlet>
<servlet-name>validate</servlet-name>
<servlet-class>ValidateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>validate</servlet-name>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
141 | P a g e
<url-pattern>/validate</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>FirstServle</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Index.html</welcome-file>
</welcome-file-list>
</web-app>
ValidateServlet:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publicclassValidateServletextends HttpServlet
{
if(name.equals("MNRAO") &&pass.equals("1234"))
{
response.sendRedirect("first?user_id="+name+"");
}
}
}
FirstServlet.java:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
142 | P a g e
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publicclassFirstServletextends HttpServlet {
Hidden form field can also be used to store session information for a particular client. In case
of hidden form field a hidden field is used to store client state. In this case user information is
stored in hidden field value and retrieved from another servlet.
Advantages :
Does not have to depend on browser whether the cookie is disabled or not.
Inserting a simple HTML Input field of type hidden is required. Hence, its easier to
implement
Disadvantage :
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
143 | P a g e
Index.htmL:
<formmethod="post"action="validate">
Name:<inputtype="text"name="uid"/><br/>
Password:<inputtype="hidden"name="pwd"value=”abc”><br/>
<inputtype="submit"value="submit">
</form>
Web.xml:
<web-app>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>second</servlet-name>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
144 | P a g e
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>second</servlet-name>
<url-pattern>/second</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
FirstServlet.java:
publicclassFirstServletextends HttpServlet
{
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
145 | P a g e
out.println("</form>");
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publicclassSecondServletextends HttpServlet
{
We can perform some important tasks at the occurrence of these exceptions, such as counting
total and current logged-in users, creating database connection object etc.
Event classes and Listener interfaces are from the javax.servlet and javax.servlet.http packages.
Event classes
1. ServletContextEvent
2. ServletContextAttributeEvent
3. HttpSessionEvent
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
146 | P a g e
4. HttpSessionBindingEvent
5. ServletRequestEvent
6. ServletRequestAttributeEvent
Listener interfaces
1. ServletContextListener
2. ServletContextAttributeListener
3. HttpSessionListener
4. HttpSessionBindingListener
5. HttpSessionAttributeListener
6. HttpSessionActivationListener
7. ServletRequestListener
8. ServletRequestAttributeListener
AppContextListener.java:
import javax.servlet.*;
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
147 | P a g e
import java.io.File;
import java.io.FileWriter;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
try
{
fout.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
148 | P a g e
try
{
fout.close();
}
catch(Exception e)
{
e.printStackTrace();
}
}
Web.xml:
<web-app>
<listener>
<listener-class>AppContextListener</listener-class>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
149 | P a g e
</listener>
<servlet>
<servlet-name>validate</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>validate</servlet-name>
<url-pattern>/validate</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>First</servlet-name>
<servlet-class>First</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>First</servlet-name>
<url-pattern>/First</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Index.html</welcome-file>
</welcome-file-list>
</web-app>
ServletContextAttributeEvent:
Methods of ServletContextAttributeListener:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
150 | P a g e
Example:
import javax.servlet.*;
publicclass AppContextAttributeListener implements
ServletContextAttributeListener
{
@Override
publicvoid attributeAdded(ServletContextAttributeEvent event)
{
// TODO Auto-generated method stub
@Override
publicvoid attributeRemoved(ServletContextAttributeEvent event)
{
String attributeName = event.getName();
Object attributeValue = event.getValue();
System.out.println("attribute removed");
System.out.println(" Name : "+attributeName);
System.out.println(" Value : "+attributeValue);
@Override
publicvoid attributeReplaced(ServletContextAttributeEvent event)
{
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
151 | P a g e
Web.xml:
<web-app>
<listener>
<listener-class>AppContextListener</listener-class>
</listener>
<listener>
<listener-class>AppContextAttributeListener</listener-class>
</listener>
<servlet>
<servlet-name>validate</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>validate</servlet-name>
<url-pattern>/validate</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>First</servlet-name>
<servlet-class>First</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>First</servlet-name>
<url-pattern>/First</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Index.html</welcome-file>
</welcome-file-list>
</web-app>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
152 | P a g e
HttpSessionListener:
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
publicclass AppClentSessionListener implements HttpSessionListener
{
@Override
publicvoid sessionCreated(HttpSessionEvent sessionEvent)
{
System.out.println("Session Created:: ID="+sessionEvent.getSession().getId());
@Override
publicvoid sessionDestroyed(HttpSessionEvent sessionEvent)
{
System.out.println("Session Destroyed:
ID="+sessionEvent.getSession().getId());
Web.xml:
<web-app>
<listener>
<listener-class>AppContextListener</listener-class>
</listener>
<listener>
<listener-class>AppContextAttributeListener </listener-class>
</listener>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
153 | P a g e
<servlet>
<listener>
<listener-class> AppClentSessionListener</listener-class>
</listener>
<servlet-name>validate</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>validate</servlet-name>
<url-pattern>/validate</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>First</servlet-name>
<servlet-class>First</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>First</servlet-name>
<url-pattern>/First</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Index.html</welcome-file>
</welcome-file-list>
</web-app>
HttpSessionAttributeListener:
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
@Override
publicvoid attributeAdded(HttpSessionBindingEvent sessionAttributeEvent)
{
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
154 | P a g e
@Override
publicvoid attributeRemoved(HttpSessionBindingEvent sessionAttributeEvent)
{
String sessionId = sessionAttributeEvent.getSession().getId();
System.out.println("Attribute removed from session Id : "+sessionId);
String name = sessionAttributeEvent.getName();
String value = (String) sessionAttributeEvent.getValue();
System.out.println("name :"+name);
System.out.println("value :"+value);
@Override
publicvoid attributeReplaced(HttpSessionBindingEvent sessionAttributeEvent)
{
String sessionId = sessionAttributeEvent.getSession().getId();
System.out.println("Attribute replaced in session Id : "+sessionId);
String name = sessionAttributeEvent.getName();
String value = (String) sessionAttributeEvent.getValue();
System.out.println("name :"+name);
System.out.println("value :"+value);
Web.xml:
<web-app>
<listener>
<listener-class>AppContextListener</listener-class>
</listener>
<listener>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
155 | P a g e
<listener-class>AppContextAttributeListener </listener-class>
</listener>
<servlet>
<listener>
<listener-class> AppClentSessionListener</listener-class>
</listener>
<listener>
<listener-class> AppClientSessionAtributeListener</listener-class>
</listener>
<servlet-name>validate</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>validate</servlet-name>
<url-pattern>/validate</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>First</servlet-name>
<servlet-class>First</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>First</servlet-name>
<url-pattern>/First</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>Index.html</welcome-file>
</welcome-file-list>
</web-app>
HttpSessionBindingListener:
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
156 | P a g e
HttpSessionBindingEvent communicates the event and identifies the session into which the
object is bound. Similarly, when an unbinding occurs (using HttpSession.removeAttribute())
HttpSessionBindingEvent communicates the event and identifies the session from which the
object is unbound.
Note, this listener will not be declared in the deployment descriptor as the same as
HttpSessionActivationListener interface. The container at runtime will introspect this object to
see if it implements the HttpSessionActivationListener and/or HttpSessionBindingListener and
fires appropriate events to the object.
These methods have a HttpSessionBindingEvent parameter that can be used to retrieve the
session that the object was bound to and the name it was given in the session.
import javax.servlet.http.HttpSessionBindingEvent;
import javax.servlet.http.HttpSessionBindingListener;
@Override
publicvoid valueBound(HttpSessionBindingEvent event)
{
System.out.println("Value Bounded to session");
String name = event.getName();
Object value = event.getValue();
System.out.println("name : "+name);
System.out.println("value : "+value);
@Override
publicvoid valueUnbound(HttpSessionBindingEvent event)
{
System.out.println("Value UnBounded to session");
String name = event.getName();
Object value = event.getValue();
System.out.println("name : "+name);
System.out.println("value : "+value);
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
157 | P a g e
ServletRequestListener:
ServletRequestEvent class gives notification about lifecycle events for a ServletRequest. The
source of the event is the ServletContext of the web application. ServletRequestListener
receives the notifications generated by ServletRequestEvent and performs some specified tasks
based on them.
As the name suggests these methods will be called when request is initialized and when it is
destroyed, hence we can use them for various purposes, like variable cleanup when request is
destroyed, or performing some initial checks when request is received etc.
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
@Override
publicvoid requestDestroyed(ServletRequestEvent event)
{
ServletRequest servletRequest = event.getServletRequest();
System.out.println("ServletRequest destroyed. Remote
IP="+servletRequest.getRemoteAddr());
@Override
publicvoid requestInitialized(ServletRequestEvent event)
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
158 | P a g e
{
ServletRequest servletRequest = event.getServletRequest();
System.out.println("ServletRequest Initialized. Remote
IP="+servletRequest.getRemoteAddr());
ServletRequestAttributeListener:
This interface is used for receiving notification events about ServletRequest attribute changes.
Notifications will be generated while the request is within the scope of the web application in
which the listener is registered. A ServletRequest has a very short lifespan. It only lives when it
enters the first servlet or filter and is destroyed when it reaches the last servlet or filter. The
ServletRequestAttributeListener can be registerd by @WebListener annotation, adding the
listener to the servlet descriptor or programmatically adding a listener with .addListener() to
the servlet context. In this example we use the @WebListener annotation.
This interface lets us listen to the following events, the names speak for themselves.
attributeAdded()
attributeRemoved()
attributeReplaced()
To register a listener we can add the @WebListener, define the listener in the servlet descriptor
(web.xml) or programatigally add it to the servlet context. In this example we choose to add
the listener through the @WebListener annotation.
import javax.servlet.*;
import javax.servlet.annotation.WebListener;
@WebListener
publicclassAppClientServletRequestAttribute implements
ServletRequestAttributeListener
{
@Override
publicvoid attributeAdded(ServletRequestAttributeEvent event)
{
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
159 | P a g e
@Override
publicvoid attributeRemoved(ServletRequestAttributeEvent event)
{
System.out.println("attribute was removed");
System.out.println("name :"+event.getName());
System.out.println( "value: " + event.getValue());
}
@Override
publicvoid attributeReplaced(ServletRequestAttributeEvent event)
{
System.out.println("attribute was replaced");
System.out.println("name :"+event.getName());
System.out.println( "value: " + event.getValue());
}
<web-app>
<listener>
<listener-class>AppClientServletRequestAttribute</listener-class>
</listener>
</web-app>
File Handling:
Sometimes, the client may ask the Servlet to send the file contents of a file existing on the
server. It is not file download. Here, the Servlet reads manually line-by-line and send each line
separately to client. Read Servlet Read text file.
TextFileSend.html:
<BODY>
<H2> Getting File contents from the Server </H2>
<FORMACTION="file"METHOD="get">
</FORM>
</BODY>
web.xml:
<web-app>
<servlet>
<servlet-name>file</servlet-name>
<servlet-class>TextFileSendServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>file</servlet-name>
<url-pattern>/file</url-pattern>
</servlet-mapping>
</web-app>
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.*;
publicclassTextFileSendServletextends HttpServlet
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
161 | P a g e
{
publicvoid doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException
{
res.setContentType("text/html");
PrintWriter pw = res.getWriter();
String str;
while( (str = br.readLine()) != null )
{
pw.println(str + "<BR>");
}
br.close();
pw.close();
}
}
Servlet Filters:
Filters are compontents that you can use and configure to perform some filtering tasks.
We can have any number of filters for pre-processing of a request and post-processing of a
response.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
162 | P a g e
When a request reaches the Web Container, it checks if any filter has URL patterns
that matches the requested URL.
The Web Container locates the first filter with a matching URL pattern and filter's
code is executed.
If another filter has a matching URL pattern, its code is then executed. This continues
until there are no filters with matching URL patterns left.
If no error occurs, the request passes to the target servlet. Hence we know, that the
request will be passed to the target servlet only when all the related Filters are
successfully executed.
The servlet returns the response back to its caller. The last filter that was applied to the
request is the first filter applied to the response.
At last the response will be passed to the Web Container which passes it to the client.
Filter API is part of Servlet API. Filter interface is found in the javax.servlet package.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
163 | P a g e
For creating a filter, we must implement Filter interface. Filter interface gives the
following life cycle methods for a filter:
3) void destroy():
invoked by the web container to indicate to a filter that it is being taken
out of service
<web-app>
<filter>
<filter-name>file</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>file</filter-name>
<url-pattern>/file</url-pattern>
(or)
<servlet-name>first</servlet-name>
</filter-mapping>
</web-app>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
164 | P a g e
In this example we are using Filter to authenticate(check correct username and password).
Here index.html will ask username and password from the user, MyFilter will validate the
password entered by the user, if the user has entered "1234" as password, then he will be
forwarded to first servlet else the index.html will be shown again to the user.
This is exactly what we used to do earlier using two servlet classes earlier, one for validation
and the other to Welcome the user. Now we will insert a Filter for validating the user.
Index.html:
<formaction="first"method="post">
Name:<inputtype="text"name="uid"/><br/>
Password:<inputtype="text"name="pwd"/><br/>
<inputtype="submit"value="submit"/>
</form>
Web.xml:
<web-app>
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
165 | P a g e
<filter-name>MyFilter</filter-name>
<servlet-name>first</servlet-name>
</filter-mapping>
<servlet>
<servlet-name>first</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
import java.io.*;
import javax.servlet.*;
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
166 | P a g e
FirstServlet.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publicclassFirstServletextends HttpServlet
{
In this example you will see how to develop a registration form in Servlet. To develop a
registration form you will need to connect your servlet application with database. Here we are
using MySQL database.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
167 | P a g e
<html>
<head>
<title>Register form</title>
</head>
<body>
<formaction="register"method="post">
Name:<inputtype="text"name="name"/><br/>
Email ID:<inputtype="text"name="email"/><br/>
Password:<inputtype="text"name="pass"/><br/>
<inputtype="submit"value="submit"/>
</form>
</body>
</html>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
168 | P a g e
RegisterServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
publicclassRegisterServletextends HttpServlet
{
PreparedStatement ps=con.prepareStatement
("insert into Student values(?,?,?)");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
inti=ps.executeUpdate();
if(i>0)
{
out.println("You are sucessfully registered");
}
}
catch(Exception se)
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
169 | P a g e
{
se.printStackTrace();
}
}
}
Web.xml:
<?xmlversion="1.0"encoding="UTF-8"?>
<web-appversion="3.0"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>RegisterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
In this example we will show you how to develop a login form using servlet. Here we are using
MySql database. List of file to be created are:
index.html
LoginServlet.java
Validate.java
WelcomeSevlet.java
web.xml
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
170 | P a g e
To try this application you will need to create a table in your database and enter some record
into it.
index.html
<html>
<head>
<title>login form</title>
</head>
<body>
<formaction="login"method="post">
Email ID:<inputtype="text"name="email"/><br/>
Password:<inputtype="text"name="pass"/><br/>
<inputtype="submit"value="login"/>
</form>
</body>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
171 | P a g e
</html>
LoginServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publicclassLoginServletextends HttpServlet
{
if(Validate.checkUser(email, pass))
{
RequestDispatcher rs = request.getRequestDispatcher("Welcome");
rs.forward(request, response);
}
else
{
out.println("Username or Password incorrect");
RequestDispatcher rs = request.getRequestDispatcher("index.html");
rs.include(request, response);
}
}
}
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
172 | P a g e
Validate.java:
import java.sql.*;
publicclassValidate
{
publicstaticboolean checkUser(String email,String pass)
{
booleanvalidity =false;
try
{
}
catch(Exception e)
{
e.printStackTrace();
}
returnvalidity;
}
}
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
173 | P a g e
WelcomeServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publicclassWelcomeServletextends HttpServlet
{
Web.xml:
<?xmlversion="1.0"encoding="UTF-8"?>
<web-
appversion="3.0"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/20
01/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>welcome</servlet-name>
<servlet-class>WelcomeServlet</servlet-class>
</servlet>
<servlet-mapping>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
174 | P a g e
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>welcome</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
In this example we will see how to send an email in Servlet application. We will be using the
JavaMail API that provides all the classes required for sending an email. JavaMail API
encapsulates two important packages javax.mail and javax.mail.internet. These packages
provide classes that can be used to send and recieve simple emails. You simply need an
Internet connection to send email using this simple Application.
index.html
<formaction="mail"method="post">
To:<inputtype="text"name="to"/><br/>
Subject:<inputtype="text"name="subject"/><br/>
Message:<inputtype="text"name="message"/><br/>
Your Email id:<inputtype="text"name="user"><br/>
Password :<inputtype="password"name="pass"/><br/>
<inputtype="submit"value="send"/>
</form>
MailAppServlet.java
import java.io.*;
import javax.servlet.*;
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
175 | P a g e
import javax.servlet.http.*;
publicclassMailAppServletextends HttpServlet
{
String to = request.getParameter("to");
String subject = request.getParameter("subject");
String message = request.getParameter("message");
String user = request.getParameter("user");
String pass = request.getParameter("pass");
SendMail.send(to,subject, message, user, pass);
out.println("Mail send successfully");
}
}
SendMail.java:
import java.util.*;
import javax.mail.*;
import javax.mail.internet.*;
publicclass SendMail
{
publicstaticvoid send(String to, String sub,
String msg, final String user,final String pass)
{
//create an instance of Properties Class
Properties props = new Properties();
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
176 | P a g e
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
try
{
Transport.send(message);
}
catch(Exception e)
{
e.printStackTrace();
}
}
}
Web.xml:
<?xmlversion="1.0"encoding="UTF-8"?>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
177 | P a g e
<web-
appversion="3.0"xmlns="http://java.sun.com/xml/ns/javaee"xmlns:xsi="http://www.w3.org/20
01/XMLSchema-instance"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<servlet>
<servlet-name>mail</servlet-name>
<servlet-class>MailAppServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>mail</servlet-name>
<url-pattern>/mail</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
In this example, we are going to improve the performance of web application to fetch records
from the database. To serve this, we are storing the data of the table in a collection, and reusing
this collection in our servlet. So, we are not directly hitting the database again and again. By
this, we are improving the performance.
To run this application, you need to create following table with some records.
"USERNAME" VARCHAR2(4000),
"USERPASS" VARCHAR2(4000),
"USEREMAIL" VARCHAR2(4000),
"USERCOUNTRY" VARCHAR2(4000),
"CONTACT" NUMBER,
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
178 | P a g e
1. index.html
2. User.java
3. MyListener.java
4. MyServlet1.java
5. MyServlet2.java
6. web.xml
1) index.html:
<ahref="servlet1">first servlet</a>|
<ahref="servlet2">second servlet</a>
2) User.java
publicclass User
{
privateintid;
private String name;
private Stringpassword;
publicint getId()
{
returnid;
}
publicvoid setId(intid) {
this.id = id;
}
public String getName() {
returnname;
}
publicvoid setName(String name) {
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
179 | P a g e
this.name = name;
}
public String getPassword() {
returnpassword;
}
publicvoid setPassword(String password) {
this.password = password;
}
3) MyContextListener.java
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import java.sql.*;
import java.util.ArrayList;
publicvoid contextInitialized(ServletContextEvent e) {
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
180 | P a g e
ResultSet rs=ps.executeQuery();
while(rs.next()){
User u=new User();
u.setId(rs.getInt(1));
u.setName(rs.getString(2));
u.setPassword(rs.getString(3));
list.add(u);
}
con.close();
}
catch(Exception ex){System.out.print(ex);}
}
publicvoid contextDestroyed(ServletContextEvent arg0) {
System.out.println("project undeployed...");
}
4) MyServlet1.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
publicclassMyServlet1extends HttpServlet
{
publicvoid doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException
{
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
181 | P a g e
response.setContentType("text/html");
PrintWriter out = response.getWriter();
longbefore=System.currentTimeMillis();
ServletContext context=getServletContext();
Listlist=(List)context.getAttribute("data");
Iteratoritr=list.iterator();
while(itr.hasNext()){
User u=(User)itr.next();
out.print("<br>"+u.getId()+" "+u.getName()+" "+u.getPassword());
}
longafter=System.currentTimeMillis();
out.print("<br>total time :"+(after-before));
out.close();
}
5) MyServlet2.java:
It is same as MyServlet1. This servlet gets the information from the servlet context object and
prints it.
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
182 | P a g e
publicclassMyServlet2extends HttpServlet {
publicvoid doGet(HttpServletRequestrequest, HttpServletResponse
response)throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
longbefore=System.currentTimeMillis();
ServletContext context=getServletContext();
Listlist=(List)context.getAttribute("data");
Iteratoritr=list.iterator();
while(itr.hasNext()){
User u=(User)itr.next();
out.print("<br>"+u.getId()+" "+u.getName()+" "+u.getPassword());
}
longafter=System.currentTimeMillis();
out.print("<br>total time :"+(after-before));
out.close();
}
6) web.xml:
<web-appversion="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<listener>
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
183 | P a g e
<listener-class>MyListener</listener-class>
</listener>
<servlet>
<servlet-name>MyServlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class>
</servlet>
<servlet>
<servlet-name>MyServlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>MyServlet2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
In this example, we are using FileInputStream class to read image and ServletOutputStream
class for writing this image content as a response. To make the performance faster, we have
used BufferedInputStream and BufferedOutputStream class.
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
184 | P a g e
In this example, we are assuming that you have java.jpg image inside the c:\test directory. You
may change the location accordingly.
1. index.html
2. DisplayImage.java
3. web.xml
index.html:
DisplayImage.java
This servlet class reads the image from the mentioned directory and writes the content in the
response object using ServletOutputStream and BufferedOutputStream classes.
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
publicclassDisplayImageextends HttpServlet {
bin.close();
fin.close();
bout.close();
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com
185 | P a g e
out.close();
}
}
Durga Soft
nd
#202, 2 Floor, HUDA Maithrivanam, Ameerpet, Hyderabad.
040-6451 2786, 8096 9696 96, 9246 2121 43 | www.durgasoft.com