Advance Java Module 1
Advance Java Module 1
Advance Java Module 1
Introduction to J2EE
J2EE stands for Java 2 Enterprise Edition.
J2EE is a platform-independent, Java-centric environment from Sun for developing, building and
deploying Web-based enterprise applications online. The J2EE platform consists of a set of services, APIs,
and protocols that provide the functionality for developing multitier, Web-based applications.
The J2EE platform uses a multitiered distributed application model. This means application logic is
divided into components according to function, and the various application components.
A J2EE application system is divided into the tiers as shown below:
Client Tier
Web Tier
EJB (Enterprise JavaBeans) Tier
EIS Tier (Enterprise Information
Systems)
J2EE application can consist of the three
or four tiers shown in figure 1.1
Web Tier
Web tier accepts requests from other
software that was sent using POST, GET,
and PUT operations, which are part of
HTTP transmissions. The two major
components of web tier are Servlets and
Java Server Pages. A servlet is a java class
that resides on the web tier and is called
by a request from a browser client that
operates on the client tier. Figure 1.3: Web Tier Architecture
Applet Container
An applet is a java program that can be embedded into a web page. Most of the web pages are authored in HTML.
To use an applet in HTML document, the tags <APPLET> and </APPLET> are used. They are used to indicate to
Module -1 Servlet
the browser that a java applet should be loaded. “These tags act as a container for the java applet definition.”
Applet container manages the execution of applet, and contains the web browser.
Application-Client Container
The Application Client Container (ACC) is a combination of Java classes, libraries, and other files. They are used
to distribute along with Java client programs that execute on their own JVM. The execution of the application
client components is managed by the application-client container. The ACC can take the responsibility to collect
user name and password which is treated as authentication data.
Web Container:
A web container is a part of web server. It provides the run time environment to execute a web application such as
a servlet, JSP. A servlet container translates the URL requests into servlet requests. The JSP implicit objects such
as request, response, out, page, pageContext etc., are exposed by JSP container.
EJB Container:
The EJB container manages the execution of enterprise beans for Java EE applications. Enterprise beans and their
container run on the java EE server. An EJB Container manages transactions, state management details, multi
threading, connection pooling. The applications are provided with security using EJB container. All database
access required by the entity bean will be handled by the EJB container.
Module -1 Servlet
Chapter – 1
Servlets
Servlet is a java program that runs on the server side and it acts as a middle layer between a request
coming from the web browser or other HTTP client. The figure 1.6 shows the interaction between client
and Servlet.
Servlet is an API that provides many
interfaces and classes including
documentations.
Servlet is a class that extends the capabilities
of the servers and responds to the incoming
request. It can respond to any type of
requests. Servlet is a web component that is
deployed on the server to create dynamic
web page.
Servlets are Java technology’s answer to
Figure 1.6: Client and Servlet Interaction
CGI programming.
ii. Look up any other information about the request that is embedded in the HTTP request.
This information includes details about browser capabilities, cookies, the host name of the requesting
client, and so forth.
v. Cheaper:
There are a number of free or very inexpensive Web servers available that are good for “personal” use or low-
volume Web sites. However, with the major exception of Apache, which is free, most commercial-quality Web
servers are relatively expensive. Nevertheless, once you have a Web server, adding a Servlets.
Module -1 Servlet
vi. Efficient than CGI:
If N requests to the same CGI program, the If N requests(threads) but only a single copy of
code for the CGI program is loaded into the servlet class.
memory N times. When a servlet finishes handling a request,
When a CGI program finishes handling a remain in memory. So it is straightforward to
request, the program terminates store arbitrarily complex data between
requests.
index.html
<html>
<head><title>User Name</title></head>
<body>
<center><h1>Welcome</h1></center>
<form action="HelloServlet" method="Post">
Enter your Name: <input type="text" name="name"/><br/><br/>
<input type="submit" value="submit"/>
</form></body></html>
HelloServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Move the files to a subdirectory that matches the intended package name.
Example: I’ll use the coreservlets package for the servlets case. So, the class files need to go in a
subdirectory called coreservlets.
Insert a package statement in the class file.
Example: place a class file in a package called coreservlets Package, the first line of the file should read.
package coreservlets;
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.
it can be validated in the normal manner unless it requires POST data to return its result.
Remember that GET data is attached to the URL, so you can submit a URL that includes GET data to the
validators.
Module -1 Servlet
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:
import java.io.*
import javax.servlet.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class NoArgServlet extends HttpServlet {
String str;
public void init()throws ServletException{
ServletConfig info= getServletConfig();
str=info.getInitParameter("greet");
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException {
PrintWriter out=response.getWriter();
out.println("<h1>"+str+"<h1>");
}
}
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<servlet>
<servlet-name>NoArgServlet</servlet-name>
<servlet-class>NoArgServlet</servlet-class>
<init-param>
<param-name>greet</param-name>
<param-value>Hello J2EE World !!!! </param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>NoArgServlet</servlet-name>
<url-pattern>/NoArgServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
</web-app>
Module -1 Servlet
The second version of init() is used when the servlet needs to read server-specific settings before it can complete
the initialization. For example: about database settings, password files, serialized cookies
public void init(ServletConfig config) throws ServletException {
super.init(config); // Initialization code...
}
Notice two things about this code.
First, the init method takes a ServletConfig as an argument. ServletConfig has a getInitParameter
method with which you can look up initialization parameters associated with the servlet.
Second thing is that the first line of the method body is a call to super.init(config). This method is
have a parameter ServletConfig object and always call the init method of the superclass registers it where the
servlet can find it later.
Example1.4: Using Initialize parameters[init()]: Shows a servlet that reads the message and repeats initialization
parameters when initialized.
ShowMessage.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Web.xml
<servlet>
<servlet-name>ShowMessage</servlet-name>
<servlet-class>ShowMessage</servlet-class>
<init-param>
<param-name>message</param-name>
<param-value>Advance JAVA</param-value>
</init-param>
<init-param>
<param-name>repeats</param-name>
<param-value>5</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>ShowMessage</servlet-name>
<url-pattern>/ShowMessage</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
The service method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost,
doPut, doDelete, etc., as appropriate.
Module -1 Servlet
Syntax:
PUT Says to put the enclosed info (the body) at the requested URL.
Example 1.5:
The class SingleThreadServlet which is a servlet prevents handling Single requests at a single time.
Thread. Sleep( 2000 ) will stop the execution of the thread for 2000 millisecond.
When another user access the same servlet, the new instance is created instead of using the same instance
for multiple threads.
Module -1 Servlet
SingleThreadServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.SingleThreadModel;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SingleThreadServlet extends HttpServlet
implements SingleThreadModel{
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print("Welcome");
try{
Thread.sleep(2000);
out.print(" to Servlet ! ! !");
}
catch(Exception e){
e.printStackTrace(out);
}
}
}
doGet() doPost()
In case of post request, large amount of
In case of Get request, only limited amount of
Parameters data can be sent because data is sent in
data can be sent because data is sent in header.
body.
Parameters are not saved in browser
History Parameters remain in browser history
history
Get request is not secured because data is Post request is secured because data is
Security
exposed in URL bar. not exposed in URL bar.
Restrictions on Yes, since form data is in the URL and URL
form data length is restricted ie., 2048 characters No
length
Bookmarked Get request can be bookmarked Post request cannot be bookmarked
Data are re-executed but may not be re-
BACK button submitted to server if the HTML is stored in the Data will be re-submitted
browser cache.
Module -1 Servlet
Chapter 2
Handling the Client Request: Form Data
2.1 Form Data
We’ve seen URL: http://host/path?user=Marty+Hall&origin=bwi&dest=lax. The part after the
question mark (i.e., user=Marty+Hall&origin=bwi&dest=lax) is known as form data (or query
data) and is the most common way to get information from a Web page to a server-side program.
Form data can be attached to the end of the URL after a question mark (as above), for GET requests, or
sent to the server on a separate line, for POST requests.
2.2 Reading Form Data from Servlets
The request object of HttpServletRequest class contains the incoming request data sent by client program.
Request parameters for the servlet are the strings sent by the client to a servlet container as part of its request. The
parameters are stored as a set of name-value pairs. Multiple parameter values can be given as parameter name.
By using following methods we can read parameter values which exist in the parameter name.
i. getParameter()
ii. getParameterValues()
iii. getParameterNames()
getParameter(): You call request.getParameter() method to get the value from HTML Page.
Null is returned if data is not sent.
Syntax: public String getParameter(String name)
Example: String username = request.getParameter(“UNAME”);
Example 2.1: To implement a simple servlet called Three Params that reads form data parameters named
param1, param2, and param3 and display their values. Shows an HTML form that collects user input and sends
it to Servlet.
index.html
<html>
<body bgcolor="#FDF565">
<h1>Collecting Three Parameters</h1>
<form action="ParmeterServlet" method="Get">
First Parameter:<input type="text" name="param1"/><br>
Second Parameter:<input type="text"name="param2"/><br>
Third Parameter: <input type="text" name="param3"/><br>
<input type="submit" value="Click Here">
</form></body></html>
Module -1 Servlet
ParmeterServlet.java
import java.io.*
import javax.servlet.*
import javax.servlet.http.*;
getParameterValues(): Call this method if the parameter have more than one value, which returns an
array of strings, Null is returned if data is not sent.
Syntax: public String [] getParameterValues(String name)
Example: String[] v = request.getParameterValues("Checkboxname");
Example 2.2: To implement a Servlet called checkbox that describes the different types of programming
languages, and then choose knowing languages and display as a list.
index.html
<html>
<body>
<form action="ParamValues" method="Post">
Languages:<br>
<input type="checkbox" name="language" value="C" checked>C<br>
<input type="checkbox" name="language" value="Java"/>
Java/J2EE<br>
<input type="checkbox" name="language" value="Dot Net">C#<br>
<input type="checkbox" name="language" value="Python">Python<br>
<input type="submit" value="submit">
</form>
</body>
</html>
Module -1 Servlet
ParamValues.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
String[] paramvalues=request.getParameterValues("language");
out.println("<h4>Selected Languges are:</h4>");
if(paramvalues==null){
out.println("<h5>NONE</h5>");
}
else{
for(String str:paramvalues){
out.println("<li>" + str + "</li>");
}
}
}
getParameterNames():Call this method if you want a complete list of all parameters in the current request
in the form of Enumeration. Each name is given in the form as String object.
Syntax: java.util.Enumeration getParameterNames()
Example: Enumeration paramNames=request.getParameterNames();
Example 2.3: Here isan example that looks up all the parameter names that are sent and display their values
index.html
<html>
<head><title>Reading the input</title></head>
<body bgcolor="#FDF565">
<form action="ParamNamesServlet" method="Post">
User Information:<hr>
First Parameter: <input type="text" name="param1"/><br>
Second Parameter: <input type="text" name="param2"/><br>
Third Parameter: <input type="text" name="param3"/><br>
Module -1 Servlet
index.html (Continued)
<hr>
Languages:<br>
<input type="checkbox" name="language" value="C" checked>C/C++<br>
<input type="checkbox" name="language" value="Java"/>Java/J2EE<br>
<input type="checkbox" name="language" value="Dot Net">C#<br>
<input type="checkbox" name="language" value="Python">Python<br>
<hr>
<input type="submit" value="Click Here">
</form>
</body></html>
ParamNamesServlet.java
import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
while(userinfo.hasMoreElements()){
String info=(String)userinfo.nextElement();
String[] value=request.getParameterValues(info);
for(int i=0;i<value.length;i++){
out.println("Parameter Name is '"+info+"' and
Parameter Value is '"+value[i]+"'");
}
}
}
}
Module -1 Servlet
Chapter 3
Following are the important header information which comes from browser side and you would use very
frequently in web programming:
Table 3.1: Methods for reading request header
Methods Meaning
getCookies() returns the contents of the Cookie header, parsed and stored in an array of Cookie objects
getAuthType()
break the Authorization header into its component pieces.
getRemoteUser()
getContentLength() returns int value of the Content-Length header
getContentType() Returns string value of the Content-Type header
getDateHeader()
read the specified header and then convert them to Date and int values
getIntHeader()
to get an Enumeration of the values of all occurrences of the header names received on
getHeaderNames()
this particular request.
If a header name is repeated in the request,
version 2.1 servlets cannot access: returns the value of the first occurrence of the
getHeaders()
header only
version 2.2 returns an Enumeration of the values of all occurrences of the header.
getMethod() returns the main request method(Get, Post . . . . )
getRequestURI() returns the part of the URL that comes after the host and port but before the form data
getProtocol() returns the third part of the request line, [HTTP/1.0 or HTTP/1.1]
ShowRequestHeaderServlet.java
import java.io.*;
import java.util.Enumeration;
import javax.servlet.*;
import javax.servlet.http.*;
ShowRequestHeaderServlet.java(continued)
Accept-Charset indicates the character sets (e.g., ISO-8859-1) the browser can use.
Accept-Encoding designates the types of encodings that the client knows how to handle. If it receives this header,
the server is free to encode the page by using the format, sending the Content-Encoding response
header to indicate that it has done so.
Accept-Language specifies the client’s preferred languages, in case the servlet can produce results in more than one
language. The value of the header should be one of the standard language codes such as en, en-us,
da, etc.
Authorization is used by clients to identify themselves when accessing password-protected Web pages.
Cache-Control used by the client to specify a number of options for how pages should be cached by
proxy servers.
Connection tells whether or not the client can handle persistent HTTP Connections.
Content-Length only applicable to POST requests and gives the size of the POST data in bytes. Simply use
request.getContentLength().
Content-Type usually used in responses from the server.
It can also be part of client requests when the client attaches a document as the POST data
or when making PUT requests. Simply use getContentType.
Cookie used to return cookies to servers that previously sent them to the browser.
From 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 used header applies primarily to PUT requests. The client can supply a list of entity tags
as returned by the ETag response header
If-None-Match If-Match, except that the operation should be performed only if no entity tags match.
Module -1 Servlet
If-Modified- indicates that the client wants the page only if it has been changed after the specified date.
Since
If-Range a client that has a partial copy of a document ask for either the parts it is missing (if
unchanged) or an entire new document (if it has changed since a specified date).
If-Unmodified- is used for PUT requests
Since
Pragma The only standard value for this header is no-cache indicates that a servlet that is acting as
a proxy should forward the request even if it has a local copy.
Header Names Description
Proxy- clients identify themselves to proxies that require it. Servlets typically ignore this header,
Authorization using Authorization instead
Range A client that has a partial copy of a document ask for only the parts it is missing.
Referer indicates the URL of the referring Web page.
Upgrade the browser or other client specify a communication protocol it prefers over HTTP 1.1
User-Agent identifies the browser or other client making the request and can be used to return
different content to different types of browsers
Via is set by gateways and proxies to show the intermediate sites the request passed through.
Warning clients warn about caching or content transformation errors.
EncodedPage.java
import java.io.*;
import java.util.zip.*;
import javax.servlet.*;
import javax.servlet.http.*;
Step 2:
Return a 401 (Unauthorized) response code and a header of the following form:
WWW-Authenticate: BASIC realm=“some-name”.
This response instructs the browser to pop up a dialog box telling the user to enter a name and password
for some-name, then to reconnect with that username and password embedded in a single base64 string
inside the Authorization header.
Example 3.3: Restricting the web page
RestrictingPage.java
import java.io.*;
import java.util.Properties;
import javax.servlet.*; import
javax.servlet.http.* import
sun.misc.BASE64Decoder;
RestrictingPage.java(continued)
if (authorization == null) {
askForPassword(response);
}
else {
String userInfo = authorization.substring(6).trim();
BASE64Decoder decoder = new BASE64Decoder();
The status line consists of the HTTP version, a status code, and a very short message corresponding to the
status code. In most cases, all of the headers are optional except for Content-Type, which specifies the
MIME type of the document that follows.
Servlets can perform a variety of important tasks by manipulating the status line and the response headers.
Example: They can forward the user to other sites; indicate that the attached document is an image, Adobe
Acrobat file, or HTML file; tell the user that a password is required to access the document; and so forth.
There are other two common cases where a shortcut method in HttpServletResponse is provided. Just be
aware that both of these methods throw IOException .
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException {
// Set error code and reason.
response.sendError(407, "Need authentication!!!" );
}
}
500-599: Server Error the server failed to fulfill an apparently valid request.
You should only send the new codes to clients that support HTTP 1.1, as verified by checking
request.getRequestProtocol.
Common HTTP 1.1 Status Code:
However, you should note that servers are allowed to vary the messages slightly, and clients pay attention only to
the numeric value.
Table 4.2: List of Common numeric value in status code
Status Code &
Constant Name Description
Message
100 it means that the client is asking if it can send an attached
SC_CONTINUE document in a follow-up request.
Continue
200 SC_OK The request is OK. This status is the default for servlets
OK
204 SC_NO_CONTENT Browser should keep displaying previous document, no new
No Content document is available
301 (SC_MOVED_ • Requested document permanently moved to url.
Moved PERMANENTLY)
• Browsers go to new location automatically
Permanently
302
SC_FOUND The requested page has moved temporarily to a new url
Found
401
SC_UNAUTHORIZED The requested page needs a username and a password
Unauthorized
404
SC_NOT_FOUND The server cannot find the requested page.
Not Found
500 SC_ status notifies the client that the server doesn’t support the
NotImplemented NOT_IMPLEMENTED functionality to fulfill the request.
Module -1 Servlet
4.3 HTTP Response Headers and Their Meaning
You must set the headers before the first use of the PrintWriter or OutputStream that transmits the document
content.
There is another two special methods to set headers that contain dates and integers:
setDateHeader(String header, long milliseconds)
setIntHeader(String header, int headerValue)
If you want to add a new header rather than replace any existing header with the same name.
addHeader(string headername, int headervalue)
addDateHeader(String header, long milliseconds)
addIntHeader(String header, int headerValue)
Finally, HttpServletResponse also supplies a number of methods for specifying common headers.
Methods Meaning
sets the Content-Type header(MIME)
setContentType()
used by the majority of servlets
sets the Content-Length header
setContentLength()
used for persistent (keep-alive) HTTP connections.
addCookie() Adds a value to the Set-Cookie header
sendRedirect() Sets Location header (plus changes status code)
Handling Cookies
Cookies are text files stored on the client computer and they are kept for various information tracking purpose.
Java Servlets transparently supports HTTP cookies.
There are three steps involved in identifying returning users:
» Server script sends a set of cookies to the browser.
Example: name, age, or identification number etc.
» Browser stores this information on local machine for future use.
» When next time browser sends any request to web server then it sends those cookies information to
the server and server uses that information to identify the user.
5.1 Benefits of Cookies
i. Identifying a User during an E-commerce Session:
Many on-line stores use a “shopping cart” in which the user selects an item, adds it to his/her shopping cart,
and then continues shopping. Since the HTTP connection is usually closed after each page is sent, when the
user selects a new item to add to the cart, how does the store know that it is the same user that put the
previous item in the cart? Persistent (keep-alive). HTTP connections do not solve this problem because it is
stateless. But, Cookies can solve this problem.
ii. Avoiding Username and Password:
Many large sites require you to register in order to use their services, but it is inconvenient to remember and
enter the username and password each time you visit. Cookies are a good alternative for low-security sites.
When a user registers, a cookie containing a unique user ID is sent to him. When the client reconnects at a
later date, the user ID is returned, the server looks it up, determines it belongs to a registered user and
permits access without an explicit username and password.
iii. Customizing a Site:
Many “portal” 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.
iv. Focusing Advertising:
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 search on “Java Servlets” the search site can charge an advertiser much more for showing you an ad for a
servlet development environment. Without cookies, the sites have to show a random ad when you first arrive
and haven’t yet performed a search, as well as when you search on something that doesn’t match any ad
categories. Cookies let them remember “that’s the person who was searching for such and such previously”
and display an appropriate ad instead of a random one.
Module -1 Servlet
5.2 Problems with Cookies
Providing convenience to the user and added value to the site owner is the purpose behind cookies. And despite
much misinformation, cookies are not a serious security threat.
Cookies are never interpreted or executed in any way and thus cannot be used to insert viruses or attack your
system. Furthermore, since browsers generally only accept 20 cookies per site and 300 cookies total and since
each cookie can be limited to 4 kilobytes, cookies cannot be used to fill up someone’s disk or launch other denial
of service attacks.
The problem is privacy not security,
First, some people don’t like the fact that search engines can remember that they’re the user who usually
does searches on certain topics. For example, they might search for job openings or sensitive health data
and don’t want some banner ad tipping off their coworkers next time they do a search.
A second, privacy problem occurs when sites rely on cookies for overly sensitive data. For example, some
of the big on-line bookstores use cookies to remember users and let you order without reentering much of
your personal information.
Note: Neither the name nor the should contain white space or any of the following characters:
[ ] ( ) = , “ / ? @ : ;
Cookie Attributes:
Before adding the cookie to the outgoing headers, you can set and get the cookie using following methods:
setXxx methods: you can set the cookie getXxx methods: you can retrieve the attribute value
Xxx is the name of the attribute you want to specify. javax.servlet.http.Cookie class provides the functionality
of using cookies. It provides a lot of useful methods for cookies, listed below.
5.4 Steps for creating and set the cookie in to the response header:
Cookie userCookie = new Cookie("user", "uid1234"); //creating cookie
userCookie.setMaxAge(60*60*24*365); //setting lifespan
response.addCookie(userCookie); // Sending Cookie to the Client [HTTP Response Header]
Cookie[] cks=request.getCookies();
for(int i=0;i<cks.length;i++) {
out.print(“<br>” + ck[i].getName() + “ ” + ck[i].getValue() );
}
Deleting a Cookie:
Cookie ck=new Cookie(“user”, “ ”); //deleting value of cookie
Ck.setMaxAge(0); //Changing the maximum age to 0 seconds
response.addCookie(ck); //adding cookie in the response
Module -1 Servlet
Example 5.3: Program using cookie to remember the user preferences
index.html
<html>
<head><title>Demo on Cookie</title></head>
<body>
<form action="CreateCookieServlet" method="post">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body>
</html>
CreateCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.*;
ReadCookieServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.*;
@Override
public void doPost(HttpServletRequest request,HttpServletResponse
response)throws ServletException, IOException {
try {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<BODY BGCOLOR=\"#FDF5E6\">\n" +
"<TABLE BORDER=1 ALIGN=\"CENTER\">\n" +
"<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>Cookie Name</TH>" +
"<TH>Cookie Value</TH>");
Cookie[] cks=request.getCookies();
for(int i=0;i<cks.length;i++){
out.print("<TR>" + "<TD>" + ck.getName() + "</TD>" +
"<TD>" + ck.getValue() + "</TD>" );
}
}catch(Exception e){System.out.println(e);}
}
}
Module -1 Servlet
Chapter 6
Session Tracking
What is a Session?
Session simply means a particular interval of time.
Session is a conversional state between client and server and it can consists of multiple request and
response between client and server.
Each time user requests to the server, server treats the request as the new request.
Since HTTP and Web Server both are stateless.
So we need to maintain the state of a user to recognize to particular user.
There are four techniques used in Session tracking are listed below:
i. Cookies:
A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a
maximum age, and a version number.
Advantage of Cookies
Simplest technique of maintaining the state.
Cookies are maintained at client side.
Disadvantage of Cookies
It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.
Because of these reasons, Cookie is not an effective to maintain the sessions.
Note:
Non-persistent cookie: It is valid for single session only. It is removed each time when user closes the
browser. (e.g. WebApplication1/SessionTrack)
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.
Module -1 Servlet
ii. Hidden Form Field:
In this case user information is stored in hidden field value and retrieves from another servlet. A web server
can send a hidden HTML form field along with a unique session ID as follows:
index.html
<html>
<head><title>Demo on Hidden</title></head>
<body>
<form action="Servlet1">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>
</body></html>
Servlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Servlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
Example 6.2: We are maintaining the state of the user using link. For this purpose, we are appending the name of
the user in the query string and getting the value from the query string in another page.
Module -1 Servlet
index.html
<html>
<body>
<form action="FirstServlet">
Name:<input type="text" name="userName"/><br/>
<input type="submit" value="go"/>
</form>/body></html>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
@Override
public void doGet(HttpServletRequest request, HttpServletResponse
response)throws IOException, ServletException{
try{
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome");
public HttpSession getSession(boolean create): Returns the current HttpSession associated with this
request or, if there is no current session and create is true, returns a new session.
Example: HttpSession session = request.getSession(true);
It provides a lot of useful methods to set and get the session object attributes that listed below:
Table 6.1: list of methods for HTTPSession
S.N. Method & Description
public Object getAttribute(String name)
1 This method returns the object bound with the specified name in this session, or null if no object is bound
under the name.
Module -1 Servlet
SessionTracking.java
import java.io.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
public class SessionTrack extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)throws ServletException, IOException{
// Create a session object if it is already not created.
HttpSession session = request.getSession();
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = "Welcome Back to my website";
Integer visitCount = 0;
String visitCountKey = "visitCount";
// Check if this is new comer on your web page.
if (session.isNew())
title = "Welcome to my website";
else {
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
}
session.setAttribute(visitCountKey, visitCount);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println(“id:”+ session.getID() +”\n”+ “Creation Time”
+ createTime +”\n” + “Time of Last Access: ”+
lastAccessTime + “\n” + “Number of visits: ” +visitCount);
}
}