0% found this document useful (0 votes)
27 views

Servlets

Servlets are used primarily with web servers as a Java-based replacement for CGI scripts that can provide dynamic web content. Servlets have advantages over CGI scripts like improved performance through persistence between requests. Servlets can handle HTTP requests and responses, support collaboration and load balancing, and have lifecycle methods like init(), service(), and destroy().

Uploaded by

Naman K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views

Servlets

Servlets are used primarily with web servers as a Java-based replacement for CGI scripts that can provide dynamic web content. Servlets have advantages over CGI scripts like improved performance through persistence between requests. Servlets can handle HTTP requests and responses, support collaboration and load balancing, and have lifecycle methods like init(), service(), and destroy().

Uploaded by

Naman K
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 27

Java Servlets

 Servlets are used primarily with web servers, where they provide a
Java-based replacement for CGI scripts. They can be used to provide
dynamic web content like CGI scripts.

 Advantages of servlets over CGI scripts:


1. Servlets are persistent between invocations, which dramatically
improves performance relative to CGI programs.
2. Servlets are portable among operating systems and among
servers.
3. Servlets have access to all the APIs of the Java platform (e.g. a
servlet can interact with a database using JDBC API).

 Servlets are a natural fit if you are using the web for enterprise
computing. Web browsers then function as universally available thin
clients; the web server becomes middleware responsible for running
applications for these clients.
Thus the user makes a request of the web server, the server invokes a servlet
designed to handle the request, and the result is returned to the user in the web
browser. The servlet can use JNDI, Java IDL, JDBC, and other enterprise APIs to
perform whatever task is necessary to fulfill the request.

 Servlets can be used when collaboration is needed between people. A


servlet can handle multiple requests concurrently, and can
synchronize requests. So servlets can support on-line conferencing.

 Servlets can forward requests to other servers and servlets. Thus,


servlets can be used to balance load among several servers that mirror
the same content, and to partition a single logical service over several
servers, according to task type or organizational boundaries.

Difference between Java Servlet and Applet


Applet Servlet
1. Applet is a client-side 1. Servlet is a server-side
programming. programming.
2. Lifecycle methods of 2. Lifecycle methods of a
an applet are init(), servlet are init( ), service( ),
start(), paint(), stop() and and destroy( ).
destroy().
3. Applet is required 3. No user interface is
user interface Such as required here.
AWT and Swing.
4. Applet uses parent 4. Servlet uses parent
packages: packages:
import java.applet.*; import javax.servlet.*;
import java.awt.*; import java.servlet.http.*;
5. It requires more 5. It requires less bandwidth
bandwidth for execution. for execution.
6. It uses the resources 6. It uses the resources of
of the client to produce the server to process
Graphical Interface request and response of the
client.
7. Applets are less 7. Servlets are more secure
secure as its execution. as its execution
:

The Servlet Life Cycle

When a client (web browser) makes a request involving a servlet, the web server loads
and executes the appropriate Java classes. Those classes generate content (e.g. HTML),
and the server sends the contents back to the client. From the web browser’s perspective,
this isn’t any different from requesting a page generated by a CGI script, or standard
HTML. On the server side there is one important difference: persistence. Instead of
shutting down at the end of each request, the servlet remains loaded, ready to handle the
subsequent requests. Each request is handled by a separate thread. These threads share
code and data (instance vars). So try to avoid using instance vars, else be sure to use them
in synchronized blocks.

 The request processing time for a servlet can vary, but is typically
quite fast when compared to a similar CGI program. The advantage in
the servlet is that you incur the most of the startup overhead only
once.
 When a servlet loads, its init() method is called. You can use init() to
create I/O intensive resources, such as database connections, for use
across multiple invocations. If you have a high-traffic site, the
performance benefits can be quite dramatic.
Instead of creating thousands of database connections, the servlet needs to create a
connection only once.
 The servlet’s destroy() method can clean up resources when the server
