0% found this document useful (0 votes)
3 views52 pages

Unit 6

Uploaded by

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

Unit 6

Uploaded by

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

Servlets

Unit IV
By Ghazala Khan
Web and Web Application
Web consists of billions of clients and servers connected through wires
and wireless networks.
The web clients make requests to web servers. The web servers receive the
requests, find the resources and return the responses to the clients.

■ A web application is an application accessible from the web.


■ A Web application is a web site with dynamic functionality on
the server. Eg. Google, Twitter.
■ A web application has web components like Servlet, JSP, Filter etc. and
other components such as HTML.
■ The web components typically execute in Web Server and respond to
HTTP request.
- Users request web pages by entering a URL (youtube.com) into a browser(Chrome).
- The browser generates an HTTP request to the web server.
- The web server finds the requested file and sends it back to the browser in a response.
- HTTP response includes MIME (Multipurpose Internet Mail Extensions) , for content
type in the header (e.g.,text/plain- plain ASCII text, text/html- page with HTML tags.).

- Before, dynamic pages were constructed using the Common Gateway Interface (CGI).
- A separate process (CGI) was created for each client request, and this process
communicated with databases to get the required data, in languages like C, C++, Perl.
- CGI programs read data from the HTTP request and wrote data to the HTTP response.

- CGI had significant performance issues because a separate process had to be created
for each client request, which was resource-intensive ( processor and memory usage).
- Opening and closing Db connections for each request was costly.
- Platform Dependent
Alternative methods, such as Servlets, were introduced to solve these problems.
1. To request a page “abc.html” that will be built (at that time), send a request to the server.
2. Server doesn’t have it and has to build that page, it goes to a helper application (web container).
3. Web/Servlet container contains servlets. We’re using Apache Tomcat web container.
4. Servlets are Java files on the internet, take a request, process it, give an HTML page as response.
5. Request goes to Tomcat, Tomcat doesn’t have a page called abc.html, so execute a servlet..
6. You can have multiple servlets and many requests for one servlet.
7. Servlet name for this page is AddServlet, so when abc.html is being requested, this means
AddServlet is to be executed. This is taken care of by Deployment Descriptor.
8. Deployment Descriptor (web.xml) specifies for which request which servlet will be called.
9. In xml file, Servlet tag- class name, servlet-mapping tag - url (abc.html).
10. Extends HTTPServlet, so it meets all requirements, take request, process, give response. Response
goes to client in response object format.
11. Can use annotations to avoid xml files.
Serve
r ■ It is a running program or software that provides services.
■ Two types:

■ EJB(Enterprise Java Beans): architecture that simplifies building


server-side applications
SERVLETS DEFINITION
There are two types of servers: 1) Web Servers 2) Application Servers
Servlets are small programs that execute on the server in a web connection to:-
Handle client request, process the request, generate dynamic response

It is similar to php, spring, python that are server side technologies.


Just as applets dynamically extend the functionality of a web browser, servlets
dynamically extend the functionality of a web server.

1. Better performance: Servlets run within the web server's address space
(memory area allocated for the web server to run its processes and handle
requests), so there's no need to create a new process for each client request,
making them faster.
2. Platform-independent: Since servlets are written in Java, they can run on any
platform that supports Java.
3. Security: The Java security manager ensures that servlets follow specific rules
to protect the server's resources.
4. Full Java functionality: Servlets can use all the Java libraries, allowing them to
interact with applets, databases, and other programs through mechanisms like
sockets and RMI.
5. Servlet technology is robust and scalable because of Java language.
Servlet life cycle
Assume that user enters a (URL) to a web browser. Browser generates an HTTP request for. This
request is then sent to the appropriate server.
Second, this HTTP request is received by the web server. The server gives 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 to
configure.

Fourth, the server invokes the service( ) method of the servlet. The service( ) method is called for
each HTTP request to process it.
● It is possible for the servlet to read data that has been provided in the HTTP request.
● It may also create 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.

Finally, the server may decide to unload the servlet from its memory. The algorithms for this is
specific to each server. The server calls the destroy( ) method to release 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.
■ Each servlet instance is loaded once.
■ Each execution happens in a separate thread
■ Three methods:
■ init() : call only once to initialize servlet.
■ service() : Call for every request.
■ destroy() : call only once

