Académique Documents
Professionnel Documents
Culture Documents
Unit-IV
Servlets
Servlets are simple java programs
that run on servers.
Commonly used with HTTP, hence
the name HTTP Servlet
Make use of Java standard extension
classes in packages
- javax.servlet
- javax.servlet.http
Uses of Servlets
Process and store data submitted by HTML
form
Useful for retrieving and updating databases
Working is based on Request-Response
Used in Cookies and Session tracking
- Cookies are a message given to a Web
browser by a Web server. The browser stores the
message in a text file.
- Session tracking keeps track of all previously
accessed web pages
Web Servers
Communication with web servers
established with the help of web
browser
Examples of web browsers:
IE,Mozilla
Examples of web servers: Apache
web server, Microsoft IIS(Internet
Information Services)server
Deployment of Servlets
Writing the servlets is best choice for server side
programming
Servlets need a special environment for execution
i.e., Tomcat, a servlet container & open-source
product is recommended which contains class
libraries, documentation and runtime support which
is useful for executing and testing the servlets.
For execution of servlets,following software must be
installed
- JDK: As servlets are basically java files,JDK must be
installed
- Tomcat: servlet can be executed
JDSK
The Java Development Standard Edition Kit(JDSK) is
available from Sun Microsystems in order to develop
and deploy Java applications on desktop and servers
Installation : http://www.java.sun.com/j2se
After installation, important task is setting up of
environment variables
Steps: Control panel Click System Click Advanced
System Settings-Click Environment Variables
Set the path variable by mentioning the directory
C:\jdk1.06_4(your jdk directory)\bin.Click OK to save
settings.
Finally, go to cmd prompt and type javac
Tomcat Webserver
Description
Servlet
ServletConfig
ServletContext
ServletRequest
ServletResponse
Description
Void destroy()
ServletConfig getServletConfig()
Void Service(ServletRequest
req,Servlet Response res) Throws
Servlet Exception,IO Exception
String getServletInfo()
Description
String getServletName()
String getInitParameter(String p)
Enumeration
getinitParamernames()
ServletContext
getServletContext()
The ServletContext
Interface
Method
Description
Object getAttribute(String
Attribute_name)
Void setAttribute(String
attribut_name,object value)
String getServerInfo()
The ServletRequest
Interface
Method
Description
Object getAttribute(String
Attribute_name)
Int getContentlength()
String getContentType()
getInputStream()
getProtocol()
getReader()
getServerName()
The ServletResponse
Interface
Method
Description
String getCharacterEncoding()
PrintWriter getWriter()
javax.servlet package
Classes
Class
Package
GenericServlet
ServletContextAttribute Event
javax.servlet package
Classes
Class
Description
ServletInputStream
ServletOutputStream
ServletException
Unavailable Exception
javax.servlet.http package
Interfaces
Interface
Description
HttpSession
HttpServerRequest
HttpServerResponse
HttpSessionBindingListener
Object getAttribute(String
attribute_name)
Attribute_name value is
returned
Enumeration
getAttributeNames()
Description
String getMethod()
String getPathInfo()
HttpSession getSession()
Cookie [ ] getCookies()
Description
void setContentType(String
Type)
The HttpSessionBinding
Listener
Description
Object getValue()
String getName()
HttpSession getSession()
javax.servlet.http package
Classes
Class
Description
Cookie
HttpServlet
HttpSessionEvent
HttpSessionBindingEvent
Void setValue(String s)
String getName()
Description
Void doGet(HttpServletRequest
req,HttpServletResponse res)
Void doPost(HttpServletRequest
req,HttpServletResponse res)
Void doPut(HttpServletRequest
req,HttpServletResponse res)
HttpSessionBindingEvent:
Same as HttpSessionBindingListener
Architecture of Servlet
I/O Operations
import java.io.*;
import javax.servlet.*;
Contains Interfaces and
import javax.servlet.http.*;
Classes for Servlet Operation
public class FirstServlet extends HttpServlet
Used when developing servlets
{
that receive and process HTTP
requests
public void doGet(HttpServletRequest request,HttpServletResponse
response)
throws ServletException,IOException
Performs HTTP Get
{
request
Commonly Used Basic
response.setContentType("text/html");
Exceptions for servlets
PrintWriter out=response.getWriter();
servlet contains data in text
form and browser should
out.println("<html>");
interpret the contents as
out.println("<head>");
HTML source code
out.println("<title>My First Servlet</title>");
out.println("<body>");
getwriter()method which
out.println("<h1>Hello</h1>");
helps to display messages
out.println("<h2>How are You</h2>");
out.println("</body>");
out.println("</html>");
}
}
Architecture of Servlet
Architecture of Servlet
Request
Web
browser
Response
init
Service
Destroy
To
determine
which HTTP
method
should be
called
This method
gives your
servlet a
chance to
close
database
connections,
halt
background
threads i.e.,
to cleanup
activities
Java Program[LifeCycle.java]
import java.io.*;
This class implements the Servlet
import javax.servlet.*;
and ServletConfig interfaces
import javax.servlet.http.*;
public class LifeCycle extends GenericServlet
Used an init() method to
{
which object of
public void init(ServletConfig config) throws ServletException ServletConfig interface
is passed
{
This interface allows the
System.out.println("init");
servlet to get the
}
initialization parameters
public void service(ServletRequest request,ServletResponse response)
throws ServletException,IO Exception
{
System.out.println("from service");
service() method is used to
PrintWriter out=response.getWriter();
ServletRequest and
out.println("Hello,How are you");
ServletResponse parameters
out.print("I'm good,Thanks");
are passed for making HTTP
request and getting HTTP
}
response from servlet
public void destroy()
Destroy()
{
function is
System.out.println("destroy");
written in order
}
to unload the
}
servlet from
memory
HTML Program
<html>
<body>
<center>
<form name=form1 method=GETaction=http://localhost:4040/servletsexamples/servlet/my_choiceservlet>
<b>Fruit:</b>
1)The action
<select name="Fruit" size="1">
parameter specifies
<option value="Apple">Apple</option>
the servlet name
<option value="Mango">Mango</option>
which is to be invoked
<option value="Banana">Banana</option>
2) The action is
<option value="Strawberry">Strawberry</option>
specified as GET, i.e.,
</select>
GET request is made
<br><br>
by HTML to servlet
<input type="submit" value="submit">
</form>
</center>
</body>
</html>
Servlet
Program[my_choiceservlet.java
]
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class my_choiceservlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
String Fruit=req.getParameter("Fruit");
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<b>Done!!! ");
out.println("You have choosen "+Fruit);
out.close();
}
}
Servlet
Program[my_choiceservlet.java
]
Servlet class my_choiceservlet is inherited from class
Servlet Program[my_choiceservlet1.java]
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class my_choiceservlet1 extends HttpServlet
{
public void doPost(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
String Fruit=req.getParameter("Fruit");
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<b>Done!!! ");
out.println("You have choosen "+Fruit);
out.close();
}
}
Session Tracking
Client 1
Client 2
S
E
R
V
E
R
Session
1
Session
2
One-One
relationship
between a client
and session i.e,
Particular
session
maintains an
identity and
state of
particular client
across multiple
HTTP requests
Session Tracking
Mechanism to maintain state across a series of
requests from the same browser
Ex: Selecting items in Online shopping cart
Each time a client sends requests a web server, it
opens new connection
Web based applications are responsible for
maintaining such state, called as Session
Use of cookies
GET
/introduction.html
HOST
Browser
Requests
HTTP P.1
www.mywebpage.com
Server
The server then replies in the form of HTTP response. This packet
contains a line requesting browser to store cookies
Using set-cookie statement, server is requesting browser to store the
sid=xf1234ad
HTTP P.1
Set-Cookie :
Browser
Response
200 OK
sid=xf1234ad
Server
Use of cookies
GET
/Chapter1.html
HOST
Cookie
HTTP P.1
www.mywebpage.com
sid=xf1234ad
Browser
Request
Server
This is another request to the same server. By including
cookies which contain sid=xf1234ad server knows that this
request is related to previous request.
In this way, server-browser can keep track of current session
/introduction.html
HOST
Browser
www.mywebpage.com
Request
HTTP P.1
Browser
HTTP 1.1
Server
200 OK
<html>
<form action = introduction.html
method=post>
<input type = hidden
Name = sid
value = xf1234ad
.... <!----Content of Page--
</html>
Response
Server
/Chapter1.html
HTTP P.1
sid=xf1234ad
Browser
Request
Server
URL Rewriting
/introduction.html
HOST
www.mywebpage.com
Browser
Server
Request
HTTP P.1
HTTP 1.1
200 OK
<html>
The server then responds
by putting sid=xf1234ad in
<form action = introduction.html method=post>
response body
<input type = hidden
Name = sid
value = xf1234ad
.... <!----Content of Page--
</html>
Browser
Response
Serve
URL Rewriting
/introduction.html
HTTP/1.1
Request
sid=xf1234ad
Server
Cookies
HTML form
<html>
<head>
<title>Demo of Cookie</title>
</head>
<body>
<form name=form1 method=post
action=http://localhost:8080/examples/servlet/mycooki
eservlet>
<h3>Enter the value for my Cookie:</h3>
<input type= text name=txt_data size=30 value= >
<input type=submit value=submit>
</form>
</body>
</html>
Servlet Program[mycookieservlet.java]
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class mycookieservlet extends HttpServlet
{
public void doPost(HtttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
String txt_data = req.getParamater(txt_data);
//Create cookie
Cookie cookie = new Cookie(My_Cookie,txt_data);
// Adding cookie to HTTP response
res.addCookie(cookie);
//Write friendly output to browser
Res.setContentType(text/html)
PrintWriter out=response.getWriter();
out.println(<h2>MyCookie has been set to:");
out.println(txt_data);
out.println(<br> <br> <br>);
out.println(This page shows that the cookie has been added);
out.close();
}
}
Servlet Program[getcookieserlet.java]
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class getcookieservlet extends HttpServlet
{
public void doGet(HtttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
Cookie[ ] my_cookies = req.getCookies();
res.setContentType(text/html)
PrintWriter out=res.getWriter();
out.println(<b>);
int n = my_cookies.length;
for(int i=0;i<n;i++)
{
String name=my_cookies[i].getName();
String value=my_cookies[i].getValue();
out.println(name=+name);
out.println(and value=+value);
}
out.close();
}
}
Security Issues
Two important security issues:
(a)Use of Cookies - Personal information can
be accessed by other computer using
cookies
(b)Use of doGet request: Using doGet()
method, if HTML page sends some
information to servlet, then it is visible in
browser
If we develop login page, avoiding use of
doGet method, then username and
password will be visible in browser
MVC Architecture
MODEL
(Business logic
and Processing)
Querie
s
Change
Notificatio
n
VIEW
(User Interface)
Changes
View Selection
CONTROLLER
(Navigation and
input)
MVC Architecture
Advantages of MVC
Focus on Developer specialization
Allows separate teams to implement
project development
Reusability of business logic across
applications
Allows development User Interfaces
separate from business logic
.html
files
.jsp
files
72
76
The Web Browser then sends the request to Web Server. The Web Server finds
the requested servlet
The obtained servlet gathers the relevant information by clients request and
builds a Web Page
77
Deployment of Servlets
78
JDSK
The Java Development Standard Edition Kit(JDSK) is
available from Sun Microsystems in order to develop
and deploy Java applications on desktop and servers
Installation : http://www.java.sun.com/j2se
After installation, important task is setting up of
environment variables
Steps: Control panel Click System Click Advanced
System Settings-Click Environment Variables
Set the path variable by mentioning the directory
C:\jdk1.06_4(your jdk directory)\bin.Click OK to save
settings.
Finally, go to cmd prompt and type javac
Tomcat Webserver