shuts down.
Because servlets are persistent, you can eliminate a lot of filesystem and/or database
accesses altogether. E.g., to implement a page counter, you can simply store a number in
a static variable, rather than consult a file (or database) for every request. Thus you need
to read and write to disk only occasionally to save state.
Since a servlet remains active, it can perform other tasks when it is not servicing client
request, such as running a background thread (where clients connect to the servlet to view
the result) or even acting as an RMI host, enabling a single servlet to handle connections
from mutiple types of clients. E.g., a servlet that accepts transactions from both an HTML
form and an applet using RMI.

Servlet Basics

 The Servlet API consists of two packages, javax.servlet, and


javax.servlet.http.
The javax is there because servlets are a standard extension to Java, rather than a
mandatory part of the API. Thus JVM developers are not required to include classes
for them in their Java development and execution environments.

 Sun has kept the distribution of the servlets API separate from the
Java 2 platform because the Servlet API is evolving much faster than
the core Java SDK. You can find the Java Servlet Development Kit
(JSDK) at http://java.sun.com/products/servlet/.
 The JSDK includes the necessary servlet classes and a small
servletrunner application for development and testing.

HTTP Servlets

 The HttpServlet class is an extension of GenericServlet class that


includes methods for handling HTTP specific data. HttpServlet
defines a number of methods, such as doGet(), and doPost(), to handle
particular types of HTTP requests (GET, POST, etc.). These methods
are called by the default implementation of the service() method,
which figures out the kind of request being made and then invokes the
appropriate method. (service() is defined in GenericServlet class).

Example 1:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class HelloWorldServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {

resp.setContentType(“text/html”);
PrintWriter out = resp.getWriter();

out.println(“<HTML>”);
out.println(“<HEAD><TITLE>Have you seen this
before?</TITLE></HEAD>”);
out.println(“<BODY><H1>Hello World!</H1></BODY></HTML>”);
}
}

The doGet() method is called whenever anyone requests a URL that points to this
servlet. The servlet is installed in the servlets directory (this is similar to the cgi-bin
directory for CGI programs), and its URL is http://site:8080/servlet/HelloWorldServlet.
The doGet() method is actually called by the default service() method of HttpServlet.
The service() method is called by the web server when a request is made of
HelloWorldServlet; the method determines what kind of HTTP request is being made
and dispatches the request to the appropriate doXXX() method (in this case, doGet()).
doGet() is passed two objects, HttpServletRequest ,and HttpServletResponse, that
contain information about the request and provide a mechanism for the servlet to
provide a response, respectively.

Example 2:
This example deals with forms and dynamic HTML.

The HTML form that calls the servlet using a GET request is as follows:

<HTML>
<HEAD><TITLE> Greetings Form</TITLE></HEAD>
<BODY>
<FORM METHOD=GET ACTION=”/servlet/HelloServlet”>
What is your name?
<INPUT TYPE=TEXT NAME=username SIZE=20>
<INPUT TYPE=SUBMIT VALUE=”Introduce Yourself”>
</FORM>
</BODY>
</HTML>

The form submits a variable named username to the URL /servlet/HelloServlet. The
servlet is as follows:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class HelloServlet extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {

resp.setContentType(“text/html”);
PrintWriter out = resp.getWriter();

out.println(“<HTML>”);
out.println(“<HEAD><TITLE>Finally, interaction!</TITLE></HEAD>”);
out.println(“<BODY><H1>Hello,” + req.getParameter(“username”) +
“!</H1>” );
out.println(</BODY></HTML>”);
}
}

The getParameter() method of HttpServletRequest is used to retrieve the value of the


form variable. When a server calls a servlet, it can also pass a set of request parameters.

The POST request

 The POST request is designed for posting information to the server,


although in practice it is also used for long parameterized requests and
larger forms, to get around limitations on the length of URLs. The
doPost() method is the corresponding method for POST requests.
 If your servlet is performing database updates, charging a credit card,
or doing anything that takes an explicit client action, you should make
sure that this activity is happening in a doPost() method.