STEPS:-
1. Load Servlet Class.
2. Create Instance of Servlet.
3. Call the servlets init() method.
4. Call the servlets service() method.
5. Call the servlets destroy() method.
Note: Step 1,2,3 executed only once when servlet is
initially loaded.
Step 4 executed "N"-times whenever http request
comes
Step 5 executed to destroy servlet means unload servlet
class

Method service() is invoked every time a request comes.


It spawns off threads to perform doGet or doPost based
on the method invoked.
■ A Servlet container (like Apache Tomcat) is designed to host and manage
multiple web applications together at the same time.
■ Each web application runs in its own isolated environment within the
container. This means it has its own resources and servlets, separate
from other applications.

Multiple Servlets per Application:


● Each web application can contain multiple servlets, each dedicated to
handling specific requests or tasks.

It provides runtime environment for JavaEE applications.


It performs many operations that are given below:
■ Life Cycle Management
■ Multithreaded support
■ Security etc.
HTT
■HTTPPis a protocol that clients and servers
use on the web to communicate.
■It is similar to other internet protocols
such as SMTP (Simple Mail Transfer
Protocol) and FTP (File Transfer Protocol)
but there is one fundamental difference.
■HTTP is a stateless protocol.
■The client sends an HTTP request and the
server answers with an HTML page to the
client, using HTTP.
HTTP methods
Method Name Description
OPTIONS Request for communication options that are available
on the request/response chain.
GET Request to retrieve information from server using a given
URI.
HEAD Identical to GET except that it does not return a
message-body, only the headers and status line.
POST Request for server to accept the message in the body of
HTTP method.
DELETE Request for the Server to delete the resource.
CONNECT Reserved for use with a proxy that can switch to being a
tunnel.
PUT This is same as POST, but POST is used to create, PUT can
be used to create as well as update. It replaces all current
representations of the target resource with the uploaded
content. Mr. Nilesh Vishwasrao
Anatomy of HTTP GET
Request
■ Get request contains path to server and the
parameters added to it.
Anatomy of HTTP
POST
Reque
st are used to make more complex requests on the server. For
■ Post requests
instance, if a user has filled a form with multiple fields and the application
wants to save all the form data to the database. Then the form data will
be sent to the server in POST request body, which is also known as
Message body.
HTTP
methods
GET Request POST Request
Data is sent in header to the Data is sent in the request
server body
Get request can send Large amount of data can
only limited amount of be sent.
data
Get request is not secured Post request is secured
because data is exposed in because data is not
URL exposed in URL.
Get request can be Post request cannot be
bookmarked and is more bookmarked.
efficient.
HTTP Request and
Response
■ Browser sends an HTTP request to the Java web server.
■ The web server checks if the request is for a servlet. If it is,
the servlet container is passed the request.
■ The servlet container will then find out which servlet the
request is for, and activate that servlet.
■ The servlet is activated by calling the
Servlet.service()method.
■ Once the servlet has been activated the servlet processes the
request, and generates a response. The response is then sent
back to the browser.
Content
Type
Content Type is also known as MIME (Multipurpose internet Mail
Extension) Type.
It is a HTTP header that provides the description about what are
you sending to the browser.
■ text/html
■ text/plain
■ application/msword
■ application/vnd.ms-excel
■ application/jar
■ application/pdf
■ application/octet-stream
■ application/x-zip
■ images/jpeg
video/quick

Servlet API
Servlet API consists of two important packages that
encapsulates all the important classes and interface,
namely :

1) javax.servlet
2) javax.servlet.http
1)javax.servlet package
The java.servlet Package
The javax.servlet package contains a number of
interfaces and classes that establish the framework in
which servlets operate.
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.
javax.servlet package:
interfaces
Interfaces Description
Servlet Declare life cycle methods for servlet. To
implement this interface we have to extend
GenericServlet or HttpServlet classes.

ServletConfig Helps servlet to get initialization parameter,


which means the startup information/basic
information about servlet.

ServletContext Allows servlet to log events and access


information about their environment
ServletRequest Used to read data from client request
ServletResponse Used to send data to client response
javax.servlet package:
classes
Classes Description
GenericServlet Used to create servlet (Protocol
independent). Implements Servlet and
ServletConfig interfaces.
ServletInputStream Provides an input stream for reading
requests from client.
ServletOutputStream Provides an output stream for writing
responses to a client
ServletException For handling exception, indicates error
Occurred
UnavailableException For handling exception: indicates servlet
not available
javax.servlet package: interfaces
1)Servlet Interface:
Methods
2) ServletConfig interface
● ServletConfig object created by container for each servlet.
● The interface allows a servlet to obtain configuration data
when it is loaded from web.xml file.
● No need to edit servlet file if info is modified from web.xml.

