0% found this document useful (0 votes)
153 views25 pages

Servlets

The document discusses servlets, which are Java programs that extend the functionality of web servers. Servlets execute on the server-side and can dynamically generate web page content. The document covers the servlet lifecycle, advantages over CGI, using the Tomcat server, and the Servlet API.

Uploaded by

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

Servlets

The document discusses servlets, which are Java programs that extend the functionality of web servers. Servlets execute on the server-side and can dynamically generate web page content. The document covers the servlet lifecycle, advantages over CGI, using the Tomcat server, and the Servlet API.

Uploaded by

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

IT6503-Web Programming Unit-4: Servlets

Servlets
Servlets:
Servlets are small programs that execute on the server side of a web connection
Just as applets dynamically extend the functionality of a web browser, servlets dynamically extend the
functionality of a web server.

Consider a request for a static web page:


 A user enters a Uniform Resource Locator (URL) into a browser.
 The browser generates an HTTP request to the appropriate web server.
 The web server maps this request to a specific file.
 That file is returned in an HTTP response to the browser.
 The HTTP header in the response indicates the type of the content.
 The Multipurpose Internet Mail Extensions (MIME) are used for this purpose. For example, ordinary ASCII text has a MIME
type of text/plain.
 The Hypertext Markup Language (HTML) source code of a web page has a MIME type of text/html.

Consider dynamic content:


The contents of those web pages must be dynamically generated to reflect the latest information in the database.
CGI
 A server could dynamically construct a page by creating a separate process to handle each client request.
 The process would open connections to one or more databases in order to obtain the necessary information.
 It communicated with the web server via an interface known as the Common Gateway Interface (CGI).
 CGI allowed the separate process to read data from the HTTP request and write data to the HTTP response.
 A variety of different languages were used to build CGI programs.
 These included C, C++, and Perl.

Disadvantages of CGI:
 It suffered serious performance problems.
 It was expensive in terms of processor and memory resources to create a separate process for each client request.
 It was also expensive to open and close database connections for each client request.
 CGI programs were not platform-independent.

Servlets offer several advantages in comparison with CGI.


 First, performance is significantly better. Servlets execute within the address space of a web server. It is not
necessary to create a separate process to handle each client request.
 Second, servlets are platform-independent because they are written in Java.
 Third, the Java security manager on the server enforces a set of restrictions to protect the resources on a server
machine.
 Finally, the full functionality of the Java class libraries is available to a servlet. It can communicate with applets,
databases, or other software via the sockets and RMI mechanisms that you have seen already.

The Life Cycle of a Servlet


Three methods are central to the life cycle of a servlet. These are
init( )
service( )
destroy( )
They are implemented by every servlet and are invoked at specific times by the server.
 First, assume that a user enters a Uniform Resource Locator (URL) to a web browser. The browser then
generates an HTTP request for this URL. This request is then sent to the appropriate server.
 Second, this HTTP request is received by the web server. The server maps this request to a particular servlet.
The servlet is dynamically retrieved and loaded into the address space of the server.
 Third, the server invokes the init( ) method of the servlet. This method is invoked only when the servlet is first
loaded into memory. It is possible to pass initialization parameters to the servlet so it may configure itself.

1|Page H.Bemesha Smitha,AP/IT, LICET


IT6503-Web Programming Unit-4: Servlets

 Fourth, the server invokes the service( ) method of the servlet. This method is called to process the HTTP
request.
You will see that it is possible for the servlet to read data that has been provided in the HTTP request. It may also formulate an HTTP response for
the client. The servlet remains in the server’s address space and is available to process any other HTTP requests received from clients.
The service( ) method is called for each HTTP request.

 Finally, the server may decide to unload the servlet from its memory.
 The algorithms by which this determination is made are specific to each server.
 The server calls the destroy( ) method to relinquish any resources such as file handles that are allocated for
the servlet.
 Important data may be saved to a persistent store.
 The memory allocated for the servlet and its objects can then be garbage collected.

Using Tomcat for Servlet Development