This is because POST requests are not idempotent, which means that they are not
safely repeatable, and web browsers treat them specially. E.g. a browser cannot
bookmark them. GET requests are idempotent, so they can safely be bookmarked,
and a browser is free to issue the request repeatedly (say to get some information
from the web server) without necessarily consulting the user. Hence it is not
appropriate to charge a credit card in a GET method!

To create a servlet that can handle POST requests, you need to override the default
doPost() method from HttpServlet and implement the necessary functionality. If
necessary, your application can implement different code in doPost() and doGet().
For instance, the doGet() method might display a postable data entry form that the
doPost() method processes. doPost() can even call doGet() at the end to display the
form again.
Servlet Responses

 In the case of an Http servlet, the response can include three


components: a status code, any number of HTTP headers, and a
response body.

 You use setContentType() method of the response object passed into


the servlet to set the type of the response. Examples include
“text/html” for text, “image/gif” for returning a GIF file from the
database, and “application/pdf” for Adobe Acrobat files.

 ServletResponse and HttpServletResponse each define two methods


for producing output streams, getOutputStream() and getWriter(). The
former returns a ServletOutputStream that can be used for text or
binary data. The latter returns a java.io.PrintWriter object used for
text data.

 You can use setStatus() or sendError() method to specify the status


code sent back to the server. Examples include, 200 (“OK”), 404
(“Not Found”) etc. The sendRedirect() method allows you to issue a
page redirect. Calling this sets the Location header to the specified
location and uses the appropriate status code for a redirect.

Servlet Requests

 When a servlet is asked to handle a request, it typically needs


specific information about the request so that it can process the
request appropriately. For example, a servlet may need to find out
about the actual user who is accessing the servlet, for
authentication purposes.
 ServletRequest and ServletRequest provide these methods.
Examples include getProtocol() (protocol used by request),
getRemoteHost() (client host name), getServerName() (name of the
web server), getServerPort() (port number the web server listens
at), getParameter() (access to request parameters as form
variables), and getParameterValues() (returns an array of strings
that contains all the values for a particular parameter).

Example 3:
This servlet requests information to restrict access.
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class SecureRequestServlet extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {

resp.setContentType(“text/html”);
PrintWriter out = resp.getWriter();

out.println(“<HTML>”);
out.println(“<HEAD><TITLE>Semi-Secure Request</TITLE></HEAD>”);
out.println(“<BODY>”);

String remoteHost = req.getRemoteHost();


String scheme = req.getScheme();
String authType = req.getAuthType();

if((remoteHost == null) || (scheme == null) || (authType == null)) {


out.println(“Request information was not available”);
return;
}

// look for a secure HTTP connection from a .gov host using Digest style /
//authentication
if(scheme.equalsIgnoreCase(“https”) && remoteHost.endsWith(“.gov”) &&
authType.equals(“Digest”)) {
out.println(“Special, secret information”);
}
else {
out.println(“You are not authorized to read this information”);
}
out.println(“</BODY></HTML>”);
}
}

Error Handling

 If the error is part of a servlet’s normal operation, such as when a user


forgets to fill in a required form field, then write an error message to
the servlet’s output stream.
 If the error is a standard HTTP error, use the sendError() method of
HttpServletResponse to tell the server to send a standard error status
code.
E.g. if a file was not found,

resp.sendError(HttpServletResponse.SC_NOT_FOUND);

