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

Mod 4

The document discusses servlets and their advantages over CGI programs. It begins by explaining how CGI programs work and their drawbacks, such as high response times and lack of scalability. It then introduces servlets as a solution developed by Sun Microsystems. The key points made about servlets are that they are server-side programs that provide dynamic web content and have advantages like better performance, portability, security and scalability compared to CGI. The document also describes the lifecycle of a servlet, including initialization, processing requests, and destruction. It concludes by outlining the steps to create a servlet application using Tomcat, such as setting up the directory structure, creating and compiling a servlet class, and defining the deployment

Uploaded by

Meera Sahoo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views

Mod 4

The document discusses servlets and their advantages over CGI programs. It begins by explaining how CGI programs work and their drawbacks, such as high response times and lack of scalability. It then introduces servlets as a solution developed by Sun Microsystems. The key points made about servlets are that they are server-side programs that provide dynamic web content and have advantages like better performance, portability, security and scalability compared to CGI. The document also describes the lifecycle of a servlet, including initialization, processing requests, and destruction. It concludes by outlining the steps to create a servlet application using Tomcat, such as setting up the directory structure, creating and compiling a servlet class, and defining the deployment

Uploaded by

Meera Sahoo
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

MODULE - 4

SERVLETS

Introduction to Web

The web clients make requests to web server. When a server answers a request, it usually sends
some type of content(MIME- Multi purpose Internet Mail Exchange) to the client. The client uses web
browser to send request to the server. The server often sends response to the browser with a set of
instructions written in HTML(HyperText Markup Language)

Before Servlets, CGI(Common Gateway Interface) programming was used to create web applications.
Here's how a CGI program works :

Drawbacks of CGI programs


 High resposne time because CGI programs execute in their own OS shell.
 CGI is not scalable.
 CGI programs are not always secure or object-oriented.
 It is Platform dependent.

Because of these disadvantages, developers started looking for better CGI solutions. And then Sun
Microsystems developed Servlet as a solution.

Servlet
Servlet technology is used to create web application (resides at server side and generates dynamic web
page).
Servlet can be described in many ways, depending on the context.
 Servlet is server side program.
 Servlet is an API that provides many interfaces and classes.
 Servlet is a web component that is deployed on the server to create dynamic web page.

Advantages of using Servlets


1. better performance: because it creates a thread for each request not process.
2. Portability: Servlets are platform independent because it uses java language.
3. Robust: Servlets are managed by JVM so we don't need to worry about memory leak, garbage
collection etc.
4. Secure: servlets are object oriented and runs inside JVM.
5. Servlets are scalable.

Life Cycle of a Servlet


 Java Servlets are programs that run on a Web or Application server
 Act as a middle layer between a request coming from a Web browser or other
HTTP client and databases or applications on the HTTP server.
 Using Servlets, you can collect input from users through web page forms,
present records from a database or another source, and create web pages
dynamically.
 Servlets are server side components that provide a powerful mechanism for

developing web applications.


A servlet life cycle can be defined as the entire process from its creation till the
destruction. The following are the paths followed by a servlet
 The servlet is initialized by calling the init () method.
 The servlet calls service() method to process a client's request.
 The servlet is terminated by calling the destroy() method.
 Finally, servlet is garbage collected by the garbage collector of

the JVM. Now let us discuss the life cycle methods in details.

The init() method :

 The init method is designed to be called only once.


 It is called when the servlet is first created, and not called again for each user
request. So, it is used for one-time initializations, just as with the init method of
applets.
 The servlet is normally created when a user first invokes a URL corresponding to
the servlet, but you can also specify that the servlet be loaded when the server is
first started.
 The init() method simply creates or loads some data that will be used throughout
the life of the servlet.

The init method definition looks like this:

public void init() throws ServletException {


// Initialization code...
}
The service() method :

 The service() method is the main method to perform the actual task.
 The servlet container (i.e. web server) calls the service() method to handle
requests coming from the client( browsers) and to write the formatted response
back to the client.Each time the server receives a request for a servlet, the
server spawns a new thread and calls service. The service() method checks the
HTTP request type (GET, POST, PUT, DELETE, etc.) and calls doGet, doPost,
doPut, doDelete, etc. methods as appropriate.