To create servlets, you will need access to a servlet development environment.
Tomcat is an open-source product maintained by the Jakarta Project of the Apache Software Foundation.
It contains the class libraries, documentation, and runtime support that you will need to create and test servlets.

web.xml:
For instance, assuming the first example, called HelloServlet, you will add the following lines in the section that defines the
servlets:
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
Next, you will add the following lines to the section that defines the servlet mappings.
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet/HelloServlet</url-pattern>
</servlet-mapping>

Steps to create and execute servlet:


The basic steps are the following:
1. Create and compile the servlet source code. Then, copy the servlet’s class file to the proper directory, and add the
servlet’s name and mappings to the proper web.xml file.
2. Start Tomcat.
3. Start a web browser and request the servlet.

Sample Program:
1. Create and Compile the Servlet Source Code

To begin, create a file named HelloServlet.java that contains the following program:
import java.io.*;
import javax.servlet.*;
public class HelloServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>Hello!");
pw.close();
}
}

2|Page H.Bemesha Smitha,AP/IT, LICET


IT6503-Web Programming Unit-4: Servlets

Explanation:
- It imports the javax.servlet package. This package contains the classes and interfaces required to build servlets.
- Next, the program defines HelloServlet as a subclass of GenericServlet.
- The GenericServlet class provides functionality that simplifies the creation of a servlet. For example, it provides
versions of init( ) and destroy( ), which may be used as is. You need supply only the service( ) method.
- Inside HelloServlet, the service( ) method (which is inherited from GenericServlet) is overridden. This method
handles requests from a client.
- The first argument is a ServletRequest object. This enables the servlet to read data that is provided via the client
request.
- The second argument is a ServletResponse object. This enables the servlet to formulate a response for the client.
- The call to setContentType( ) establishes the MIME type of the HTTP response.
- In this program, the MIME type is text/html. This indicates that the browser should interpret the content as HTML
source code.
- The getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to the client as part of
the HTTP response.
- Then println( ) is used to write some simple HTML source code as the HTTP response.
- Compile this source code and place the HelloServlet.class file in the proper Tomcat directory as described in the
previous section.
- Also, add HelloServlet to the web.xml file,

2. Start Tomcat
Start Tomcat as explained earlier. Tomcat must be running before you try to execute a servlet.

3. Start a Web Browser and Request the Servlet


Start a web browser and enter the URL shown here:
http://localhost:8080/servlets-examples/servlet/HelloServlet
Alternatively, you may enter the URL shown here:
http://127.0.0.1:8080/servlets-examples/servlet/HelloServlet
This can be done because 127.0.0.1 is defined as the IP address of the local machine. The output of the servlet in the
browser display area. It will contain the string Hello! in bold type.

The Servlet API


Two packages contain the classes and interfaces that are required to build servlets. These are
javax.servlet
javax.servlet.http
They constitute the Servlet API. Keep in mind that these packages are not part of the Java core packages. Instead, they are standard extensions
provided by Tomcat. Therefore, they are not included with Java SE 6.

The javax.servlet Package


 The javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets
operate.
The following table summarizes the core interfaces that are provided in this package. The most significant of these is Servlet.
 All servlets must implement this interface or extend a class that implements the interface.
 The ServletRequest and ServletResponse interfaces are also very important.

3|Page H.Bemesha Smitha,AP/IT, LICET


IT6503-Web Programming Unit-4: Servlets

Core classes that are provided in the javax.servlet package:

The Servlet Interface


 All servlets must implement the Servlet interface.
 It declares the init( ), service( ), and destroy( ) methods that are called by the server during the life cycle of a servlet.
These are invoked by the server
 A method is also provided that allows a servlet to obtain any initialization parameters.
 The getServletConfig( ) method is called by the servlet to obtain initialization parameters.
 A servlet developer overrides the getServletInfo( ) method to provide a string with useful information (for example,
author, version, date, copyright).This method is also invoked by the server.

The ServletConfig Interface:


The ServletConfig interface allows a servlet to obtain configuration data when it is loaded.

4|Page H.Bemesha Smitha,AP/IT, LICET


IT6503-Web Programming Unit-4: Servlets

The ServletContext Interface:


The ServletContext interface enables servlets to obtain information about their environment.