Example 4:
This servlet serves HTML files.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class FileServlet extends HttpServlet {


public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
ServletException, IOException {

File r;
FileReader fr;
BufferedReader br;

try {
r = new File(req.getParameter(“filename”);
fr = new FileReader(r);
br = new BufferedReader(fr);

if (!r.isFile()) {
resp.sendError(resp.SC_NOT_FOUND);
return;
}
}
catch (FileNotFoundException e) {
resp.sendError(resp.SC_NOT_FOUND);
return;
}
catch (SecurityException se) { //Be unavailable permanently
throw(new UnavailableException(this, “Servlet lacks appropriate
privileges”));
}

resp.setContentType(“text/html”);
PrintWriter out = resp.getWriter();
String text;
while ((text = br.readLine()) != null)
out.println(text);

br.close();
}
}

Servlet Initialization

When a server loads a servlet for the first time, it calls the servlet’s init() method. In
its default implementation, init() handles some basic housekeeping, but a servlet can
override the method to perform other tasks. This includes performing I/O intensive tasks
such as opening a database connection. You can also create threads in init() to perform
other tasks such as pinging other machines on the network to monitor the status of these
machines. When an actual request occurs, the service methods can use the resources
created in init(). The default init() is not a do-nothing method. You must call always call
super.init() as the first action in your own init() routines.

The server passes the init() method a ServletConfig object. This object encapsulates
the servlet initialization parameters, which are accessed via the getInitParameter() and
getInitParameterNames() methods. GenericServlet and HttpServlet both implement the
ServletConfig interface, so these methods are always available in a servlet. Consult your
server documentation on how to set the initialization parameters.

Each servlet also has a destroy() method that can be overwritten. This method is called
when a server wants to unload a servlet. You can use this method to free important
resources.

Example 5:
This is a persistent counter servlet that saves its state between server shutdowns. It
uses the init() method to first try to load a default value from a servlet initialization
parameter. Next the init() method tries to open a file named /data/counter.dat and
read an integer from it. When the servlet is shut down, the destroy() method creates a
new counter.dat file with the current hit-count for the servlet.

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class LifeCycleServlet extends HttpServlet {

int timesAccessed;

public void init(ServletConfig conf) throws ServletException {


super.init(conf);

// Get initial value


try {
timesAccessed = Integer.parseInt(getInitParameter(“defaultStart”));
}
catch (NullPointerException e) {
timesAccessed = 0;
}
catch (NumberFormatException e) {
timesAccessed = 0;
}

// Try loading from the disk


try {
File r = new File(“./data/counter.dat”);
DataInputStream ds = new DataInputStream(new FileInputStream(r));
timesAccessed = ds.readInt();
}
catch (FileNotFoundException e){
//Handle error
}
catch (IOException e) {
//Handle error
}
finally {
ds.close();
}
} //end init()

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws


ServletException, IOException {

resp.setContentType(“text/html”);
PrintWriter out = resp.getWriter();
timesAccessed++;

out.println(“<HTML>”);
out.println(“<HEAD><TITLE>Life Cycle Servlet</TITLE></HEAD>”);
out.println(“<BODY>”);

out.println(“I have been accessed “ + timesAccessed + “time[s]”);


out.println(“</BODY></HTML>”);
}

public void destroy() {


// Write the integer to a file
File r = new File(“./data/counter.dat”);
try {
DataOutputStream dout = new DataOutputStream(new
FileOutputStream(r));
dout.writeInt(timesAccessed);
}
catch (IOException e) {
// Handle error, maybe log the error
}

finally (
dout.close();
}
}
}

Example 6
This servlet implements an ATM display. The doGet() method displays the current
account balance and provides a small ATM control panel for making deposits and
withdrawals. The control panel uses a POST request to send the transaction back to the
servlet, which performs the appropriate action and calls doGet() to redisplay the ATM
screen with the updated balance. This example also demonstrates thread safety.

import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
import java.io.*;

public class AtmServlet extends HttpServlet {


Account act;

public void init (ServletConfig conf) throws ServletException {


super.init();
act = new Account();
act.balance = 0;
}

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws


ServletException, IOException {

resp.setContentType(“text/html”);
PrintWriter out = resp.getWriter();
out.println(“<HTML><BODY>”);
out.println(“<H2> First Bank of Java ATM</H2>”);
out.println(“Current Balance: <B>” + act.balance + “</B><BR>”);
out.println(“<FORM METHOD=POST ACTION=/servlet/AtmServlet>”);
out.println(“Amount: <INPUT TYPE=TEXT NAME=AMOUNT
SIZE=3><BR>”);
out.println(“INPUT TYPE=SUBMIT NAME=DEPOSIT
VALUE=\”Deposit\”>”);
out.println(“INPUT TYPE=SUBMIT NAME=WITHDRAW
VALUE=\”Withdraw\”>”);
out.println(“</FORM>”);
out.println(“</BODY></HTML>”);
}

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws


ServletException, IOException {
int amt = 0;
try {
amt = Integer.parseInt(req.getParameter(“AMOUNT”));
}
catch (NullPointerException e) {
// No amount Parameter passed
}
catch (NumberFormatException e) {
//Amount parameter was not a number
}

synchronized(act) {
if (req.getParameter(“WITHDRAW”) != null) && (amt < act.balance))
act.balance = act.balance – amt;
if (req.getParameter(“DEPOSIT”) != null) && (amt > 0)
act.balance = act.balance + amt;
} //end synchronized block

doGet(req, resp); // Show ATM screen


} // end doPost()

public void destroy() {


// save balance to a file before servlet is unloaded. If servlet used JDBC
to // write to a database, need to destroy all database resources here.
}

class Account {
public int balance;
}
}