Signature of service method:


public void service(ServletRequest request, ServletResponse
response) throws ServletException, IOException
{
}

 The service () method is called by the container and service method invokes
doGe, doPost, doPut, doDelete, etc.methods as appropriate.
 So you have nothing to do with service() method but you override either doGet()
or doPost() depending on what type of request you receive from the client.
 The doGet() and doPost() are most frequently used methods with in each service
request. Here is the signature of these two methods.

The doGet() Method


A GET request results from a normal request for a URL or from an HTML form that
has no METHOD specified and it should be handled by doGet() method.

public void doGet(HttpServletRequest request, HttpServletResponse


response) throws ServletException, IOException {
// Servlet code
}

The doPost() Method


A POST request results from an HTML form that specifically lists POST as the
METHOD and it should be handled by doPost() method.
public void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException
{
// Servlet code
}

The destroy() method :


 The destroy() method is called only once at the end of the life cycle of a servlet.
 This method gives your servlet a chance to close database connections, halt
background threads, write cookie lists or hit counts to disk, and perform other
such cleanup activities.
 After the destroy() method is called, the servlet object is marked for garbage
collection. The destroy method definition looks like this:

public void destroy() {


// Finalization code...
}

Steps to Create Servlet Application using tomcat server


To create a Servlet application you need to follow the below mentioned steps. These steps are common
for all the Web server. In our example we are using Apache Tomcat server. Apache Tomcat is an open
source web server for testing servlets and JSP technology. Create directory structure for your
application.
1. Create directory structure for your application.
2. Create a Servlet
3. Compile the Servlet
4. Create Deployement Descriptor for your application
5. Start the server and deploy the application
1. Creating the Directory Structure
Sun Microsystem defines a unique directory structure that must be followed to create a servlet
application.
Create the above directory structure
inside Apache-Tomcat\webapps
directory.

All HTML, static files(images, css


etc) are kept directly under Web
application folder.

While all the Servlet classes are kept


inside classes folder.

The web.xml (deployement


descriptor) file is kept under WEB-INF
folder.

2. Creating a Servlet

There are three different ways to create a servlet.


 By extending HttpServlet class
 By extending GenericServlet class
 By implementing Servlet interface

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

// extending HttpServlet class

public MyServlet extends HttpServlet


{
public void doGet(HttpServletRequest request,HttpServletResposne response)
throws ServletException
{
response.setContentType("text/html"); // set content type
//get the stream to write the data
PrintWriter out = response.getWriter(); // create printwriter object
out.println("<h1>Hello Readers</h1>"); // print ur content on client web browser
}
}
Write above code and save it as MyServlet.java anywhere on your PC. Compile it from there
and paste the class file into WEB-INF/classes/ directory that you have to create inside
Tomcat/webapps directory.

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

// extending GenericServlet class

public MyServlet extends GenericServlet


