Serv Lets Sess 2
Serv Lets Sess 2
and Response
1
Servlet Request & Response – Scope Objects
• User sends request for a servlet by clicking a link that has URL to a servlet.
Servlet Request & Response
• The container finds the servlet using deployment descriptor/@WebServlet
Annotation and creates two objects :
• HttpServletRequest
• HttpServletResponse
Servlet Request & Response
• Then the container creates or allocates a thread for that request and calls
the Servlet's service() method and passes the request, response objects as
arguments.
Servlet Request & Response
• The service() method, then decides which servlet method, doGet() or
doPost() to call, based on HTTP Request Method(Get, Post etc) sent by the
client.
• Suppose the client sent an HTTP GET request, so the service() will call
Servlet's doGet() method
Servlet Request & Response
• Then the Servlet uses response object to write the response back to the
client.
Servlet Request & Response
• After the service() method is completed the thread dies. And the request and
response objects are ready for garbage collection.
Introduction to Servlet Request
• Servlet is used to handle client request.
Cookies getCookies() returns an array containing all of the Cookie objects the client sent with this request
String getQueryString() returns the query string that is contained in the request URL after the path
HttpSession getSession() returns the current HttpSession associated with this request or, if there is no current session
and create is true, returns a new session
String getMethod() Returns the name of the HTTP method with which this request was made, for example, GET,
POST, or PUT.
Part getPart(String name) gets the Part with the given name
String getPathInfo() returns any extra path information associated with the URL the client sent when it made
this request.
String getServletPath() returns the part of this request's URL that calls the servlet
Introduction to Servlet Response
• Servlet API provides two important interfaces ServletResponse and
HttpServletResponse to assist in sending response to client.
Methods Description
PrintWriter getWriter() returns a PrintWriter object that can send character text to the
client.
void setBufferSize(int size) Sets the preferred buffer size for the body of the response
void setContentLength(int len) Sets the length of the content body in the response In HTTP
servlets, this method sets the HTTP Content-Length header
void setContentType(String sets the content type of the response being sent to the client before
type) sending the respond.
void setBufferSize(int size) sets the preferred buffer size for the body of the response.
boolean isCommitted() returns a boolean indicating if the response has been committed
void setLocale(Locale loc) sets the locale of the response, if the response has not been
committed yet.
HttpServletResponse Interface
• HttpServletResponse interface adds the methods that relates to the HTTP
response.
Methods of HttpServletResponse
Methods Description
void addCookie(Cookie cookie) adds the specified cookie to the response.
void sendRedirect(String location) Sends a temporary redirect response to the client using the
specified redirect location URL and clears the buffer
String getHeader(String name) gets the value of the response header with the given name.
void setHeader(String name, String sets a response header with the given name and value
value)
void setStatus(int sc) sets the status code for this response
void sendError(int sc, String msg) sends an error response to the client using the specified status and
clears the buffer
Servlet Communication Methods
Forwards the requests from one Servlet to another on the same server
RequestDispatcher rd=request.getRequestDispatcher("servlet2");
//servlet2 is the url-pattern of the second servlet
rd.forward(request, response);//method may be include or forward
SendRedirect ()-Servlet Communication
• The sendRedirect() method of HttpServletResponse interface
can be used to redirect response to another resource, it may be
servlet, jsp or html file.
• It works at client side because it uses the url bar of the browser to
make another request.
InterServlet Communication
Servlet
Servlet manipulation
reuse allows oneallows one to
Servlet Servlet
reuseto invoke
the the methods
methods of another
and properties of
Servlet
Servlet. collaboration allows the Servlets to share information.
another Servlet for its own purpose.
InterServlet Communication
• Servlets running together in the same server have
several ways to communicate with each other.
There are three major reasons to useinterservlet
communication:
Direct servlet manipulation:
• A servlet can gain access to the other currently loaded
servlets and perform some task on each.
• The servlet could, for example, periodically ask every
servlet to write its state to disk to protect against server
crashes.
InterServlet Communication
Servlet reuse:
• One servlet can use another's abilities to perform a task.
• For Eg Chat Servlet written as a server for chat applets, can be
reused (unchanged) by another servlet that needed to support
an HTML-based chat interface.
Servlet collaboration
• The most common, situation involves two or more servlets
sharing state information.
• For example, a set of servlets managing an online store could
share the store's product inventory count. Session tracking is a
special case of servlet collaboration.
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 configuration information from web.xml file.
Example:
//We can get the ServletContext object from ServletConfig object
• ServletContext application=getServletConfig().getServletContext();
• ServletContext application=getServletContext();
Syntax to provide the initialization parameter in Context
scope
• The context-param element, subelement of web-app, is used to
define the initialization parameter in the application scope.
• The param-name and param-value are the sub-elements of the
context-param.
• The param-name element defines parameter name and and
param-value defines its value.
1.<web-app>
2. ......
3.
4. <context-param>
5. <param-name>parametername</param-name>
6. <param-value>parametervalue</param-value>
7. </context-param>
8. ......
9.</web-app>
InterServlet Communication 3-2
//UserServlet1
UserDetails.html
String uid=request.getParameter("txtuserid");
<HTML>
response.setContentType(CONTENT_TYPE);
<HEAD><TITLE>User
PrintWriter out = Details</TITLE></HEAD>
response.getWriter();
<BODY>
ServletContext context=getServletContext();
<FORM
context.setAttribute("userid",uid);
method=post action="/Example3/UserServlet1">
<H1
RequestDispatcher
align=center>Welcome to Shop Stop</H1>
Please object
dispatcher=getServletContext().getRequestDispatcher(
enter your userRequestDispatcher
id to display your is created to
details:
<Input
"/UserServlet2"); access the context of another Servlet using
type=text name=txtuserid>
if(dispatcher==null) getServletContext() method.
<br/>
<input
{ type=submit>
</FORM>
response.sendError(response.SC_NO_CONTENT);
</BODY>
}
</HTML>
dispatcher.forward(request,response);
out.close();
4
Demonstration: Example 5
InterServlet Communication 3-3
//UserServlet2
ServletContext context=getServletContext();
Object obj=context.getAttribute("userid");
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:pubs",
"sa","playware");
Statement s=con.createStatement();
ResultSet rs=s.executeQuery("Select * from CustomerRegistration
where UserId='"+obj.toString()+"'");
boolean flag=rs.next();
if(flag==true) {
password=rs.getString(2);
FullName=rs.getString(3);
gender=rs.getString(4);
age=rs.getString(5);
} else {
out.println("<font color=red size=7>Login Failed</font>");
Demonstration: Example 6
}
Servlet Context 2-1
• Stores the attributes and resources common to all Servlets in a
ServletContext interface object. The methods dealing with
context attributes are:
out.println("<html>");
out.println("<head><title>UserServlet</title></head>");
out.println("<body bgcolor=\"#ffffff\"onload=
'javascript:frm.userName.focus();'>");
out.println("<FORM METHOD=POST Action='MainServlet'" +
"name='frm'><center>Please enter your nick name<br>
<INPUT " + "TYPE='text' NAME='userName'>" +
"<INPUT TYPE='submit'" + "value='chat'></center></FORM>");
out.println("</body>");
out.println("</html>");
out.close();
Demonstration: Example 7
Chat Application
//MainServlet 5-2
response.setContentType("text/html;charset=UTF-8");
out.println("<html>");
PrintWriter out = response.getWriter();
out.println("<frameset
String usrName rows='80%,*'>");
= request.getParameter("userName");
out.println("<frame
if(usrName src='TopServlet?name="
== null || usrName.equals("")) { +
usrName + "'>");
out.println("<h1 style='color:red' align='center'>" +
"Please out.println("<frame src='MessageServlet?name="
go back and put a valid User Name</h1>"); +
} else { usrName + "' >");
out.println("<frameset>");
Vector vec =
out.println("</body>");
(Vector)getServletContext(). getAttribute("userArray");
out.println("</html>");
if (vec == null) {
} else { vec = new Vector();
} out.println("<h1 style='color:red'
align='center'>" + "UserID
if(!vec.contains(usrName)) { in use</h1>");
} vec.add(usrName);
} //Servlet Context Initialization
HttpSession ses = request.getSession();
out.close();ses.setAttribute("userName",usrName);
getServletContext().setAttribute("userArray",vec);
Demonstration: Example
//Servlet 8
Context Initialization End
Chat Application 5-3
//TopServlet
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>TopServlet</title></head>");
out.println("<frameset cols='80%,*'>");
out.println("<frame src='DisplayServlet'>");
String usrName = request.getParameter("name");
out.println("<frame src='UserList?name'= + usrName + >");
out.println("<frameset>");
out.println("</html>");
out.close();
Demonstration: Example 9
Chat Application
UserList
// 5-4
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<META HTTP-EQUIV='REFRESH' CONTENT='3;Userlist'>");
out.println("<head><title>UserList</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
Vector usr = (Vector) getServletContext(). getAttribute("userArray");
String UserName = request.getParameter("name");
if(usr == null) {
throw new ServletException("Error in Servlet.");
}
for(int i = 0;i<usr.size();i++) {
if(String.valueOf(usr.get(i)).equals(UserName)) {
out.println("<b>" + String.valueOf(usr.get(i)) +
"</b><br>");
} else {
out.println(String.valueOf(usr.get(i)) + "<br>");
}
}
out.println("</body>");
Demonstration: Example 10
out.println("</html>");
out.close();
Chat//DisplayServlet
Application 1-5
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ServletContext app = getServletContext();
StringBuffer strMsg =
(StringBuffer)app.getAttribute("objMessage");
if(strMsg == null) {
public void displayHtml(PrintWriter out,StringBuffer msgBuffer) {
strMsg = new StringBuffer("");
out.println("<html>");
}
out.println("<META HTTP-EQUIV='REFRESH'
displayHtml(out,strMsg);
CONTENT='3;DisplayServlet'>");
out.close();
out.println("<head><title>MessageServlet
</title></head>");
out.println("<body bgcolor=\"#ffffff\">");
out.println(msgBuffer.toString());
out.println("</body>");
out.println("</html>");
}
Demonstration: Example 11
Chat Application 5-5
//MessageServlet
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String strMsg = null;
public void displayHtml(PrintWriter out) {
strMsg = request.getParameter("message");
out.println("<html>");
if (strMsg == null || strMsg.equals("")) {
out.println("<head><title>MessageServlet</title></head>");
displayHtml(out);
out.println("<body bgcolor=\"#ffffff\"onload =
} else {
'javascript:frm.message.focus();'>");
ServletContext app = getServletContext();
out.println("<form method='post' name='frm'>");
StringBuffer objMsg =
out.println("<input type='textbox'
(StringBuffer)app.getAttribute("objMessage");
name='message'size='40'>");
if(objMsg == null) {
out.println("<input type='submit' value='Send'>");
objMsg = new StringBuffer("");
out.println("</form>");
}
out.println("</body>");
String userName = request.getParameter("name");
out.println("</html>");
objMsg.append("<b>" + userName +
}
" Says : </b>" + strMsg + "<br>");
app.setAttribute("objMessage",objMsg);
displayHtml(out);
}
Demonstration: Example 12
out.close();
Attribute
• An attribute is an object that is used to share information in a web app.
• Attribute allows Servlets to share information among themselves.
• Attributes can be SET and GET from one of the following scopes :
• request
• session
• application
Attribute
Session
• A session is defined as a series of related browser requests that come from
the same client during a certain time period.
• Each time user requests to the server, server treats the request as the
new request.
Request 1
Request 2
…….
Request n
Server assigns
unique session
ID to client to
track the user
Session Tracking Techniques 9-1
• Bind objects
• View and manipulate information about a session, such as the session identifier,
creation time, and last accessed time.
HTTPSession Interface - Functionality
The HttpSession Object
• Servlet provides HttpSession Interface which provides a way to identify a
user across more than one page request or visit to a Web site and to store
information about that user.
• The session persists for a specified time period, across more than one
connection or page request from the user.
Creating a Session
Request
Authorized user
Request
Unauthorized user
Hidden Form Field
• Hidden Form Field is a hidden (invisible) textfield is used for maintaining
the state of an user.
• We store the information in the hidden field and get it from another servlet.
• This approach is better if we have to submit form in all the pages and we
don't want to depend on the browser.
Application of Hidden field
• It is widely used in comment form of a website.
…
<form action = "\\firsthtml.htm" method="POST">
</form>
…
URL Rewriting
• In URL rewriting, we append a token or identifier to the URL of the next
Servlet or the next resource.
• We can send parameter name/value pairs using the following format:
url?name1=value1&name2=value2&??
• A name and a value is separated using an equal = sign, a parameter
name/value pair is separated from another parameter using the
ampersand(&).
URL Rewriting
• When the user clicks the hyperlink, the parameter name/value pairs will be
passed to the server.
• From a Servlet, we can use getParameter() method to obtain a parameter
value.
• It will always work whether cookie is disabled or not (browser independent).
• Extra form submission is not required on each pages.
• It will work only with links.
Session Tracking Techniques 9-4
URL Rewriting
• After that if request is sent by the user, cookie is added with request by
default.
• Persistent cookie
It is valid for multiple session .
It is not removed each time when user closes the browser.
It is removed only if user logout or signout.
Pros & Cons of Cookies
• Pros
Simplest technique of maintaining the state.
Cookies are maintained at client side.
• Cons
It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.
Cookie class
• javax.servlet.http.Cookie class provides the
functionality of using cookies.
• It provides a lot of useful methods for cookies.
Constructor Description
//create a cookie
Cookie c = new Cookie("servletName", getServletName());
Demonstration: Example 1
response.addCookie(c);
out.close();
Session Tracking Techniques 9-8
//CookieReader
Cookie cookie = null;
Cookie[] cookies = request.getCookies();
boolean hasCookies = false;
if (cookies != null) If the requested URL contains cookies, the
corresponding names and values are displayed.
hasCookies = true;
if (hasCookies)
{
out.println("<h2> The name and value of each found
cookie</h2>");
for (int i = 0; i < cookies.length; i++)
{
cookie = cookies[i];
out.println("Name of cookie #" + (i + 1) +
": " + cookie.getName() + "<br>");
out.println("Value of cookie #" + (i + 1) +
": " + cookie.getValue() + "<br><br>");
}
} else {
out.println("<h2> This request did not
}
Demonstration: Example 2
include any cookies</h2>");
Session Tracking Techniques 9-9
//SessionServlet
HttpSession session=request.getSession();
out.println("Session status:<br/>");
if(session.isNew()) {
out.println("New session created...<br/>");
} else {
out.println("Old session...<br/>");
}
out.println("<br/> Session id : "+session.getId());
out.println("<br/> Creation time : ");
out.println(new Date(session.getCreationTime()));
out.println("<br/> Last Accessed : ");
out.println(new Date(session.getLastAccessedTime()));
Demonstration: Example 3
Tracking Service Requests
• To track service requests, include in your servlet class a field that counts the
• number of service methods that are running.
• This is one of the few times that your HttpServlet subclass should override the service method.
• The new method should call super.service to preserve all of the original service method’s
functionality:
Notifying Methods to Shut Down
• To ensure a clean shutdown, your destroy method should not release any
shared resources until all of the service requests have completed.
• One part of doing this is to check the service counter.
• Another part is to notify the long-running methods that it is time to shut
down.
• For this notification, another field is required.
• The field should have the usual access methods:
protected synchronized void setShuttingDown(boolean flag) {
public class ShutdownExample extends HttpServlet shuttingDown = flag;
{ }
private boolean shuttingDown; protected synchronized boolean isShuttingDown() {
... return shuttingDown;
//Access methods for shuttingDown }
}
Notifying Methods to Shut Down
• An example of the destroy method using these fields to provide a clean
shutdown follows:
public void destroy() {
/* Check to see whether there are still service methods /*
/* running, and if there are, tell them to stop. */
if (numServices() > 0) {
setShuttingDown(true);
}
/* Wait for the service methods to stop. */
while(numServices() > 0) {
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
}
}
}
Creating Polite Long-Running Methods
• The final step in providing a clean shutdown is to make any long-running
methods behave politely.
• Methods that might run for a long time should check the value of the field
that notifies them of shutdowns and should interrupt their work,
• if necessary.
public void doPost(...) {
...
for(i = 0; ((i < lotsOfStuffToDo) &&
!isShuttingDown()); i++) {
try {
partOfLongRunningOperation(i);
} catch (InterruptedException e) {
...
}
}
}
Java XML Parser
• Java XML parser is used to work with xml data.
• XML is widely used technology to transport or store data.
• That’s why there are many java xml parsers available.