METHODS
● public String getInitParameter(String name):
Returns the value for the parameter “name”.
● Enumeration<String> getInitParameterNames():
Returns an enumeration of all the initialized
parameter names.
● public String getServletName():
Returns the name of the invoking servlet.
● public ServletContext getServletContext():
Returns the context (details) for this servlet.
ServletContext interface
■ Object of ServletContext is created by the web container
at time of deploying web application, only one
ServletContext object per web application.

■ This object can be used to get configuration


information from web.xml file.
METHODS
1. `Object getAttribute(String attr)`
- Purpose: Retrieves value of a server attribute specified by `attr`.
- Eg. returns value “john123” for an attribute “user” from server.

2. `String getMimeType(String file)`


- Purpose: Returns the MIME type of a given file name (e.g.,
`text/html` for `.html` files, `image/png` for `.png` files).
- Eg. image type

3. `String getRealPath(String vpath)`


- Purpose: Returns the absolute file system path corresponding to a
relative path (`vpath`) within the application.
Eg. your web application is deployed at “/var/www/myapp”,
you call getRealPath("/images/photo.jpg"),
it might return: “/var/www/myapp/images/photo.jpg”
4. `String getServerInfo()`
- Purpose: Provides info about server, such as the server name and version.
- Eg. Obtains information about the server, including its name and version.

5. `void log(String s)`


- Purpose: Writes a message (`s`) to the server’s log.
- Eg. Adds the message "Application started successfully." to the server's log.

6. `void log(String s, Throwable e)`


- Purpose: Writes a message (`s`) and a stack trace for an exception (`e`) to
the server’s log.
- Eg. Adds the msg "Error occurred:" along with the details of an exception.

7. `void setAttribute(String attr, Object val)`


- Purpose: Sets an attribute in the with a specified name,; (`attr`) and (`val`).
- Eg. Save the current user as "loggedInUser" so that it can be accessed
later in the application.

■ A server log file is a file where the server records events,


messages, errors, and other operational details about how it’s
functioning.
ServletRequest interface
Helps to obtain information about a client request
- `getAttribute(String attr)`: Retrieves the value of an attribute.
- Eg: getAttribute("user") returns "John Doe".

- `getCharacterEncoding()`: Returns request's char. encoding.


- Eg: returns `"UTF-8"`.

- `getContentLength()`: Returns size of request body in bytes.


- Eg: returns 200 for a 200-byte request body.

- `getContentType()`: Returns the MIME type of the request.


- Eg: returns `"text/html"`.

- `getInputStream()`: Gets input stream to read binary data from the request.
- Eg: `getInputStream().read()` reads bytes from request body through inputstream

- `getParameter(String pname)`: Retrieves parameter value by name.


- Eg: `getParameter("username")` returns "johndoe123".

- `getParameterNames()`: Returns all parameter names in the request.


- Eg: returns enumeration (list) of all parameters ["user", "email",”password”].

- `getParameterValues(String pname)`: Returns all values for a parameter.


- Eg: returns `["admin", "user"]` for pname=’username’.
- `getProtocol()`: Returns the protocol used in the request.
- Eg: returns `"HTTP/1.1"`.

- `getReader()`: Gets a reader to read text data from the request.


- Example: `getReader().readLine()` reads a line of text from the request.

- `getRemoteAddr()`: Returns the client's IP address.


- Example: returns "192.168.1.10".

- `getRemoteHost()`: Returns the client host name.


- *Example*: returns "client.example.com".

- `getScheme()`: Returns the URL scheme.


- Example: returns "https".

- `getServerName()`: Returns the server's host name.


- Eg: returns "example.com".

- `getServerPort()`: Returns the port number the request was sent to.
- Eg: returns `80` for HTTP.
ServletResponse
Interface
- enables a servlet
- `getCharacterEncoding()`: to create
Returns a response
the character for
encoding for the a
response.
client"UTF-8".
- Eg: returns

- `getOutputStream()`: Gets an output stream to write binary data to the


response.
- Eg: getOutputStream().write(byteArray) writes binary data to the client.

- `getWriter()`: Gets a writer to write character data to the response.