{
public void service(ServletRequest request,ServletResponse response)
throws IOException,ServletException{
{
response.setContentType("text/html"); // set content type
//get the stream to write the data
PrintWriter out = response.getWriter(); // create printwriter object
out.println("<h1>Hello Readers</h1>"); // print ur content on client web browser
}
}

3. Compiling a Servlet
To compile a Servlet a JAR file is required. Different servers require different JAR files. In Apache
Tomcat server servlet-api.jar file is required to compile a servlet class.

□ Download servlet-api.jar file.


□ Paste the servlet-api.jar file inside Java\jdk\jre\lib\ext directory.
NOTE: After compiling your Servlet class you will have to paste the class file into WEB-INF/classes/
directory.

4. Create Deployment Descriptor


Deployment Descriptor(DD) is an XML document that is used by Web Container to run Servlets and
JSP pages.
web.xml file

<web-app>
<servlet>
<servlet-name> MyServlet </servlet-name>
<servlet-class> MyServlet </servlet-class>
</servlet>

<servlet-mapping>
<servlet-name> MyServlet </servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
</web-app>

5. Starting Tomcat Server for the first time


set JAVA_HOME or JRE_HOME in environment variable (It is required to start server).
Go to My Computer properties -> Click on advanced tab then environment variables -> Click on
the new tab of user variable -> Write JAVA_HOME in variable name and paste the path of jdk folder in
variable value -> ok

Run Servlet Application


Open Browser and type http:localhost:8080/First/hello

Servlet API
Servlet API consists of two important packages that encapsulates all the important classes and interface,
namely :
1. javax.servlet.*;

INTERFACES CLASSES
Servlet ServletInputStream
ServletContext ServletOutputStream
ServletConfig ServletException
ServletRequest UnavailableException
ServletResponse GenericServlet

Interface Summary

Servlet Defines methods that all servlets must implement.

ServletRequest Defines an object to provide client request information to a servlet.

ServletResponse Defines an object to assist a servlet in sending a response to the client.

A servlet configuration object used by a servlet container to pass information to a


ServletConfig
servlet during initialization.

Defines a set of methods that a servlet uses to communicate with its servlet
ServletContext container, for example, to get the MIME type of a file, dispatch requests, or write
to a log file.
Interface Servlet

Interface ServletRequest
Interface ServletResponse

Interface ServletConfig

Interface ServletContext
Class Summary

GenericServlet Defines a generic, protocol-independent servlet.

Provides an input stream for reading binary data from a client request,
ServletInputStream
including an efficient readLine method for reading data one line at a time.

ServletOutputStream Provides an output stream for sending binary data to the client.

ServletException Defines a general exception a servlet can throw when it encounters difficulty.

Defines an exception that a servlet or filter throws to indicate that it is


UnavailableException
permanently or temporarily unavailable.

Class GenericServlet
java.lang.Object
javax.servlet.GenericServlet
All Implemented Interfaces: Servlet, ServletConfig

Class ServletInputStream
java.lang.Object
java.io.InputStream
javax.servlet.ServletInputStream

Method Summary

int readLine(byte[] b, int off, int len)


Reads the input stream, one line at a time.

Class ServletOutputStream

Method Summary

void println()

void print(java.lang.String s)
Writes a String to the client, without a carriage return-line feed (CRLF) character at
the end.
void println()
Writes a carriage return-line feed (CRLF) to the client.

void println(java.lang.String s)
Writes a String to the client, followed by a carriage return-line feed (CRLF).

2. javax.servlet.http.*;

CLASSES
INTERFACES
Cookie HttpServletRequest

HttpServlet HttpServletResponse

HttpSessionBindingEvent HttpSession

Interface Summary

Extends the ServletRequest interface to provide request information for


HttpServletRequest
HTTP servlets.

Extends the ServletResponse interface to provide HTTP-specific


HttpServletResponse
functionality in sending a response.

Provides a way to identify a user across more than one page request or
HttpSession
visit to a Web site and to store information about that user.
Interface HttpServletResponse
Interface HttpServletRequest
Interface HttpSession

Class Summary

Creates a cookie, a small amount of information sent by a servlet to a Web


Cookie
browser, saved by the browser, and later sent back to the server.

Provides an abstract class to be subclassed to create an HTTP servlet


HttpServlet
suitable for a Web site.

Events of this type are either sent to an object that implements


HttpSessionBindingListener when it is bound or unbound from a session, or
HttpSessionBindingEvent to a HttpSessionAttributeListener that has been configured in the
deployment descriptor when any attribute is bound, unbound or replaced in
a session.

This is the class representing event notifications for changes to sessions


HttpSessionEvent
within a web application.
Class Cookie
Class HttpServlet

Class HttpSessionBindingEvent

Method Summary

java.lang.String getName()
Returns the name with which the attribute is bound to or unbound from the
session.

HttpSession getSession()
Return the session that changed.

java.lang.Object getValue()
Returns the value of the attribute that has been added, removed or replaced.

Class HttpSessionEvent

Method Summary

HttpSession getSession()
Return the session that changed.

Reading Servlet parameters


In this example, we will show how a parameter is passed to a
index.html
<form method="post" action="check">
Name <input type="text" name="user" >
<input type="submit" value="submit">
</form>

MyServlet.java
public class MyServlet extends HttpServlet {

protected void doPost(request, response){


... // set content type . . .
String user=request.getParameter("user");

out.println("<h2> Welcome "+user+"</h2>");


}
}
NOTE: getParameter( ) returns string to get int value use
Integer.parseInt(“sting”);
Handling HTTP request and Response

HttpServlet class provides various methods that handle various types of HTTP request.
A servlet typically must override at least one method, usually one of these:
 doGet, if the servlet supports HTTP GET requests
 doPost, for HTTP POST requests
 doPut, for HTTP PUT requests
 doDelete, for HTTP DELETE requests

GET and POST methods are commonly used when handling form input.
NOTE: By default a request is Get request.
Difference between GET and POST requests
GET Request POST Request

Data is sent in header to the server Data is sent in the request body

Get request can send only limited amount of data Large amount of data can be sent.

Get request is not secured because data is exposed Post request is secured because data is not exposed
in URL in URL.
Session

Session simply means a particular interval of time. Session Tracking is a way to maintain state
(data) of an user. It is also known as session management in servlet.
Http protocol is a stateless so we need to maintain state using session tracking techniques. Each time
user requests to the server, server treats the request as the new request. So we need to maintain the state
of an user to recognize to particular user.
There are 2 techniques used in Session tracking:
1. Cookies
2. HttpSession
Cookies in Servlet

A cookie is a small piece of information that is persisted between the multiple client requests.
By default, each request is considered as a new request. In cookies technique, we add cookie with
response from the servlet. So cookie is stored in the cache of the browser. After that if request is sent by
the user, cookie is added with request by default. Thus, we recognize the user as the old user.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.
Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

Example demonstrating usage of Cookies

index.html
<form method="post" action=" MyServlet ">
Name:<input type="text" name="user" /><br/>
Password:<input type="text" name="pass" ><br/>
<input type="submit" value="submit">
</form>

MyServlet.java
public class MyServlet extends HttpServlet {

protected void doPost(HttpServletRequest request, HttpServletResponse response)


{ // . . . . .
String name = request.getParameter("user");
String pass = request.getParameter("pass");

if(pass.equals("1234"))
{
Cookie ck = new Cookie("username",name);
response.addCookie(ck);

//response.sendRedirect("First");//call ur servlet

//creating submit button


out.print("<form action= First >");
out.print("<input type='submit' value='go'>");
out.print("</form>");
}
}
}

First.java
public class First extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
{ // . . .
Cookie[] cks = request.getCookies();
out.println("Welcome "+cks[0].getValue());
}
}