Server-Side Includes
Servlets are not confined to handling entire requests. Some web servers allow servlets to
add small amounts of dynamic content to otherwise static HTML pages. E.g. a server-
side include to add a randomly selected advertisement to a page. A page that uses the
advertisement servlet is written like a normal HTML page, except that it contains a
<SERVLET> tag and is saved with the .shtml extension. When a client requests a .shtml
page, the server finds all the <SERVLET> tags and replaces them with the output from
the appropriate servlets.

When using a <SERVLET> tag, you must include a CODE parameter that identifies the
servlet to be loaded. This can be a class name or a servlet alias set up within the server.

Example 7

Here’s a sample .shtml file that uses a servlet with server-side include.

<HTML>
<HEAD><TITLE>Today’s News</TITLE></HEAD>
<BODY>
<H1>Headlines</H1>
<H2>Java servlets take over the web! </H2>
<SERVLET CODE=AdMaker>
<PARAM NAME=pagetitle VALUE=”Headlines”>
</SERVLET>
</BODY>
</HTML>

The AdMaker servlet is as follows:

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class AdMaker extends HttpServlet {

static String[] adText = {“Al’s Web Services”,


“Bob’s House of HDs”,
“Main St. Computers”};
int currentAd = 0;

public void doGet(HttpServletRequest req, HttpServletResponse resp) throws


ServletException, IOException {
String adContent;
PrintWriter out = resp.getWriter();
synchronized(this) {
adContent = adText[currentAd];
currentAd++;
if (currentAd >= adText.length)
currentAd = 0;
}
String title = req.getParameter(“pagetitle”); // title of the .shtml page
I if (title != null)
out.println(title + “ is brought to you by”);
else
out.println(“This page is brought to you by”);
out.println(adContent);
}
}

Server-side includes can be a powerful tool but are not part of the standard Servlet API,
and therefore some servlet implementations may not support them.

JavaServer Pages (JSP) is another technology for accessing server-side Java components
directly in HTML pages. This is similar to Active Server Pages.

Servlet – Cookies
Cookies are the textual information that is stored in key-value pair format to the
client’s browser during multiple requests. It is one of the state management
techniques in session tracking. Basically, the server treats every client request
as a new one so to avoid this situation cookies are used. When the client
generates a request, the server gives the response with cookies having an id
which are then stored in the client’s browser. Thus if the client generates a
second request, a cookie with the matched id is also sent to the server. The
server will fetch the cookie id, if found it will treat it as an old request
otherwise the request is considered new. Using Cookies in Java
 In order to use cookies in java, use a Cookie class that is present
in javax.servlet.http package.
 To make a cookie, create an object of Cookie class and pass a name and
its value.
 To add cookie in response, use addCookie(Cookie) method of
HttpServletResponse interface.
 To fetch the cookie, getCookies() method of Request Interface is used.

Methods in Cookies
 clone(): Overrides the standard java.lang.Object.clone method to return a
copy of this Cookie.
 getComment(): Returns the comment describing the purpose of this