The ServletRequest Interface:


The ServletRequest interface enables a servlet to obtain information about a client request.

5|Page H.Bemesha Smitha,AP/IT, LICET


IT6503-Web Programming Unit-4: Servlets

The ServletResponse Interface:


The ServletResponse interface enables a servlet to formulate a response for a client.

The GenericServlet Class


 The GenericServlet class provides implementations of the basic life cycle methods for a servlet.
 GenericServlet implements the Servlet and ServletConfig interfaces.
 In addition, a method to append a string to the server log file is available.
 The signatures of this method are shown here:
void log(String s)
void log(String s, Throwable e)
Here,
s is the string to be appended to the log
e is an exception that occurred.

The ServletInputStream Class:


 The ServletInputStream class extends InputStream.
 It is implemented by the servlet container and provides an input stream that a servlet developer can use to read the
data from a client request.
 It defines the default constructor.
 In addition, a method is provided to read bytes from the stream. It is shown here:
int readLine(byte[ ] buffer, int offset, int size) throws IOException
Here,
The buffer is the array into which size bytes are placed starting at offset.
The method returns the actual number of bytes read or –1 if an end-of-stream condition is encountered.

The ServletOutputStream Class:


 The ServletOutputStream class extends OutputStream.
 It is implemented by the servlet container and provides an output stream that a servlet developer can use to write
data to a client response.
 A default constructor is defined.
 It also defines the print( ) and println( ) methods, which output data to the stream.

The Servlet Exception Classes


 javax.servlet defines two exceptions.
 The first is ServletException, which indicates that a servlet problem has occurred.
 The second is UnavailableException, which extends ServletException.
 It indicates that a servlet is unavailable.

6|Page H.Bemesha Smitha,AP/IT, LICET


IT6503-Web Programming Unit-4: Servlets

Reading Servlet Parameters


The ServletRequest interface includes methods that allow you to read the names and values of parameters that are
included in a client request
Example:
PostParameters.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<form name="Form1" method="post" action="http://localhost:8080/WebApplicationServlets/PostParametersServlet">
<table>
<tr>
<td><B>Employee</td>
<td><input type=textbox name="e" size="25" value=""></td>
</tr>
<tr>
<td><B>Phone</td>
<td><input type=textbox name="p" size="25" value=""></td>
</tr>
</table>
<input type=submit value="Submit">
</body>
</html>

 The service( ) method is overridden to process client requests.


 The getParameterNames( ) method returns an enumeration of the parameter names.
 These are processed in a loop.
 You can see that the parameter name and value are output to the client.
 The parameter value is obtained via the getParameter( ) method

PostParametersServlet.java
import java.io.*;
import java.util.*;
import javax.servlet.*;
public class PostParametersServlet extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response)throws ServletException, IOException {
// Get print writer.
PrintWriter pw = response.getWriter();

// Get enumeration of parameter names.


Enumeration e = request.getParameterNames();

// Display parameter names and values.


while(e.hasMoreElements())
{
String pname = (String)e.nextElement();

7|Page H.Bemesha Smitha,AP/IT, LICET


IT6503-Web Programming Unit-4: Servlets

pw.print(pname + " = ");


String pvalue = request.getParameter(pname);
pw.println(pvalue);
}
pw.close();
}
}
Execution:

The javax.servlet.http Package


The javax.servlet.http package contains a number of interfaces and classes that are commonly used by servlet
developers.
You will see that its functionality makes it easy to build servlets that work with HTTP requests and responses.

8|Page H.Bemesha Smitha,AP/IT, LICET


IT6503-Web Programming Unit-4: Servlets

Servlet developers typically extend this class in order to process HTTP requests.

The HttpServletRequest Interface


The HttpServletRequest interface enables a servlet to obtain information about a client request.

The HttpServletResponse Interface


 The HttpServletResponse interface enables a servlet to formulate an HTTP response to a client.
 Several constants are defined.
 These correspond to the different status codes that can be assigned to an HTTP response.

9|Page H.Bemesha Smitha,AP/IT, LICET