Useful Methods of Cookie class


Method Description

public void setMaxAge(int


Sets the maximum age of the cookie in seconds.
expiry)

Returns the name of the cookie. The name cannot be changed after
public String getName()
creation.

public String getValue() Returns the value of the cookie.

public void setName(String


changes the name of the cookie.
name)

public void setValue(String


changes the value of the cookie.
value)
Other methods required for using Cookies
For adding cookie or getting the value from the cookie, we need some methods provided by other
interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to add
cookie in response object.
2. public Cookie[ ] getCookies():method of HttpServletRequest interface is used to return all the
cookies from the browser.

HttpSession

HttpSession object is used to store entire session with a specific client. We can store, retrieve and
remove attribute from HttpSession object. Any servlet can have access to HttpSession object
throughout the getSession() method.

Some Important Methods of HttpSession

Methods Description

returns the time when the session was created, measured in


long getCreationTime()
milliseconds since midnight January 1, 1970 GMT.
returns a string containing the unique identifier assigned to the
String getId()
session.

int getMaxInactiveInterval() returns the maximum time interval, in seconds.

void invalidate() destroy the session

boolean isNew() returns true if the session is new else false

Complete Example demonstrating usage of HttpSession

index.html
<form method="post" action="Validate">
User: <input type="text" name="uname " /><br/>
<input type="submit" value="submit">
</form>