cookie, or null if the cookie has no comment.
 getDomain(): Gets the domain name of this Cookie.
 getMaxAge(): Gets the maximum age in seconds of this Cookie.
 getName(): Returns the name of the cookie.
 getPath(): Returns the path on the server to which the browser returns
this cookie.
 getSecure(): Returns true if the browser is sending cookies only over a
secure protocol, or false if the browser can send cookies using any
protocol.
 getValue(): Gets the current value of this Cookie.
 getVersion(): Returns the version of the protocol this cookie complies
with.
 setValue(String newValue): Assigns a new value to this Cookie.
 setVersion(int v): Sets the version of the cookie protocol that this Cookie
complies with.
Example
The name of the Institute is passed to Servlet 2 from Servlet 1 using  / 
HttpSession with example in Servlet
The HttpSession object is used for session management. A session contains information
specific to a particular user across the whole application. When a user enters into a
website (or an online application) for the first time HttpSession is obtained via
request.getSession(), the user is given a unique ID to identify his session. This unique ID
can be stored into a cookie or in a request parameter.

The HttpSession stays alive until it has not been used for more than the timeout value
specified in tag in deployment descriptor file( web.xml). The default timeout value is 30
minutes, this is used if you don’t specify the value in tag. This means that when the user
doesn’t visit web application time specified, the session is destroyed by servlet container.
The subsequent request will not be served from this session anymore, the servlet
container will create a new session.

This is how you create a HttpSession object.

protected void doPost(HttpServletRequest req,


HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = req.getSession();
}
You can store the user information into the session object by using setAttribute() method
and later when needed this information can be fetched from the session. This is how you
store info in session. Here we are storing username, emailid and userage in session with
the attribute name uName, uemailId and uAge respectively.
session.setAttribute("uName", "ChaitanyaSingh");
session.setAttribute("uemailId", "[email protected]");
session.setAttribute("uAge", "30");
This First parameter is the attribute name and second is the attribute value. For e.g.
uName is the attribute name and ChaitanyaSingh is the attribute value in the code above.

TO get the value from session we use the getAttribute() method of HttpSession interface.
Here we are fetching the attribute values using attribute names.

String userName = (String) session.getAttribute("uName");


String userEmailId = (String) session.getAttribute("uemailId");
String userAge = (String) session.getAttribute("uAge");

Methods of HttpSession
public void setAttribute(String name, Object value): Binds the object with a name and
stores the name/value pair as an attribute of the HttpSession object. If an attribute already
exists, then this method replaces the existing attributes.

public Object getAttribute(String name): Returns the String object specified in the
parameter, from the session object. If no object is found for the specified attribute, then
the getAttribute() method returns null.

public Enumeration getAttributeNames(): Returns an Enumeration that contains the


name of all the objects that are bound as attributes to the session object.

public void removeAttribute(String name): Removes the given attribute from session.

setMaxInactiveInterval(int interval): Sets the session inactivity time in seconds. This is


the time in seconds that specifies how long a sessions remains active since last request
received from client.

For the complete list of methods, refer the official documentation.

Session Example
index.html

<form action="login">
User Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPassword"/><br/>
<input type="submit" value="submit"/>
</form>
MyServlet1.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();

String name = request.getParameter("userName");


String password = request.getParameter("userPassword");
pwriter.print("Hello "+name);
pwriter.print("Your Password is: "+password);
HttpSession session=request.getSession();
session.setAttribute("uname",name);
session.setAttribute("upass",password);
pwriter.print("<a href='welcome'>view details</a>");
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}
MyServlet2.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();
HttpSession session=request.getSession(false);
String myName=(String)session.getAttribute("uname");
String myPass=(String)session.getAttribute("upass");
pwriter.print("Name: "+myName+" Pass: "+myPass);
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Output:
First Screen:

After clicking Submit:

After clicking view details:

.
Cookies and a
Session in a Java
Servlet

Cookie is a small piece of


data stored on the client-
side which servers use
when communicating with
clients.
They’re used to identify a
client when sending a
subsequent request. They
can also be used for passing
some data from one servlet
to another.