- Eg: `getWriter().write("Hello, world!")` writes text to the client.

- `setContentLength(int size)`: Sets the content length for the response.


- Eg: `setContentLength(150)` sets the response length to 150 bytes.

- `setContentType(String type)`: Sets the content type for the response.


- Example: `setContentType("text/html")` defines the response as HTML
content.
GenericServlet
Class
■ It implements Servlet and ServletConfig interfaces.
■ It provides the implementation of basic life cycle methods of a servlet and
all the methods of these interfaces except the service method (You have to
write code in your servlet class for this method).
■ GenericServlet class can handle any type of request so it is protocol-
independent.
2) The javax.servlet.http package
Classes Description

HttpServletRequest It enables servlets to read data from an


HTTP request
HttpServletRespons It enables servlets to write data to an
e HTTP response
HttpSession It allows to read and write session data.

Classes Description

HttpServlet Used to create http servlet (Protocol


dependent)
Cookie Cookie class allows state information to
be stored on a client machine (Cookies are small
pieces of data stored on the user's browser by a
website to remember information across visits,
such as login status or preferences.)
HttpServletRequest Interface-
enables a servlet to obtain information about a client request.
- String getAuthType(): Returns authentication scheme.
Example: If a site uses basic authentication, it would return "BASIC".

- Cookie[] getCookies(): Returns an array of the cookies in this request.


- Eg, [Cookie(name="session", value="abc123"), Cookie(name="user", value="JohnDoe")].*

- `long getDateHeader(String field)`: Returns the date value for the header named *field*.
- Example: For a "Date" header, it might return "Tue, 20 Jun 2023 15:30:00 GMT."

- `String getHeader(String field)`: Returns the value of the specified header *field* as a string.
- Example: For a "Content-Type" header, it could return "text/html."

- `Enumeration<String> getHeaderNames()`: gives enumeration of all available header names.


- Example: ["Host", "User-Agent", "Content-Type"].

- `int getIntHeader(String field)`: Returns the integer value for the specified header *field*.
- Eg: For "Expires" header, it might return 120 for the number of seconds until expiry.

- String getMethod(): Returns the HTTP method for this request.


- Eg, "POST" for a form submission request.*

- String getPathInfo(): Returns any path info after the servlet path, before a query string.
- Eg: If the URL is https://example.com/app/user/profile/picture?size=large, it would return
"/user/profile/picture".
- String getPathTranslated()
The getPathTranslated() method converts any extra path information in a request
URL into a real path on the server’s file system.
URL: http://example.com/images/user/profile.jpg
Servlet Path: /images Path Info: /user/profile.jpg
server stores resources in directory: "/var/www/images” in its file system.
This would convert path into: "/var/www/images/user/profile.jpg"

- String getQueryString(): Returns any query string in the URL.


- E.g., “https://example.com/app/user/profile/picture?size=large”

- String getRemoteUser(): Returns the name of the user issuing this request.
- E.g., "johndoe"

- String getRequestedSessionId(): Returns the session ID of the request.


*E.g., "XYZ1234567890ABCD" for an active user session.

- String getRequestURI(): Returns the URI, which is the part after the server address.
- Eg., for http://example.com/shop/products/item, returns "/shop/products/item".

- StringBuffer getRequestURL(): Returns the full URL.


- HttpSession getSession(): Returns the session; creates one if absent.
E.g., a session ID like "SESSION123456789" for tracking logged-in status.

- HttpSession getSession(boolean new): manage user sessions in a servlet by either creating a new
session or returning an existing one
E.g., If the new parameter is true, the server will:
● Return the existing session if already exists.
● Create and return a new session if no current session exists.
If the new parameter is false, the server will:
● Return the existing session if there is one.
● Return null if there is no current session

- boolean isRequestedSessionIdFromCookie(): *true* if session ID is in a cookie, else *false*.


*E.g., true, indicating session ID was set via cookies.*

- boolean isRequestedSessionIdFromURL()
- Returns *true* if session ID is in the URL, else *false*. *E.g., false, indicating session ID was not
passed in the URL.*

- boolean isRequestedSessionIdValid()
- Returns *true* if the requested session ID is valid.