Validate.java
public class Validate extends HttpServlet {

protected void doPost(request, response)


{
// . . . .
String name = request.getParameter("user");
//creating a session
HttpSession session = request.getSession();
session.setAttribute("user", uname);
response.sendRedirect("Welcome");
}
}
Welcome.java
public class Welcome extends HttpServlet {

protected void doGet(request, response){


// . . . .
HttpSession session = request.getSession();
String user = (String)session.getAttribute("user");
out.println("Hello "+user);
}
}
JSP 
 Java Server Page technology is used to create dynamic web applications.
 JSP pages are easier to maintain then a Servlet.
 JSP pages are opposite of Servlets as a servlet adds HTML code inside Java code, while JSP
 adds Java code inside HTML using JSP tags.
 Everything a Servlet can do, a JSP page can also do it.
 JSP enables us to write HTML pages containing tags, inside which we can include powerful Java
programs
Why JSP is preffered over servlets?
 JSP provides an easier way to code dynamic web pages.
 JSP does not require additional files like, java class files, web.xml etc
 Any change in the JSP code is handled by Web Container(Application server like tomcat), and
doesn't require re-compilation.
 JSP pages can be directly accessed, and web.xml mapping is not required like in servlets.
Advantage of JSP
 Easy to maintain and code.
 High Performance and Scalability.
 JSP is built on Java technology, so it is platform independent.
Life cycle of a JSP Page
The JSP pages follows these phases:
 Initialization ( jspInit() method is invoked by the container).
 Request processing ( _jspService() method is invoked by the container).
 Destroy ( jspDestroy() method is invoked by the container).

In the end a JSP becomes a Servlet


 As depicted in the above diagram, JSP page is translated into servlet by the help of JSP
translator. The JSP translator is a part of webserver that is responsible to translate the JSP page
into servlet. After that Servlet page is compiled by the compiler and gets converted into the class
file.
 Web Container translates JSP code into a servlet class source(.java) file, then compiles that
into a java servlet class. In the third step, the servlet class bytecode is loaded using classloader.
The Container then creates an instance of that servlet class.
 The initialized servlet can now service request. For each request the Web Container call the
_jspService() method. When the Container removes the servlet instance from service, it calls the
jspDestroy() method to perform any required clean up.
Do we need to follow directory structure to run a simple JSP ?
No, put jsp files in a folder directly and deploy that folder. It will be running fine. But if you are using
bean class, Servlet or tld file then directory structure is required.
JSP Scripting Element
JSP Scripting element are written inside <% %> tags. These code inside <% %> tags are processed by
the JSP engine during translation of the JSP page. Any other text in the JSP page is considered as HTML
code or plain text.

There are five different types of scripting elements

1. JSP scriptlet tag A scriptlet tag is used to execute java source code in JSP.
<% java source code %>

In this example, we are displaying a welcome message.


<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>

2. JSP Declaration Tag


The JSP declaration tag is used to declare variables, objects and methods.
The code written inside the jsp declaration tag is placed outside the service() method of auto generated
servlet.
So it doesn't get memory at each request.
<%! field or method declaration %>

Difference between JSP Scriptlet tag and Declaration tag


Jsp Scriptlet Tag Jsp Declaration Tag
The jsp scriptlet tag can only declare variables The jsp declaration tag can declare variables as well
not methods. as methods.
The declaration of scriptlet tag is placed inside The declaration of jsp declaration tag is placed
the _jspService() method. outside the _jspService() method.

declaration tag with variable declaration tag that declares method


In index.jsp
index.jsp <html>
<html> <body>
<body> <%!
<%! int data=50; %> int cube(int n){
<%= "Value of the variable is:"+data %> return n*n*n*;
</body> }
</html> %>
<%= "Cube of 3 is:"+cube(3) %>

3. JSP Expression Tag


Expression Tag is used to print out java language expression that is put between the tags. An expression
tag can hold any java language expression that can be used as an argument to the out.print() method.
Syntax of Expression Tag
<%= JavaExpression %>

<%= (2*5) %> //note no ; at end of statement.


4. JSP directives
The jsp directives are messages that tells the web container how to translate a JSP page into the
corresponding servlet.
Syntax <%@ directive attribute="value" %>
There are three types of directives:
A. import directive
B. include directive
C. taglib directive
a. import
The import attribute is used to import class,interface or all the members of a package.It is similar to
import keyword in java class or interface.
<%@ page import="java.util.Date" %>
Today is: <%= new Date() %>
b. Include Directive
The include directive tells the Web Container to copy everything in the included file and paste it into
current JSP file. The include directive is used to include the contents of any resource it may be jsp file,
html file or text file. Syntax of include directive is:
<%@ include file="filename.jsp" %>