Create a Cookie
The Cookie class is defined
in
the javax.servlet.http packag
e.
To send it to the client, we
need to create one and add
it to the response:
Cookie uiColorCookie =
new Cookie("color",
"red");
response.addCookie(uiColorCookie);
Copy
However, its API is a lot broader – let's explore it.

2.2. Set the Cookie Expiration Date


We can set the max age (with a method maxAge(int)) which defines how many
seconds a given cookie should be valid for:
uiColorCookie.setMaxAge(60*60);
Copy
We set a max age to one hour. After this time, the cookie cannot be used by a
client (browser) when sending a request and it also should be removed from the
browser cache.

Set the Cookie Domain


Another useful method in the Cookie API is setDomain(String).
This allows us to specify domain names to which it should be delivered by the
client. It also depends on if we specify domain name explicitly or not.
Let's set the domain for a cookie:
uiColorCookie.setDomain("example.com");Copy
The cookie will be delivered to each request made by example.com and its
subdomains.
If we don't specify a domain explicitly, it will be set to the domain
name which created a cookie.

Set the Cookie Path


The path specifies where a cookie will be delivered.
If we specify a path explicitly, then a Cookie will be delivered to the given
URL and all its subdirectories:
uiColorCookie.setPath("/welcomeUser");Copy
Implicitly, it'll be set to the URL which created a cookie and all its
subdirectories.
Now let's focus on how we can retrieve their values inside a Servlet.

2.5. Read Cookies in the Servlet


Cookies are added to the request by the client. The client checks its parameters
and decides if it can deliver it to the current URL.
We can get all cookies by calling getCookies() on the request
(HttpServletRequest) passed to the Servlet.
We can iterate through this array and search for the one we need, e.g., by
comparing their names:
public Optional<String> readCookie(String key) {
return Arrays.stream(request.getCookies())
.filter(c -> key.equals(c.getName()))
.map(Cookie::getValue)
.findAny();
}Copy

2.6. Remove a Cookie


To remove a cookie from a browser, we have to add a new one to the
response with the same name, but with a maxAge value set to 0:
Cookie userNameCookieRemove = new Cookie("userName", "");
userNameCookieRemove.setMaxAge(0);
response.addCookie(userNameCookieRemove);Copy
A sample use case for removing cookies is a user logout action – we may need
to remove some data which was stored for an active user session.

HOME / TECH PAGES / JAVA SERVLET TUTORIAL / COOKIES IN SERVLET WITH EXAMPLE

Cookies in Servlet with example


BY CHAITANYA SINGH

❮ Previous
In the last guide, I have covered Sessions in Servlet. Here we will discuss Cookies which
is also used for session management. Let’s recall few things here from last tutorial so that
we can relate sessions and cookies. When a user visits web application first time, the
servlet container crates new HttpSession object by calling request.getSession(). A unique
Id is assigned to the session. The Servlet container also sets a Cookie in the header of
the HTTP response with cookie name and the unique session ID as its value.

The cookie is stored in the user browser, the client (user’s browser) sends this cookie
back to the server for all the subsequent requests until the cookie is valid. The Servlet
container checks the request header for cookies and get the session information
from the cookie and use the associated session from the server memory.

The session remains active for the time specified in tag in web.xml. If tag in not set in
web.xml then the session remains active for 30 minutes. Cookie remains active as long
as the user’s browser is running, as soon as the browser is closed, the cookie and
associated session info is destroyed. So when the user opens the browser again and sends
request to web server, the new session is being created.

Types of Cookies
We can classify the cookie based on their expiry time:

1. Session
2. Persistent
1) SessionCookies:
Session cookies do not have expiration time. It lives in the browser memory. As soon as
the web browser is closed this cookie gets destroyed.

2) Persistent Cookies:
Unlike Session cookies they have expiration time, they are stored in the user hard drive
and gets destroyed based on the expiry time.

How to send Cookies to the Client


Here are steps for sending cookie to the client:

1. Create a Cookie object.


2. Set the maximum Age.
3. Place the Cookie in HTTP response header.

