Module 123
Module 123
Module 123
Servlet Structure, Servlet Packaging, HTML building utilities, Life cycle, Single Threaded Model
interface, Handling Client Request: Form Data, Handling Client Request: HTTP Request Headers.
Generating server Response: HTTP Status codes, Generating server Response: HTTP Response
Headers, Handling Cookies, Session Tracking.
Overview of JSP: JSP Technology, Need of JSP, Benefits of JSP, Advantages of JSP, Basic syntax
SERVLETS
• A servlet is a Java programming language class that is used to extend the
capabilities of servers that host applications accessed by means of a request-response
programming model.
• The javax.servlet and javax.servlet.http packages provide interfaces and classes
for writing servlets. All servlets must implement the Servlet interface, which
defines life- cycle methods
• The HttpServlet class provides methods, such as doGet and doPost, for handling
HTTP-specific services.
// Use "response" to specify the HTTP response status code and headers(eg.
• The HttpServletRequest has methods by which you can find out about
incoming information:
o such as form data,
o HTTP request headers,
o client's hostname.
Output:
<!DOCTYPE ...>
<HTML>
<HEAD><TITLE>...</TITLE>...</HEAD>
<BODY ...>
</BODY>
</HTML>
• They let you submit a URL, then they retrieve the page, check the syntax against
the formal HTML specification, and report any errors to you. Since a servlet that
generates HTML looks like a regular Web Page to visitors
• To generate HTML with println statements, especially long tedious lines like the
DOCTYPE declaration. Some people address this problem by writing detailed
HTML generation utilities in Java, then use them throughout their servlets. Still,
have the problems listed below:
o Its inconvenience of generating HTML programmatically
o HTML generation routines can be cumbersome and tend not to support the
full range of HTML attributes (CLASS and ID for style sheets, JavaScript
event handlers, table cell background colors, and so forth).
O After the Servlet class is loaded, Web Container creates the instance of it.
Servlet instance is created only once in the life cycle.
Call to the init( ) method
o init( ) method is called by the Web Container on servlet instance to
initialize the servlet.
O It is used for one-time initialization, just as in
applets O There are two init( ) methods
• init( )
• init(Sefv1etConfig config)
O init( )
• init simply creates or loads some data that will be used throughout
the life cycle.
• The first version is used when the servlet does not need to read
any settings that vary from server to server.
• Syntax:
public void init() throws ServletException {
// Initialization code...
o Syntax:
public void service(ServletRequest request, ServletResponse r
IOException {
//servlet code
// Servlet Code
// Servlet Code
• If a servlet implements this interface, you are guaranteed that no two threads will
execute concurrently in the servlet's service method.
• It queue's all the request and passing them one at a time to a single servlet instances
• The server is permitted to create a pool of multiple instances, each of which
handles one request at a time.
• URL's like
H getParameter()
o qefi Parame b er exactly the same way when the data is sent by GET as
you do when it is sent by POST.
o An empty S Lr i riq is returned if the parameter exists but has no value,
and riul l is returned if there was no such parameter.
<html>
<head>
<title>Collecting Three Parameters</title>
</head>
<body>
<form action="ParmeterServlet" method="Get">
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)throws ServletException, IOException {
PrintWriter out=response.getWriter();
String title = "Reading Three Request Parameters";
out.println("Parameterl:+reguest.getParameter(“param2”});
out.println("Parameterl:+reguest.getParameter}"paramf’Ç);
out.println("Parameterl:+reguest.getParameter}“paramS”j);
H getParameterValues( )
• If the parameter have more than one value, eg: checkbox
o which returns an array of strings
o The return value of qefi Parame fi e rVa l ue s is nul l , for nonexistent
parameter names and is a one-element array when the parameter has only a
single value.
• General form:
String[] values = getParameterValues(“Input Parameter”);
• Example:
Index.html
<form action="ongetParameterVlaues" method="post">
Habits
<input type="checkbox" name="habits" value="Reading">Reading
<input type="checkbox" name="habits" value=”Movies">Movies
<input type="checkbox" name="habits" value="Writing">Writing
<input type="checkbox" name="habits" value="Singing">Singing
<input type="submit" value="Submit">
</form>
OngetParameterValues.java
public class OngetParameterValues extends HttpServlet
PrintWriter out=res.getWriter();
response.setContentType("text/html");
String[] values=request.getParameterWa2ues{"habits"j;
out.println("Selected Values. .");
for(int i=0;i<values.length;i++)
out.println("<li>"+values[i]+"</li>");
out.close();
H getParameterNames( )
• to get a full list
• to get this list in the form of an Enumeration, each entry of which can be cast to
a String and used in a getParameter or getParameterValues call.
• Example:
Index.html
<form action="onPM" method="post">
Name:<input type="text" name="name">
Country:<input type="text" name="country">
<input type="submit" value="Submit">
</form>
OngetParameterNames.java
public class OngetParameterNames extends HttpServlet
PrintWriter out=response.getWriter():
response.setContentType("text/html");
Enumeration en=request.getParameterNames( ):
while(en.hasMoreElements())
String parameterName
=(String)en.nextElement();
out.println("Parameter "+parameterName);
out.close();
Cookie This header is used to return cookies to servers that previously sent
them to the browser.
Expect This rarely used header lets the client tell the server what kinds of
behaviors it expects.
From This header gives the e-mail address of the person responsible for
the HTTP request.
Host Browsers are required to specify this header, which indicates the
host and port as given in the original URL.
If-Match This rarely used header applies primarily to PUT requests. The client
can supply a list of entity tags as returned by the ETag response
header, and the operation is performed only if one of them matches.
If-Modified-Since This header indicates that the client wants the page only if it has
been changed after the specified date. This option is very useful
because it lets browsers cache documents and reload them over the
network only when they've changed.
Pragma A Pragma header with a value of no-cache indicates that a servlet
that is acting as a proxy should forward the request even if it has a
local copy.
Referer This header indicates the URL of the referring Web page. it is a
useful way of tracking where requests came from
Upgrade The Upgrade header lets the browser or other client specify
a communication protocol it prefers over HTTP 1.1
User-Agent This header identifies the browser or other client making the request.
Via This header is set by gateways and proxies to show the
intermediate sites the request passed through.
Warning This rarely used catchall header lets clients warn about caching or
PrintWriter out;
String title;
response.setHeader("Content-Encoding", "gzip");
} else {
title = "Unencoded Page";
out = response.getWriter();
out.println(ServletUtilities.headWithTitle(title) +
"<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<H1 ALIGN=CENTER>" + title + "</H1>\n");
out.println("</BODY></HTML>");
out.close();
Output:
Hello World
• The setstatus method takes an int (the status code) as an argument, but instead of
using explicit numbers, it is clearer and more reliable to use the constants defined in
HttpServletResponse.
• There are two common cases where a shortcut method in HLrpSe rvle tResponse
is provided. Just be aware that both of these methods throw I OExcepL i on, whereas
s e LSfiafiu s doesn't.
• The following sections describe each of the status codes available for use in
servlets talking to HTTP 1.1 clients, along with the standard message associated with
each code.
• You should only send the new codes to clients that support HTTP 1.1, as verified
by checking request.getRequestProtocol.
101 (Switching SC_SWI TCH ING_PROTOCO status indicates that the server will comply with the
ProtocolS) LS Upgrade header and change to a different protocol.
This status code is new in HTTP 1.1.
200 (OK) SC_OK A value of 200 me s that eve h ng is me
201(Created) SC_CREATE D signifies that the server created a new document in
response to the request; the Local ion header
should
tells ive its
the client URL.
that the request is being acted upon, but processing
202 (Accepted) SC ACCE PTE D
203 (Non- SC NON AUTHOR I TAT IVE status signifies that the document is being returned
Authoritative _I NFORNAT I ON normally, but some of the response headers might
Information) be incorrect since a document copy is being used
204 (No SC_NO_CONTENT stipulates that the browser should continue to
Content) display the previous document because no new
document is available.
205 (Reset SC RESET CONTENT means that there is no new document, but the
Content) browser should reset the document view. status indicates bad syn
400 (Bad SC_BAD_REQUEST
Request)
401 SC UNAUTHORIZED signifies that the client tried to access a password-
(Unauthorized) protected page without proper identifying
information in the Aufihori z ad ion header. The
response must include a wu—AufihenfiieaLe
header.
403(Forbidden) SC_FORB I DDEN means that the server refuses to supply the
resource, regardless of authorization
404 (Not SC NOT FOUND status tells the client that no resource could be
Found) found at that address. This value is the standard “no
such page” response.
502 (Bad SC BAD GATEWAY used by servers that act as proxies or gateways; it
Gateway) indicates that the initial server got a bad response
from the remote server.
503 (Service SC_SERVI CE_UNAVAI LAB signifies that the server cannot respond because of
Unavailable) LE maintenance or overloading
504 (Gateway SC GATEWAY T IMEOUT is used by servers that act as proxies or gateways;
Timeout) it indicates that the initial server didn't get a timely
response from the remote server.
Methods Meaning
setContentType This method sets the Content-Type header and is used by the
majority of servlets.
setContentLength This method sets the Content-Length header, which is useful
if the browser supports persistent (keep-alive) HTTP
connections.
addCookie This method inserts a cookie into the Set-Cookie header.
There is no corresponding setCookie method, since it is
normal to have multiple
Set-Cookie lines.
sendRedirect The sendRedirect method sets the Location header as well as
setting the status code to 302.
•
Private means document is for a single user and can only be
stored in private caches
• no-cache means document should never be cached.
• response.setHeader("Cache-Control","no-
cache");
• response.setHeader("Pragma", "no-cache");
Connection instructs the browser whether to use persistent in HTTP connections or
not. Connec I ion : keep—al ive
Content-Encoding indicates the way in which the page was encoded during transmission.
Content- This header signifies the language in which the document is written.
Language Example: en, en-us, ru, etc.
Content-Length indicates the number of bytes in the response.
Content-Location supplies an alternative address for the requested
document. Content-Location is informational;
Content-Range is sent with partial-document responses and specifies how much of the
total document was sent
Content-Type • gives the MIME type of the response document.
• The default MIME type for servlets is text/plain
H Customizing a site
o Many “portal” sites let you customize the look of the main page. They might
let you pick which weather report you want to see, what stock and sports
results you care about, how search results should be displayed, and so
forth. Since it would be inconvenient for you to have to set up your page
each time you visit their site, they use cookies to remember what you
wanted. For simple settings, this customization could be accomplished by
storing the page settings directly in the cookies.
S Focusing advertising
o Most advertiser-funded Web sites charge their advertisers much more for
displaying “directed” ads than “random” ads. Advertisers are generally
willing to pay much more to have their ads shown to people that are known
to have some interest in the general product category. For example, if you go
to a search engine and do a search on “Java Servlets,” the search site can
charge an advertiser much more for showing you an ad for a servlet
development environment than for an ad for an on-line travel agent
specializing in Indonesia.
Creating Cookie
• Call the Cookie constructor with a cookie name and a cookie value, both of which are
• Syntax:
Cookie obj_name = new Cookie(“name”,
“value”);
• Neither the name nor the value should contain white space or any of the
following characters: [ ] ( ) = , " / ? @ : ;
Cookie Attribute
• Before adding the cookie to the outgoing headers, you can set various characteristics
of the cookie by using one of the following
o setXxr methods, where lxx is the name of the attribute you want to specify.
o getYxx method to retrieve the attribute value.
Methods NameDescription
public String getComment( ) These methods look up or specify a comment
associated with the cookie. The comment is
public void setComment(String used purely for informational purposes on the
comment) server; it
is not sent to the client
public String getDomain( ) These methods get or set the domain to which the
public void setDomain(String cookie applies. the browser only returns cookies
domainPattern) to the exact same hostname that sent them.
public int getMaxAge( ) These methods tell how much time (in
seconds) should elapse before the cookie
public void setMaxAge(int lifetime) expires.
A negative value, which is the default,
indicates that the cookie will last only for the
current session and will not be stored on disk.
Specifying a value of 0 instructs the browser to
delete the cookie.
public String getName( ) This pair of methods gets or sets the name of the
public void setName(String cookie. The name and the value are the two pieces
cookieName) you virtually always care about.
public String getPath( ) These methods get or set the path to which the
public void setPath(String path) cookie applies. If you don't specify a path, the
browser returns the cookie only to URLs in or
below the directory containing the page that sent
the cookie.
public boolean getsecure( ) This pair of methods gets or sets the Boolean
public void setSecure(boolean value indicating whether the cookie should
secureFIag) only be sent over encrypted (i.e., SSL)
connections. The default is false; the cookie
should apply to all
connections.
public String getValue( ) The getValue method looks up the value
public void setValue(String associated with the cookie; The setValue method
cookieVaIue) specifies it.
• Now you can iterate through the array of cookies and find the cookies you need.
Unfortunately there is no way to obtain a cookie with a specific name. The only way
to find that cookie again is to iterate the Cookie[ ] array and check each cookie name.
Here is an example:
Removing Cookies
• The simple code to delete cookie
MyServIet.java
import java.io.*:
import javax.servlet.*:
import javax.servlet.http.*;
request.getParameter("pass");
if(pass.equals("1234"))
First.java
First.java
return(null);
1.11 Session
• Session: interval of time
• Session Tracking is a way to maintain state (data) of an user
1.11.1 Session Tracking
• We all know that HTTP is a stateless protocol. All requests and responses are
independent. But sometimes you need to keep track of client's activity across
multiple requests. For eg. When a User logs into your website, not matter on which
web page he visits after logging in, his credentials will be with the server, until he
logs out. So this is managed by creating a session.
• Session Management is a mechanism used by the Web container to store session
information for a particular user.
• There are four different techniques used by Servlet application for session
management. They are as follows:
1. Cookies
2. URL-rewriting
3. Hidden form fields
4. HttpSession
Cookies
• Cookies are small pieces of information that are sent in response from the web
server to the client.
• Cookies are stored on client's computer. They have a lifespan and are destroyed by
the client browser at the end of that lifespan.
• Advantage of cookie
o Simplest technique of maintaining the state
o Cookies are maintained at client side.
• Disadvantage
o It will not work if cookie is disabled from the browser.
o Only textual information can be set in Cookie object
URL-rewriting
• 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 separated by an equal(=) sign.
• 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.
• getParameter()
• Advantage of URL-Rewriting
O It will always work whether cookie is disabled or not (browser
independent). O Extra form submission is not required on each pages.
• Disadvantage of URL-Rewriting
O It will work only with links.
O It can send Only textual information.
URL ;jsessionid=1234567
• Hidden form field can also be used to store session information for a particular client.
• User information is stored in hidden field value and retrieved from another servlet.
<INPUT TYPE="HIDDEN" NAME="session" VALUE="...">
• Advantage
O Does not have to depend on browser whether the cookie is disabled or not.
O Inserting a simple HTML Input field of type hidden is required. Hence, its
easier to implement.
• Disadvantage
o Extra form submission is required on every page. This is a big overhead.
HttpSession
• Servlets provide an outstanding technical solution: the HttpSession API.
• This high-level interface is built on top of cookies or URL-rewriting
These methods extract a previously stored value from a session object. They return
null if there is no value associated with the given name. gerArt.ribut.e is preferred
and qetValue is deprecated.
2 public void putValue(String name, Object value)
public void setAttribute(String name, Object value)
These methods associate a value with a name. Use puLVal ue with servlets and either
s e CAT fri ibufie (preferred) or putVa lue (deprecated) with version 2.2 servlets.
3 public void removeVaIue(String name)
public void removeAttribute(String name)
These methods remove any values associated with the designated name. If the value
being removed implements HLLpSe s s i onBi ndi nqLi s tener, its value
Unbound method is called.
4 public String[] getValueNames()
public Enumeration getAttributeNames0
These methods return the names of all attributes in the session. Use qe tValueName s
in version 2.1 of the servlet specification. In version 2.2, qe LVa1ueName s is
supported but deprecated; use qeLAt Ir ibuteNames instead.
5 public String getId
This method returns the unique identifier generated for each session. It is sometimes
used as the key name when only a single value is associated with a session, or when
information about sessions is being logged.
public boolean isNew()
This method returns true if the client (browser) has never seen the session, usually
because it was just created rather than being referenced by an incoming client request.
It returns false for preexisting sessions.
7 public long getCreationTime0
This method returns the time in milliseconds since midnight, January 1,1970 (GMT) at
which the session was first built. To get a value useful for printing out, pass the value
to the Dafie constructor or the s efi Time I nMi11 i s method of Gre gor i anCalendar.
8 public long getLastAccessedTime()
This method returns the time in milliseconds since midnight, Januaryl970 (GMT) at
which the session was last sent from the client.
public int getMaxInactiveInterval()
public void setMaxInactiveInterval(int seconds)
These methods get or set the amount of time, in seconds, that a session should go
without access before being automatically invalidated. A negative value indicates
that the
session should never time out.
Index.html
<html>
<head>
<title>TODO supply a title</title> </head>
<body>
<form method="post" action="Validate">
<h3>User: <input type="text" name="user" /></h3>
<h3> Password: <input type="password" name="pass"></h3>
<input type="submit" value="submit">
</body>
</html>
Validate.java
public class Validate extends HttpServlet (
protected void doPost(HttpServletRequest request, HttpServletResponse respons
throws ServletException, IOException { response.setContentType("text/html;cha
if(pass.equals("1234"))
//creating a session
HttpSession session = request.getSession(); session.setAttribute("user", nam
Welcome.java
public class Welcome extends HttpServlet {
• There are three main types of JSP constructs that you embed in a page:
o scripting elements
o directives
o actions
1.12.1 lifecycle of JSP
JSP pages are saved with .jsp extension which lets the server know that this is a JSP page and
needs to go through JSP life cycle stages.
• Easy to maintain
o JSP can be easily managed because we can easily separate our business
logic with presentation logic. In servlet technology, we mix our business
logic with the presentation logic.
• Fast Development: No need to recompile and redeploy
o If JSP page is modified, we don't need to recompile and redeploy the
project. The servlet code needs to be updated and recompiled if we have to
change the look and feel of the application.
• Less code than Servlet
o In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc.
that reduces the code. Moreover, we can use EL, implicit objects etc
i. 1s Basic syntax
There are four different types of elements you can use in JSP.
• Scripting elements
• Comments
• Directives
• Actions
Scripting elements
• Example:
<body>
<% out.print("welcome to jsp"); %>
</body>
x/htmlx
• Example
<html>
<body>
<%! int data=50 %>
</body>
</html>
• General form:
• Example:
• Directives
o JSP directives let you give directions to the server on how a page should
be processed. There are three directives in JSP.
Directive Description
<%@page...%> defines page dependent properties such
as language, session, errorPage etc.
<%@ include.. . defines file to be included.
%>
<%@ taglib.. .%> declares tag library used in the page
• Actions
o The action tags are used to control the flow between pages and to use
Java Bean. The Jsp action tags are given below.
JSP Action Tags Description
jsp:forward forwards the request and response to another resource.
jsp:include includes another resource.
jsp:useBean creates or locates bean object.
jsp:setProperty sets the value of property in bean object.
jsp:getProperty prints the value of property of the bean.
jsp:plugin embeds another components such as applet.
jsp:param sets the parameter value. It is used in forward and include
mostly.
jsp:fa11back can be used to print the message if plugin is working. It is
used in jsp:plugin.
Extra questions
• Difference between get() and post
HTTPPOST
GET The request contains only Along with request line and header it also
Request the request line and HTTP contains HTTP body.
header
Parameter The form elements are The form elements are passed in the body of
Passing passed to the server by the HTTP request.
appending at the end of the
Size The parameter data is Can send huge amount of data to the server.
limited(the limit depends
on the container)
Usage Generally used to fetch Generally used to process the sent data
some information from
the host.
• sendRedirect
o In case of sendRedirect() method, the request is transferred to another
resource to a different domain or the different server for further processing
o When developers use the sendRedirect(), the web-container transfers the
request to a client or a browser so that the URL given inside
the sendRedirect() method is visible as a new request to the client
o In case of sendRedirect() call, the old request and response object is lost
because it is treated as a new request by the browser
o In browser's address bar, developers are able to see the new redirected address
i.e. it is not transparent
o sendRedirect() is slower as one extra round trip is required i.e. The
complete new request is created and the old request object is lost
o In case of sendRedirect() call, if developers want to store the data they will
do it in a Session object or pass it along the value with the URL
• sendError