IT6503-Web Programming Unit-4: Servlets

 For example, SC_OK indicates that the HTTP request succeeded, and SC_NOT_FOUND indicates that the
requested resource is not available.

The HttpSession Interface


 The HttpSession interface enables a servlet to read and write the state information that is associated with an HTTP
session.
 All of these methods throw an IllegalStateException if the session has already been invalidated.

10 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets

Handling HTTP Requests and Responses


 The HttpServlet class provides specialized methods that handle the various types of HTTP requests.
 A servlet developer typically overrides one of these methods.
 These methods are
 doDelete( )
 doGet( )
 doHead( )
 doOptions( )
 doPost( )
 doPut( )
 doTrace( )
 The GET and POST requests are commonly used when handling form input.

Handling HTTP POST Requests

Program: Simple Hello Servlet : Using method post


FirstServlet.html
<!DOCTYPE html>
<!--
To change this license header, choose License Headers in Project Properties.
To change this template file, choose Tools | Templates
and open the template in the editor.
-->
<html>
<head>
<title>HelloWorldServlet</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<form method=post action="http://localhost:8080/WebApplicationServlets/HelloServlet">
<input type=submit>
</form>
</center>
</body>
</html>
View:
Submit

HelloServlet.java
package basic;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloServlet extends HttpServlet {


@Override

11 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets

protected void doPost(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {
PrintWriter ps = response.getWriter();
response.setContentType("text/html");
ps.println("<h1 align=center> Welcome to Servlet </h1>");
}
}

web.xml (Servlet mapping)


<?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>HelloServlet</servlet-name>
<servlet-class>basic.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

Output:

Handling HTTP GET Requests:


Program: Simple Hello Servlet : Using method get
SecondServlet.html
<html>
<head>
<title>SimpleHelloServlet</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<form method=get action="http://localhost:8080/WebApplicationServlets/HelloServletGet">

12 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets

<input type=submit>
</form>
</center>
</body>
</html>

HelloServletGet.java
package basic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloServletGet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/html");
out.println("<h1> My First Servlet Program </h1>");
}
}

web.xml (Servlet Mapping)


<?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>HelloServletGet</servlet-name>
<servlet-class>basic.HelloServletGet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServletGet</servlet-name>
<url-pattern>/HelloServletGet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Output:

13 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets

Program: To perform a simple calculator


index.html
<!DOCTYPE html>
<html>
<head>
<title>Calculator</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form action="http://Bemesha-PC:8080/WebApplicationServlets/Calculator" method="get">
Enter Number 1: <input type="text" name="fnum"/>
<br><br>
Enter Number 2: <input type="text" name="snum"/>
<br><br>
Select Operations <br/>
<input type="radio" name="calc" value="Add"/>Add <br><br>
<input type="radio" name="calc" value="Sub"/>Subtract<br><br>
<input type="radio" name="calc" value="Div"/>Divide<br><br>
<input type="radio" name="calc" value="Multi"/>Multiply <br><br>
<br>
<input type="submit" value="Calculate" name="submit"/>
</form>
</body>
</html>

View:
Enter Number 1:
Enter Number 2:
Select Operations
Add
Subtract
Divide
Multiply
Calculate

Calculator.java
package basic;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class Calculator extends HttpServlet {


@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//assuming request as the object of the HttpServletRequest Class.

14 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets

//retriving & storing the values from the textboxes into the String Variables.
String n1 = request.getParameter("fnum");
int num1 = Integer.parseInt(n1); //Converting String into Integer Variable
String n2 = request.getParameter("snum");
int num2 = Integer.parseInt(n2); int ans=0;

//performing calculation according to the selection made from the Radio Buttons named "calc".
if(request.getParameter("calc").equals("Add"))
ans = num1+num2;
if(request.getParameter("calc").equals("Sub"))
ans = num1-num2;
if(request.getParameter("calc").equals("Div"))
ans = num1/num2;
if(request.getParameter("calc").equals("Multi"))
ans = num1*num2;

//assuming response as the object of the HttpServletResponse Class.


//displaying output to the user
response.getWriter().println("Result: "+ ans);
}
}
web.xml : Servlet Mapping
<?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>Calculator</servlet-name>
<servlet-class>basic.Calculator</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Calculator</servlet-name>
<url-pattern>/Calculator</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Output:

15 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets

The Cookie Class


Cookie:
The Cookie class encapsulates a cookie.
A cookie is stored on a client and contains state information.
Cookies are valuable for tracking user activities.
A cookie can save the user’s name, address, and other information.
The user does not need to enter this data each time he or she visits the store.

A servlet can write a cookie to a user’s machine via the addCookie( ) method of the HttpServletResponse
interface.
The data for that cookie is then included in the header of the HTTP response that is sent to the browser.
The names and values of cookies are stored on the user’s machine.
Some of the information that is saved for each cookie includes the following:
 The name of the cookie
 The value of the cookie
 The expiration date of the cookie
 The domain and path of the cookie

The expiration date determines when this cookie is deleted from the user’s machine. If an expiration date is not
explicitly assigned to a cookie, it is deleted when the current browser session ends. Otherwise, the cookie is saved in
a file on the user’s machine.

The domain and path of the cookie determine when it is included in the header of an HTTP request. If the user
enters a URL whose domain and path match these values, the cookie is then supplied to the Web server. Otherwise, it
is not.

Constructor for Cookie:


Cookie(String name, String value)
Here, the name and value of the cookie are supplied as arguments to the constructor.

Methods Defined by Cookie:

16 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets

The HttpServlet Class:


 The HttpServlet class extends GenericServlet.
 It is commonly used when developing servlets that receive and process HTTP requests.
The methods of the HttpServlet class:

The HttpSessionEvent Class:


 HttpSessionEvent encapsulates session events.
 It extends EventObject and is generated when a change occurs to the session.
 It defines this constructor:
HttpSessionEvent(HttpSession session)
 Here, session is the source of the event. HttpSessionEvent defines one method, getSession( ), which is shown here:
HttpSession getSession( )
 It returns the session in which the event occurred.

The HttpSessionBindingEvent Class:


 The HttpSessionBindingEvent class extends HttpSessionEvent.
 It is generated when a listener is bound to or unbound from a value in an HttpSession object.
 It is also generated when an attribute is bound or unbound.
 Here are its constructors:
HttpSessionBindingEvent(HttpSession session, String name)
HttpSessionBindingEvent(HttpSession session, String name, Object val)
Here,
- session is the source of the event
- name is the name associated with the object that is being bound or unbound.
- If an attribute is being bound or unbound, its value is passed in val.
 The getName( ) method obtains the name that is being bound or unbound. It is shown here:
String getName( )

17 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets

 The getSession( ) method, shown next, obtains the session to which the listener is being bound or unbound:
HttpSession getSession( )
 The getValue( ) method obtains the value of the attribute that is being bound or unbound.
Object getValue( )

Using Cookies
How to use cookies?
Example:
The servlet is invoked when a form on a web page is submitted

The HTML source code for AddCookie.html page contains a text field in which a value can be entered.
There is also a submit button on the page.
When this button is pressed, the value in the text field is sent to AddCookieServlet via an HTTP POST request.
AddCookie.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<form name="Form1" method="post" action="http://localhost:8080/WebApplicationServlets/AddCookieServlet" >
<B>Enter a value for MyCookie:</B>
<input type=text name="data" size=25 value=""/>
<input type=submit value="Submit"/>
</form>
</body>
</html>

The source code for AddCookieServlet.java gets the value of the parameter named “data”.
It then creates a Cookie object that has the name “MyCookie” and contains the value of the “data” parameter.
The cookie is then added to the header of the HTTP response via the addCookie( ) method.
A feedback message is then written to the browser.

AddCookieServlet.java
package basic;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

18 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets

import javax.servlet.http.HttpServletResponse;
/**
* @author Bemesha
*/
public class AddCookieServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get parameter from HTTP request.
String data = request.getParameter("data");

// Create cookie.
Cookie cookie = new Cookie("MyCookie", data);

// Add cookie to HTTP response.


response.addCookie(cookie);

// Write output to browser.