A session ID is a unique identifier assigned to each user session, allowing the server to
track and manage the user's activity across multiple requests.
HttpServletResponse
Interface-
void addCookie(Cookie cookie)
enables
● Addsaa servlet
cookie totothe
create
HTTPan HTTP response
response. E.g., Addsto a client. cookie with value
a "session"
"abc123".
boolean containsHeader(String field)
● Returns true if the HTTP response header contains a field named field. E.g.,
Returns true for "Content-Type" if Content-Type is present in header.
String encodeURL(String url)
● Determines if the session ID must be encoded in the URL and returns the modified
or original URL. E.g., Encodes "https://example.com" to include session ID.
String encodeRedirectURL(String url)
● Encodes the session ID in the URL for redirects if needed. E.g., Encodes "
https://example.com/redirect" to include session id if session tracking is needed.
void sendError(int code)
● Sends the error code to the client. E.g., Sends a 404 error code for a missing
page.
void sendError(int code, String msg)
● Sends the error code and message to the client. E.g., Sends 500 with "Internal
Server Error" message.
HttpServletResponse
Interface
void sendRedirect(String url)
● Redirects the client to the specified url. E.g., Redirects to
"https://example.com/homepage".
void setDateHeader(String field, long ms)
● Adds field to the header with date value equal to ms (milliseconds since Jan 1,
1970). E.g., Set "Expires" header to a future date.
void setHeader(String field, String value)
● Adds field to the header with value value. E.g., Sets "Content-Type" header to
"text/html".
void setIntHeader(String field, int value)
● Adds field to the header with integer value value. E.g., Sets "Content-Length"
header to 1024.
void setStatus(int code)
● Sets the status code for the response. E.g., Sets 200 for a successful response.
SESSION
In an e-commerce website, when a user logs in, an HTTP
session is created with a unique session ID. This session
stores user-specific data, such as their user ID, login status,
and items in their shopping cart. As the user browses and
adds products to their cart, the server retrieves and
updates this session data. If the user is inactive for a certain
period, the session expires, requiring them to log in again
to continue shopping. This mechanism allows for a
personalized and seamless shopping experience.
HttpSession interface (manages session-related data )

Object getAttribute(String attr)


Returns the value of attr, or null if not found. E.g., Retrieves "user" attribute as "JohnDoe".

Enumeration<String> getAttributeNames()
Returns an enumeration of attribute names in the session. E.g., ["username", "cart", "preferences"].

long getCreationTime()
Returns the session creation time in milliseconds since January 1, 1970. E.g., 1625244000000 for a
session created on July 2, 2021.

String getId()
Returns the session ID. E.g., "SESSION123456789".

long getLastAccessedTime()
Returns the last accessed time in milliseconds since January 1, 1970. E.g., 1625247600000 when
user last accessed session.

void invalidate()
Invalidates and removes the session from context. E.g., Destroys session after user logout.

boolean isNew()
Returns true if the server created the session and it hasn’t been accessed. E.g., true for a newly
created session.

void removeAttribute(String attr)


Removes the attribute attr from the session. E.g., Removes "cart" attribute after checkout.

void setAttribute(String attr, Object val)


Associates the attribute name attr with val in the session. E.g., Sets "user" attribute to "JohnDoe".
HTTPServlet Class
void doDelete(HttpServletRequest req, HttpServletResponse res)

● Handles an HTTP DELETE request. E.g., Deletes a specific resource like "/user/123" (user with id 123).

void doGet(HttpServletRequest req, HttpServletResponse res)

● Handles an HTTP GET request. E.g., Retrieves data from "/products".

void doHead(HttpServletRequest req, HttpServletResponse res)

● Handles an HTTP HEAD request. E.g.,When a client sends a HEAD request to "/status", the server responds with
headers, like status code and content type, but no body data.

void doOptions(HttpServletRequest req, HttpServletResponse res)

● Handles an HTTP OPTIONS request. E.g., When a client sends an OPTIONS request to "/api", the server responds
with a list of HTTP methods supported at that endpoint (e.g., GET, POST, PUT).

void doPost(HttpServletRequest req, HttpServletResponse res)

● Handles an HTTP POST request. E.g., Submits form data to "/submit-form".

void doPut(HttpServletRequest req, HttpServletResponse res)

● Handles an HTTP PUT request. E.g., Updating a user's details at "/user/123"(user with id 123).

void doTrace(HttpServletRequest req, HttpServletResponse res)

● When a client sends a TRACE request to "/api/debug", the server responds with a diagnostic trace- showing the
path and any modifications made to the request by any servers on its way to the destination server.

long getLastModified(HttpServletRequest req)