c. JSP Taglib directive


The JavaServer Pages API allow you to define custom JSP tags that look like HTML or XML tags and a
tag library is a set of user-defined tags that implement custom behavior. The taglib directive declares
that your JSP page uses a set of custom tags, identifies the location of the library, and provides means
for identifying the custom tags in your JSP page.
syntax <%@ taglib uri = "uri" prefix = "prefixOfTag" >
For example, suppose the custlib tag library contains a tag called hello. If you wanted to use the hello
tag with a prefix of mytag, your tag would be <mytag:hello> and it will be used in your JSP file as
follows

<%@ taglib uri = "http://www.example.com/custlib" prefix = "mytag" %>

<html>
<mytag:hello/>
</body>
</html>
5. JSP Comments
JSP comment marks text or statements that the JSP container should ignore.
syntax of the JSP comments <%- - This is JSP comment - -%>
Request String
 The query string contains the attribute & the value of the html form or JSP form, which sends
with the POST /GET method to Servlet or JSP page for any request.
 A query string is the part of a URL which is attached to the end, after the file name. It begins
with a question mark and usually includes information in pairs. The format is parameter=value,
as in the following example:
www.mediacollege.com/cgi-bin/myscript.cgi?name=”Umesh”
 Query strings can contain multiple sets of parameters, separated by an ampersand (&) like so:
www.mediacollege.com/cgi-bin/myscript.cgi?fname=”Umesh”&lname=”M”
 to parse this info we use method of JSP request object
 we can easily get using request.getParameter() with name of parameter as argument, to get its
value.
welcome.jsp
index.html
<html>
<form action="welcome.jsp"> <body>
<input type="text" name="uname"> <%
<input type="submit" value="go"><br/> String
</form> name=request.getParameter("uname");
out.print("Welcome "+name);
welcome.jsp session.setAttribute("user",name);

<% <a href="second.jsp">second jsp page</a>


String name=request.getParameter("uname");
out.print("welcome "+name); %>
%> </body>
</html>
Following are the JSP implicit object
Implicit
Description
Object
request The HttpServletRequest object associated with the request.
The HttpServletRequest object associated with the response that is sent back to the
response
browser.
out The JspWriter object associated with the output stream of the response.
session The HttpSession object associated with the session for the given user of request.

Session implicit object (concept same as servlet)


In JSP, session is an implicit object of type HttpSession. The Java developer can use this object to
set,get or remove attribute or to get session information.
Example of session implicit object
index.html

<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

second.jsp

<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
//other methods of Session what u used in servlets can be used here.
Cookie (concept same as servlet)
Step 1: Creating a Cookie object
Cookie cookie = new Cookie("key","value");
Step 2: Setting the maximum age
You use setMaxAge to specify how long (in seconds) the cookie should be valid. The following code
will set up a cookie for 24 hours.
cookie.setMaxAge(60*60*24);
Step 3: Sending the Cookie into the HTTP response headers
You use response.addCookie to add cookies in the HTTP response header as follows
response.addCookie(cookie);

<%
// Create cookies for first and last names.
Cookie firstName = new Cookie("first_name", request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name", request.getParameter("last_name"));

// Set expiry date after 24 Hrs for both the cookies.


firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);

// Add both the cookies in the response header.


response.addCookie( firstName );
response.addCookie( lastName );
%>

<html>
<body>
p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p>
<p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p>
</body>
</html>
Reading Cookies with JSP
<html>
<body>
<%
Cookie cookie = null;
Cookie[] cookies = null;

// Get an array of Cookies associated with the this domain


cookies = request.getCookies();

if( cookies != null ) {


out.println("<h2> Found Cookies Name and Value</h2>");

for (int i = 0; i < cookies.length; i++) {


cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println("<h2>No cookies founds</h2>");
}
%>
</body>

</html>
//other methods of Cookie what u used in servlets can be used here.

You might also like