response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>MyCookie has been set to");
pw.println(data);
pw.close();
}
}

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>AddCookieServlet</servlet-name>
<servlet-class>basic.AddCookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddCookieServlet</servlet-name>
<url-pattern>/AddCookieServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Execution:

19 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets

Output:
Run AddCookie.html

Click the submit button. AddCookieServlet is called

The HTML source code for AddCookie.html page contains a text field in which a value can be entered.
There is also a submit button on the page.
When this button is pressed, the value in the text field is sent to AddCookieServlet via an HTTP POST request.
AddCookie.html
<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<form name="Form1" method="get" action="http://localhost:8080/WebApplicationServlets/GetCookiesServlet">
<B>Enter a value for MyCookie:</B>
<input type=text name="data" size=25 value=""/>
<input type=submit value="Submit"/>
</form>
</body>
</html>

The source code for GetCookiesServlet.java invokes the getCookies( ) method to read any cookies that are included in the HTTP GET request.
The names and values of these cookies are then written to the HTTP response.

20 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets

Observe that the getName( ) and getValue( ) methods are called to obtain this information.
In this example, an expiration date is not explicitly assigned to the cookie via the setMaxAge( ) method of Cookie. Therefore, the cookie expires
when the browser session ends.
You can experiment by using setMaxAge( ) and observe that the cookie is then saved to the disk on the client machine.
GetCookiesServlet.java
package basic;

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

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* @author Bemesha
*/
public class GetCookiesServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Get cookies from header of HTTP request.
Cookie[] cookies = request.getCookies();

// Display these cookies.


response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<B>");
for(int i = 0; i < cookies.length; i++) {
String name = cookies[i].getName();
String value = cookies[i].getValue();
pw.println("name = " + name +
"; value = " + value);
}
pw.close();
}
}

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>GetCookiesServlet</servlet-name>
<servlet-class>basic.GetCookiesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetCookiesServlet</servlet-name>

21 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets

<url-pattern>/GetCookiesServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

Execution:

************************************************

22 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets

Session Tracking
Session Tracking:
 HTTP is a stateless protocol.
 Each request is independent of the previous one.
 However, in some applications, it is necessary to save state information so that information can be collected from
several interactions between a browser and a server. Sessions provide such a mechanism.
 A session can be created via the getSession( ) method of HttpServletRequest.
 An HttpSession object is returned. This object can store a set of bindings that associate names with objects.
 The setAttribute( ), getAttribute( ), getAttributeNames( ), and removeAttribute( ) methods of HttpSession manage
these bindings.
 It is important to note that session state is shared among all the servlets that are associated with a particular client.

How to use session state?


Example:
 The getSession( ) method gets the current session.
- A new session is created if one does not already exist.
 The getAttribute( ) method is called to obtain the object that is bound to the name “date”.
- That object is a Date object that encapsulates the date and time when this page was last accessed.
- (Of course, there is no such binding when the page is first accessed.)
- A Date object encapsulating the current date and time is then created.
 The setAttribute( ) method is called to bind the name “date” to this object.

Program:
package basic;

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

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DateServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

// Get the HttpSession object.


HttpSession hs = request.getSession(true);

// Get writer.
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.print("<B>");

23 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets

// Display date/time of last access.


Date date = (Date)hs.getAttribute("date");
if(date != null)
{
pw.print("Last access: " + date + "<br>");
}

// Display current date/time.


date = new Date();
hs.setAttribute("date", date);
pw.println("Current date: " + date);
}
}
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>DateServlet</servlet-name>
<servlet-class>basic.DateServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DateServlet</servlet-name>
<url-pattern>/DateServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>

Execution in Netbeans:

Running first time:


When you first request this servlet, the browser displays one line with the current date and time information.

24 | P a g e H.Bemesha Smitha,AP/IT,
LICET
IT6503-Web Programming Unit-4: Servlets

Running Second Time:


On subsequent invocations, two lines are displayed.
The first line shows the date and time when the servlet was last accessed. The second line shows the current date and
time.

***************************************************************

25 | P a g e H.Bemesha Smitha,AP/IT,
LICET

You might also like