1) Create a Cookie object:


Cookie c = new Cookie("userName","Chaitanya");
2) Set the maximum Age:
By using setMaxAge () method we can set the maximum age for the particular cookie in
seconds.

c.setMaxAge(1800);
3) Place the Cookie in HTTP response header:
We can send the cookie to the client browser through response.addCookie() method.

response.addCookie(c);

How to read cookies


Cookie c[]=request.getCookies();
//c.length gives the cookie count
for(int i=0;i<c.length;i++){
out.print("Name: "+c[i].getName()+" & Value: "+c[i].getValue());
}

Example of Cookies in java servlet


index.html

<form action="login">
User Name:<input type="text" name="userName"/><br/>
Password:<input type="password" name="userPassword"/><br/>
<input type="submit" value="submit"/>
</form>
MyServlet1.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet1 extends HttpServlet
{
public void doGet(HttpServletRequest request,
HttpServletResponse response) {
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();

String name = request.getParameter("userName");


String password = request.getParameter("userPassword");
pwriter.print("Hello "+name);
pwriter.print("Your Password is: "+password);
//Creating two cookies
Cookie c1=new Cookie("userName",name);
Cookie c2=new Cookie("userPassword",password);

//Adding the cookies to response header


response.addCookie(c1);
response.addCookie(c2);
pwriter.print("<br><a href='welcome'>View Details</a>");
pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}

HttpSession Object
The HttpSession is another option for storing user-related data across different
requests. A session is a server-side storage holding contextual data.
Data isn't shared between different session objects (client can access data from
its session only). It also contains key-value pairs, but in comparison to a cookie,
a session can contain object as a value. The storage implementation mechanism
is server-dependent.
A session is matched with a client by a cookie or request parameters.

Getting a Session
We can obtain an HttpSession straight from a request:
HttpSession session = request.getSession();
Copy
The above code will create a new session in case it doesn't exist. We can
achieve the same by calling:
request.getSession(true)Copy
In case we just want to obtain existing session and not create a new one, we
need to use:
request.getSession(false)
Copy
If we access the JSP page for the first time, then a new session gets created by
default. We can disable this behavior by setting the session attribute to false:
<%@ page contentType="text/html;charset=UTF-8" session="false"
%>Copy
In most cases, a web server uses cookies for session management. When a
session object is created, then a server creates a cookie with JSESSIONID key
and value which identifies a session.

3.2. Session Attributes
The session object provides a bunch of methods for accessing (create, read,
modify, remove) attributes created for a given user session:

 setAttribute(String, Object) which creates or replaces a session attribute


with a key and a new value
 getAttribute(String) which reads an attribute value with a given name
(key)
 removeAttribute(String) which removes an attribute with a given name
We can also easily check already existing session attributes by
calling getAttributeNames().
We can create an attribute:
HttpSession session = request.getSession();
session.setAttribute("attributeKey", "Sample Value");
Copy
The attribute value can be obtained by its key (name):
session.getAttribute("attributeKey");
Copy
We can remove an attribute when we don't need it anymore:
session.removeAttribute("attributeKey");
Copy
A well-known use case for a user session is to invalidate whole data it stores
when a user logs out from our website. The session object provides a solution
for it:
session.invalidate();
Copy
This method removes the whole session from the web server so we cannot
access attributes from it anymore.
HttpSession object has more methods, but the one we mentioned are the most
common.
MyServlet2.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request,
HttpServletResponse response){
try{
response.setContentType("text/html");
PrintWriter pwriter = response.getWriter();

//Reading cookies
Cookie c[]=request.getCookies();
//Displaying User name value from cookie
pwriter.print("Name: "+c[1].getValue());
//Displaying user password value from cookie
pwriter.print("Password: "+c[2].getValue());

pwriter.close();
}catch(Exception exp){
System.out.println(exp);
}
}
}
web.xml

<web-app>
<display-name>BeginnersBookDemo</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
Output:
Welcome Screen:

After clicking Submit:

After clicking View Details:

You might also like