● Returns the last modified time of the requested resource in milliseconds. E.g., 1625259000000 for a recent modification.

void service(HttpServletRequest req, HttpServletResponse res)

● Processes an HTTP request and response. E.g., Manages incoming requests to "/service-endpoint".
Cookie Class
■HTTP Cookies are little pieces of data that a web
application can store on the client machine of users
visiting the web application.
■Typically up to 4 kilo bytes (KB) of data can be stored.
■We can write cookies using HttpServletResponse object:

■Example:
Cookie cookie = new Cookie("myCookie", "myCookieValue");
response.addCookie(cookie);
Cooki
e
■ By default, each request from client to server is a new request.
■ Servlet sends response and cookies.
■ Cookies are stored in the cache of the browser on client machine
■ After that, if new request is sent by the user, cookie is sent along with
the request by default. Now, server recognizes the user as the old user.
Cookie:
Types
■Non-persistent cookie:
■It is valid for single session only. It is removed each time
when user closes the browser.

■Persistent cookie:
■It is valid for multiple sessions . It is not removed each time
when user closes the browser. It is removed only if user
logout or sign-out or clear cookies/cache memory of
browsers.
Object clone()

● Returns a copy of this object. E.g., Clones a cookie for re-use in another request.

String getComment()

● Returns the comment. E.g., "This cookie stores user session info."

String getDomain()

● Returns the domain. E.g., "example.com"

int getMaxAge()

● Returns the maximum age (in seconds) of the cookie. E.g., 3600 for one-hour expiry.

String getName()

● Returns the cookie’s name. E.g., "sessionID"

String getPath()

● Returns the path. E.g., "/user" for a cookie accessible under "/user".

boolean getSecure()

● Returns true if the cookie is secure. Otherwise, returns false. E.g., true for cookies sent over
HTTPS.

String getValue()

● Returns the cookie’s value. E.g., "abc123xyz"


int getVersion()

● Returns the cookie’s version. E.g., 1

boolean isHttpOnly()

● Returns true if the cookie has the HttpOnly attribute. Eg, if isHttpOnly() returns
true for a cookie, it means that cookie is protected from being accessed by
client-side scripts like JavaScript.
void setComment(String c)

● Sets the comment to c. E.g., Adds "Stores shopping cart items."

void setDomain(String d)

● Sets the domain to d. E.g., Sets domain to "example.com".

void setHttpOnly(boolean httpOnly)

● Adds or removes the HttpOnly attribute. E.g., Sets to true to prevent


JavaScript access.

void setMaxAge(int sec)

● Sets the maximum age to sec. E.g., Sets expiry to 600 seconds.
void setPath(String p)
● Sets the path to p. E.g., Sets path to "/account".

void setSecure(boolean secure)


● Sets the security flag to secure. E.g., Sets to true to restrict to
HTTPS only.
void setValue(String v)
● Sets the value to v. E.g., Updates cookie value to
"newSessionID".
void setVersion(int v)
● Sets the version to v. E.g., Sets version to 2.
Cookie:
Constructor
■javax.servlet.http.Cookie class provides the
functionality of using cookies. It provides a lot of
useful methods for cookies.

Constructor Description
Cookie() constructs a cookie.
Cookie(String name, String value) constructs a cookie with a specified
name and value.
■ Creating cookie object
Cookie ck=new Cookie("user",”Sandip");

■ Adding cookie in the response


response.addCookie(ck);//
■ Deleting value of cookie
Cookie ck=new Cookie("user","");

■ Changing the maximum age to 0 seconds


ck.setMaxAge(0);

■ Adding cookie in the response


response.addCookie(ck);
Cookie ck[]=request.getCookies();
for(int i=0;i<ck.length;i++)
{
out.print("<br>"+ck[i].getName()+"
"+ck[i].getValue());
//printing name and value of cookie
}
Steps

1) Create & compile servlet source code.


Copy servlet's class file to proper directory & add servlet's
name and mappings to proper web.aml file.
2) Start Tomcat
3) Start a web browser and request the soulet.

Example:
import java.io.*; import javax.servlet.*;
public class Hello Servlet extends GenericServlet{

public void service(ServletRequest request,


ServletResponse response) throws ServletException,
IOException {
("text
response. set ContentType ("text/html”).
PrintWriter pw = response.getWriter();
pw.println(“<B>Hello”);
pw.close();
}

You might also like