0% found this document useful (0 votes)
7 views33 pages

Java Servlets

Java Servlets are server-side programs used for developing web applications, offering advantages over CGI and ASP in terms of efficiency, portability, and integration. The servlet lifecycle includes initialization, request handling, and destruction, with key methods such as init(), service(), and destroy() defined in the Servlet interface. Servlets can handle various HTTP methods like GET, POST, HEAD, and PUT, making them versatile for dynamic content generation.

Uploaded by

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

Java Servlets

Java Servlets are server-side programs used for developing web applications, offering advantages over CGI and ASP in terms of efficiency, portability, and integration. The servlet lifecycle includes initialization, request handling, and destruction, with key methods such as init(), service(), and destroy() defined in the Servlet interface. Servlets can handle various HTTP methods like GET, POST, HEAD, and PUT, making them versatile for dynamic content generation.

Uploaded by

hemali kotak
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Java Servlets are programs that run on a web server and used for

developing web applications. Lets take an example to understand it


better: Consider a scenario where we need to log on to a web site to
access our e-mail account. We are required to submit the login details
such as username and password for authentication. The website accepts
the login information and validates it using server side programs. These
server side programs can be written using different technologies, such
as Common Gateway Interface (CGI),Active Server Pages
(ASP) and Servlets.
Limitations of CGI
CGI scripts are written in C, C++ or Perl programming languages. In case
of an application server using CGI script to process client request, the
server creates a separate instance of the CGI script to process the
request. As a result, the efficiency of the server is affected when there is
large number of concurrent requests.

Limitations of ASP
ASP is a server side technology that enables a developer to combine both
HTML and scripting language in the same page. ASP objects are
multithreaded and can therefore concurrently service multiple requests.
The limitation of ASP is that it is not compatible with all the commercial
Web servers.

How Servlet is better than CGI and ASP


Servlets are server side programs written in Java. Unlike CGI scripts,
the servlet initialization code excutes only once. Moreover, separate
threads in the server handle each client request. This prevents the
creation of unnecessary processes, thus enhancing the performance of
the server. In addition, Servlets inherit all the features of the Java
programming language. For example, like all standard Java classes, a
servlet is platform independent and can be used across different
operating systems. Similarly, a servlet can make use of the extensive
power of Java, such as networking, multithreading, Java Database
Connectivity (JDBC), internationalization, and Remote Method Invocation
(RMI).
Java Servlet Technology

Servlets enable you to extend the functionality of the application server


for generating dynamic content in an application. Besides inheriting all the
features of Java, Servlets also have the following features:

Features and Advantages of Servlets


The advantages of servlets are as follows:

1. Portability
Servlets are supported on all platforms that support java and servlets
work with all the major web servers. They are highly portable across
operating systems and across server implementations. A servlet can be
developed on a Windows NT machine running the tomcat server and later
deploy it effortlessly on a high end Unix server running the
iPlanet/Netscape application server.
2. Power
Servlets has full power of the core Java APIs: Networking and URL access,
multithreading, image manipulation, data compression, database
connection (JDBC), object serialization, remote method invocation (RMI),
and legacy integration (CORBA). Servlets can also take advantage of the
J2EE platform.
3. Efficiency and endurance
Sevlet stays in server’s memory as a single object instance, it
automatically maintains its state and can hold on to external resources.
4. Safety
As they are written in Java, servlets inherit the strong type safety of java
language.
5. Integration
Servlets are highly integrated with the server. This integration allows a
servlet to cooperate with the server in ways that a CGI program cannot.
6. Extensibilty and flexibility
Servlets could be extended and optimized for another type of
[Link] can create simple content using [Link]() statements, or
they can generate complicated sets of pages using a template engine.
A Servlet is a class, which implements the [Link] interface.
However instead of directly implementing the [Link] interface
we extend a class that has implemented the interface
like [Link] [Link].

Servlet Exceution
This is how a servlet execution takes place when client (browser) makes a
request to the webserver.
Servlet architecture includes:

a) Servlet Interface
To write a servlet we need to implement Servlet interface. Servlet
interface can be implemented directly or indirectly by
extending GenericServlet or HttpServlet class.
b) Request handling methods
There are 3 methods defined in Servlet interface: init(), service() and
destroy().
The first time a servlet is invoked, the init method is called. It is called
only once during the lifetime of a servlet. So, we can put all your
initialization code here.

The Service method is used for handling the client request. As the client
request reaches to the container it creates a thread of the servlet object,
and request and response object are also created. These request and
response object are then passed as parameter to the service method,
which then process the client request. The service method in turn calls the
doGet or doPost methods (if the user has extended the class from
HttpServlet ).

c) Number of instances

Basic Structure of a Servlet

public class firstServlet extends HttpServlet {


public void init() {
/* Put your initialization code in this method,
* as this method is called only once */
}
public void service() {
// Service request for Servlet
}
public void destroy() {
// For taking the servlet out of service, this method is
called only once
}
}

Servlet life cycle

The [Link] interface defines the life cycle methods of


servlet such asinit(), service() and destroy(). The Web container invokes
the init(), service() anddestroy() methods of a servlet during its life cycle.
The sequence in which the Web container calls the life cycle methods of a servlet
is:

1. The Web container loads the servlet class and creates one or more
instances of the servlet class.
2. The Web container invokes init() method of the servlet instance during
initialization of the servlet. The init() method is invoked only once in
the servlet life cycle.
3. The Web container invokes the service() method to allow a servlet to
process a client request.
4. The service() method processes the request and returns the response
back to the Web container.
5. The servlet then waits to receive and process subsequent requests as
explained in steps 3 and 4.
6. The Web container calls the destroy() method before removing the
servlet instance from the service. The destroy() method is also invoked
only once in a servlet life cycle.

The init() Method


The init() method is called during initialization phase of the servlet life
cycle. The Web container first maps the requested URL to the
corresponding servlet available in the Web container and then instantiates
the servlet. The Web container then creates an object of the ServletConfig
interface, which contains the startup configuration information, such as
initialization parameters of the servlet. The Web container then calls the
init() method of the servlet and passes the ServletConfig object to it.
The init() method throws a ServletException if the Web container cannot
initialize the servlet resources. The servlet initialization completes before
any client requests are accepted. The following code snippet shows the
init() method:
public class ServletLifeCycle extends HttpServlet
{
static int count;
public void init(ServletConfig config) throws ServletException
{
count=0;
}
}
The service() Method
The service() method processes the client requests. Each time the Web
container receives a client request, it invokes the service() method. The
service() method is invoked only after the initialization of the servlet is
complete. When the Web container calls the service() method, it passes
an object of the ServletRequest interface and an object of the
ServletResponse interface. The ServletRequest object contains
information about the service request made by the client. The
ServletResponse object contains the information returned by the servlet
to the client. The following code snippet shows the service() method:

public void service(ServletRequest req, ServletResponse res)


throws ServletException, IOException
The service() method throws ServletException exception when an
exception occurs that interferes with the normal operation of the servlet.
The service() method throws IOException when an input or output
exception occurs.

The service() method dispatches a client request to one of the request


handler methods of the HttpServlet interface, such as the doGet(),
doPost(), doHead() or doPut(). The request handler methods accept the
objects of the HttpServletRequest and HttpServletResponse as
parameters from the service() method.

The doGet() Method


The doGet() method processes client request, which is sent by the client,
using the HTTP GET method. GET is a type of HTTP request method that is
commonly used to retrieve static resources. To handle client requests that
are received using GET method, we need to override the doGet() method
in the servlet class. In the doGet() method, we can retrieve the client
information of the HttpServletRequest object. We can use the
HttpServletResponse object to send the response back to the client. The
following code snippet shows the doGet() method:

public void doGet(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException
The doPost() Method
The doPost() method handles requests in a servlet, which is sent by the
client, using the HTTP POST method. For example, if a client is entering
registration data in an HTML form, the data can be sent using the POST
method. Unlike the GET method, the POST request sends the data as part
of the HTTP request body. As a result, the data sent does not appear as a
part of URL.

To handle requests in a servlet that is sent using the POST method, we


need to override the doPost() method. In the doPost() method, we can
process the request and send the response back to the client. The
following code snippet shows the doPost() method:

public void doPost(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException
The doHead() Method
The doHead() method handles requests sent using the HTTP HEAD
method. Similar to the GET method, the HEAD method also sends
requests to the server. The only difference between the GET and the
HEAD methods is that the HEAD method returns the header of the
response, which contains entries, such as Content-Type, Content-Length,
and Last-Modified. The HEAD method is used to find whether a requested
resource exists. It is also used to obtain information about the resource,
such as type of the resource. This information is required before
requesting for resource content. The following code snippet shows the
doHead() method:

public void doHead(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException
The doPut() Method
The doPut() method handles requests sent using the HTTP PUT method.
The PUT method allows a client to store information on the server. The
following code snippet shows the doPut() method:

public void doPut(HttpServletRequest req, HttpServletResponse res)


throws ServletException, IOException
The destroy() Method
The destroy() method marks the end of the life cycle of a servlet. The Web
container calls the destroy() method before removing a servlet instance
from the service. The Web container calls the destroy() method when

 The time period specified for the servlet has elapsed. The time period
of a servlet is the period for which the servlet is kept in the active state
by the Web container to service the client request.
 The Web container needs to release servlet instances to conserve
memory.
 The Web container is about to shut down.
In the destroy() method we can write the code to release the resources
occupied by the servlet. The destroy() method is also used to save any
persistent information before the servlet instance is removed from the
service. The following code snippet shows the destroy() method:
public void destroy();

Servlet Interface
The Servlet interface defines the methods that must be implemented by all the
servlets. In short, all servlet must implement Servlet interface directly or
indirectly (To implement this interface, you can write a generic servlet that
extends [Link] an HTTP servlet that
extends [Link]). A servlet is a java program that
receives the request from client(web browser) and returns the response to client.

Servlet Interface methods

1) void destroy(): This method ends the life cycle of a servlet, it is called
by Servlet container. This method is only called once all threads within the
servlet’s service method have exited or after a timeout period has passed.
Once destroy() method is called the servlet container does not call the
service() method for that servlet.
2) void init(ServletConfig config) throws ServletException: This
methods initializes the servlet. It is called by servlet container after
instantiating the servlet.
3) void service(ServletRequest req, ServletResponse res)
throws ServletException, [Link]: It responds the
requests that comes from client.
4) ServletConfig getServletConfig(): Returns a ServletConfig object,
which contains initialization and startup parameters for this servlet.
5) [Link] getServletInfo(): Returns information about the
servlet, such as author, version, and copyright.
Example:
In this example we have created a servlet class by extending Servlet
interface.

[Link]
<a href="welcome">Click here to call the servlet</a>
[Link]
import [Link].*;
import [Link].*;

public class DemoServlet implements Servlet{


ServletConfig config=null;
public void init(ServletConfig config){
[Link]=config;
[Link]("Initialization complete");
}

public void service(ServletRequest req,ServletResponse res)


throws IOException,ServletException{
[Link]("text/html");
PrintWriter pwriter=[Link]();
[Link]("<html>");
[Link]("<body>");
[Link]("<h1>Servlet Example Program</h1>");
[Link]("</body>");
[Link]("</html>");
}
public void destroy(){
[Link]("servlet life cycle finished");
}
public ServletConfig getServletConfig(){
return config;
}
public String getServletInfo(){
return "A Demo program written by Chaitanya";
}
}
[Link]
<web-app>
<servlet>
<servlet-name>Beginnersbook</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Beginnersbook</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

welcome-file-list in [Link] file of Project

Have you ever seen <welcome-file-list> tag in your [Link] file and
wondering what it is? In this post we will discuss what is this tag and why we use
it.
The tag <welcome-file-list> is used for specifying the files that needs to
be invoked by server by default, if you do not specify a file name while
loading the project on browser.

For e.g. You have created a project named “MyServletProject” and you
have few html pages and servlet classes defined in the project. However
in browser you have given the url like this:

[Link]
Generally we give the complete path like
this[Link] However if you
have given the path like above then the webserver will look for the
<welcome-file-list> tag in your project’s [Link] file. Lets say you have
below content in the [Link] file:
<web-app>
....
<welcome-file-list>
<welcome-file>[Link]</welcome-file>
<welcome-file>[Link]</welcome-file>
<welcome-file>[Link]</welcome-file>
</welcome-file-list>
....
</web-app>
Based on the welcome file list, server would look for the [Link] page
if this doesn’t exist then the second welcome file [Link] and so on
till it finds a valid welcome file.
Note: If the <welcome-file-list> tag is not defined in [Link] or the
welcome files defined in the <welcome-file> tags does not exist then the
server would look for the following files in the given sequence:
1) [Link]
2) [Link]
3) [Link]
Servlet Class Hierarchy
The Servlet interface is the root interface of the servlet class hierarchy. All
Servlets need to either directly or indirectly implement the Servlet interface.
The GenericServlet class of the Servlet API implements the Servlet interface.
In addition to the Servlet interface, the GenericServlet class implements
the ServletConfig interface of the Servlet API and the Serializable interface
of the standard [Link]. package. The object of the ServletConfig interface is used
by the Web container to pass the configuration information to a servlet when a
servlet is initialized.

To develop a servlet that communicates using HTTP, we need to extend


the HttpServletclass in our servlet. The HttpServlet class extends the
GenericServlet class and provides built-in HTTP functionality.

The [Link] Interface

The servlet interface of the [Link] package defines methods that


the Web container calls to manage the servlet life cycle. The following
table describes various methods of [Link] interface:
Method Description
public void destroy() The Web container calls the destroy()
method just before removing the
servlet instance from service.

public ServletConfig getServletConfig() Returns a ServletConfig object that


contains configuration information,
such as initialization parameters, to
initialize a servlet.

public String getServletInfo() Returns a string that contains


information about the servlet, such as
author, version, and copyright.

public void init(ServletConfig config) The Web container calls this method
throws ServletException after creating a servlet instance.

The [Link] Interface

The [Link] interface is implemented by a Web


container to pass configuration information to a servlet, during
initialization of a servlet. A servlet is initialized by passing an object of
ServiceConfig to its init() method by the Web container. The ServletConfig
object contains initialization information and provides access to the
ServletContext object.
Initialization parameters are name value pairs that we can use to pass
information to a servlet. The following table lists some of the methods of
the [Link] interface:

Method Description
public String getInitParameter(String Returns a String containing the value
param) of the specified initialization
parameters or null if the parameter
does not exist.

public Enumeration Returns the names of all initialization


getInitParameterNames() parameters as an Enumeration of
String objects. If no initialization
parameters have been defined, an
empty Enumeration is returned.

public ServletContext Returns the ServletContext object for


getServletContext() the servlet, which allows interaction
with the Web container.

GenericServlet class

GenericServlet class defines a protocol-independent(HTTP-less) servlet. However


while building a website or an online application, you may want to have Http
protocol, in that case extend HttpServlet instead of GenericServlet class

This is the blue print of GenericServlet class:

public abstract class GenericServlet extends [Link]


implements Servlet,
ServletConfig, [Link]
As you can see it is an abstract class and it extends Object class &
implements Servlet, ServletConfig and Serializable interfaces.

Methods of GenericServlet class:


 void destroy(): It is called by servlet container to indicate that the servlet
life cycle is finished.
 [Link] getInitParameter([Link] name): It returns
the value of the specified initialization parameter. If the parameter does not
exist then it returns null.
 [Link] getInitParameterNames(): This method returns
all the initialization parameters in form of a String enumeration. By using
enumeration methods we can fetch the individual parameter names.
 ServletConfig getServletConfig(): It returns this servlet’s ServletConfig
object.
 ServletContext getServletContext(): It returns a reference to the
ServletContext in which this servlet is running.
 [Link] getServletInfo(): It returns information about the servlet,
such as author, version, and copyright.
 [Link] getServletName(): This method returns the name of this
servlet instance.
 void init(): This is the first method of servlet life cycle and it is used for
initializing a servlet.
 void init(ServletConfig config): Called by the servlet container to indicate
to a servlet that the servlet is being placed into service.
 void log([Link] msg): Writes the specified message to a servlet
log file, prefixed with servlet’s name.
 void log([Link] message, [Link] t)
 abstract void service(ServletRequest req, ServletResponse res): It is
called by the servlet container to allow the servlet to respond to the client’s
request.

Example of GenericServlet

[Link]
<a href="welcome">Click to call Servlet</a>
[Link]
import [Link].*;
import [Link].*;

public class ExampleGeneric extends GenericServlet{


public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{
[Link]("text/html");
PrintWriter pwriter=[Link]();
[Link]("<html>");
[Link]("<body>");
[Link]("<h2>Generic Servlet Example</h2>");
[Link]("</body>");
[Link]("</html>");
}
}
[Link]
<web-app>
<servlet>
<servlet-name>Beginnersbook</servlet-name>
<servlet-class>ExampleGeneric</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>Beginnersbook</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

HTTP Basics and HTTP Servlet

In this tutorial I will cover HTTP basics and server side programming. If you are
not a beginner and have done server side programming before then you can skip
this post. However a java beginner should understand the basics of HTTP
in servlet programming.

I am going to split it up in three sections – When a web browser sends a


request the web server receives the request and sends the response
based on the request. That’s how transaction gets completed.
1. Request
2. Response
3. Header

Request, Response and Header

Client sending a request to Sever


When a client(web browser) makes a request, first line in the request it
specifies is the URL and the version of HTTP protocol. for example
GET /[Link] HTTP/1.0
The above request is using the GET method to ask for a webpage
[Link] using HTTP version 1.0. Along with the above line, client can
send optional header information which can be helpful for webserver in
order to generate better response. for example:

user-Agent: Firefox/4.0 (compatible; Windows 2000)


Accept: image/jpg, image/png, */*
User-Agent header: It provides the information about client(web
browser) software. In the above example it is telling web-server that
request is being sent from a Firefox version 4.0 browser.
Accept header: It specifies the media(MIME) time which client can easily
accept.
Server sending a response to client
In the above part we learned what all things client mentions while sending
a request to server. So Once Web-Server processed the request it sends a
response to client. In the first line it specifies the HTTP protocol server is
using along with the status code of request. for example –

HTTP/1.0 200 OK
The status code 200 means request processed successfully.
Another example:
HTTP/1.0 404 Not Found
The status code 404 means request document was not found by server.

Code Range Response Meaning


100-199 Informational
200-299 Client request successful
300-399 Client request redirected, further action necessary
400-499 Client request incomplete
500-599 Server error
Along with above status line Response header contains few additional
things which tells client more about Sever side software and content type
– for example –
Date: Monday, 15-May-2012 [Link] GMT
Server: JavaWebServer/1.1.1
MIME-version: 1.0
Content-type: text/html
Content-length: 2024
Last-modified: Tuesday, 9-May-2012 [Link] GMT
Points to remember:
1. Server sends a blank line after the header section to separate it from
content section.
2. If server process the request successfully it sends the response along
with header otherwise it respond back in human readable format to let
them know why it had not be able to process the request.

GET & POST

The request which client sends to server can be of different types,


generally referred as methods. The most frequently used methods
are GET and POST.
GET method:
It is used for fetching the information such as getting a webpage or
querying a database. This method can include its own information
in client’s request in order to better specify what to get. The GET methods
parameters are appended to the URL while passing the request to server.
The query string (URL+Parameters) can have maximum 240 characters
thus through this method you cannot send large amount of information to
server.
POST method:
POST method is generally used to send large (in megabytes) and sensitive
(confidential such as credit card number) information. It doesn’t append
anything to the URL, instead it sends the information directly to server
through a socket connection.
GET vs POST – A Gist:
1. For sending large amount of information you must prefer POST over
GET.
2. For sensitive information use POST as it doesn’t append information in
the URL so makes confidentiality.
Few Other Methods
Apart from GET and POST there are other HTTP methods, which are rarely
used –

HEAD method : It is used by client when client just want to see response
header information such as document modification date, document size
etc.
PUT method: In order to place document directly on server.
DELETE method: Reverse of PUT method.
TRACE method: Used for debugging.
OPTIONS method: Can be used to know what all method concerned web
server supports.

HTTP Servlet

The HttpServlet class implements Serializable interface and


extends GenericServletclass. It provides the definition of HTTP specific
methods such as doGet(), doPost(),doTrace() etc.
Methods:
The methods of HttpServlet class are as follows:
1. protected void doGet(HttpServletRequest request,
HttpServletResponse response): It handles the GET request. It is
invoked by the web container.
2. protected void doPost(HttpServletRequest request,
HttpServletResponse response): Similar to doGet() method, it also
gets invoked by the web container and it handles the POST request.
3. public void service(ServletRequest request,ServletResponse
response): There are two types of service method, one is public and
other one is protected. The purpose of this public method is to dispatch
the request to the protected service method by converting the request
and response object into HTTP type.
4. protected void service(HttpServletRequest request,
HttpServletResponse response): This method receives the request
from the public service() method. It dispatches the request to the
doXXX() method depending on the incoming http request type.
5. protected void doHead(HttpServletRequest request,
HttpServletResponse response): It handles the HEAD request.
6. protected void doOptions(HttpServletRequest request,
HttpServletResponse response): Performs the HTTP OPTIONS
operation; the default implementation of this method automatically
determines what HTTP Options are supported.
7. protected void doPut(HttpServletRequest request,
HttpServletResponse response): Performs the HTTP PUT operation;
the default implementation reports an HTTP BAD_REQUEST error.
8. protected void doTrace(HttpServletRequest request,
HttpServletResponse response): Performs the HTTP TRACE
operation; the default implementation of this method causes a
response with a message containing all of the headers sent in the trace
request.
9. protected void doDelete(HttpServletRequest request,
HttpServletResponse response): Performs the HTTP DELETE
operation; the default implementation reports an HTTP BAD_REQUEST
error.
10. protected long getLastModified(HttpServletRequest
request): Gets the time the requested entity was last modified; the
default implementation returns a negative number, indicating that the
modification time is unknown and hence should not be used for
conditional GET operations or for other cache control operations as this
implementation will always return the contents.

HttpSession Interface in Servlets

The HttpSession object is used for session management. A session contains


information specific to a particular user across the whole application. When a
user enters into a website (or an online application) for the first time, the user is
given a unique ID to identify his session by. This unique ID can be stored into a
cookie or in a request parameter.

The below snippet shows the way to access the HttpSession object.

protected void doPost(HttpServletRequest req,


HttpServletResponse res)
throws ServletException, IOException {
HttpSession session = [Link]();
}
You can store the user information into the session object and later when
needed this information can be fetched from the session object. Lets see
how to store the value first. In the below snippet, I am storing user name,
user emailid and user age into the session object.

[Link]("uName", "ChaitanyaSingh");
[Link]("uemailId", "myemailid@[Link]");
[Link]("uAge", "26");
This First parameter is the attribute name and second is the attribute
value. For e.g. uName is the attribute name and ChaitanyaSingh is the
attribute value above.

In order to read the value from session, you can


use getAttribute() method like this:
String userName = (String) [Link]("uName");
String userEmailId = (String) [Link]("uemailId");
String userAge = (String) [Link]("uAge");
Values stored in the session object are stored in the memory of the servlet
container.

Methods of HttpSession class


Method Description
public void setAttribute(String Binds the object with a name
name, Object value) and stores the name/value pair
as an attribute of the
HttpSession object. If an
attribute already exists, then this
method replaces the existing
attributes.
public Object getAttribute(String Returns the String object
name) specified in the parameter, from
the session object. If no object is
found for the specified attribute,
then the getAttribute() method
returns null.
public Enumeration Returns an Enumeration that
getAttributeNames() contains the name of all the
objects that are bound as
attributes to the session object..
Example
[Link]
<form action="login">
User Name:<input type="text" name="userName"/><br/>
Password:<input type="text" name="userPassword"/><br/>
<input type="submit" value="submit"/>
</form>
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class MyServlet1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response){
try{
[Link]("text/html");
PrintWriter pwriter = [Link]();

String name = [Link]("userName");


String password = [Link]("userPassword");
[Link]("Hello "+name);
[Link]("Your Password is: "+password);
HttpSession session=[Link]();
[Link]("uname",name);
[Link]("upass",password);
[Link]("<a href='welcome'>view details</a>");
[Link]();
}catch(Exception exp){
[Link](exp);
}
}
}
[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class MyServlet2 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response){
try{
[Link]("text/html");
PrintWriter pwriter = [Link]();
HttpSession session=[Link](false);
String myName=(String)[Link]("uname");
String myPass=(String)[Link]("upass");
[Link]("Name: "+myName+" Pass: "+myPass);
[Link]();
}catch(Exception exp){
[Link](exp);
}
}
}
[Link]
<web-app>
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-class>MyServlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>Servlet2</servlet-name>
<servlet-class>MyServlet2</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Servlet2</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>

ServletContext Interface
The ServletContext interface provides information to servlets about the
environment in which they are running. Each web application has only one
ServletContext object. The context also known as Web context and is created by
the Web container as an object of the ServletContext interface. This object
represents a context within which a Web application executes. The Web
container creates a ServletContext object for each deployed Web application.
The user can use the ServletContext object to find path information of other files
of the Web application, access other servlets of the Web application, and log
messages to the application server log file. The following table describes various
methods of the ServletContext interface:

Method Description
public void setAttribute(String, Binds the object with a name
Object) and stores the name/value pair
as an attribute of the
ServletContext object. If an
attribute already exists, then
this method replaces the
existing attributes.
public Object getAttribute(String Returns the object stored in the
attrname) ServletContext object with the
name passed as a parameter.
public Enumeration Returns an Enumeration of
getAttributeNames() String object that contain names
of all the context attributes.
public String Returns the value of the
getInitParameter(String pname) initialization parameter with the
name passed as a parameter.
public Enumeration Returns the Enumeration of
getInitParameterNames() String object that contain names
of all the initialization
parameters.
public int getMajorVersion() Returns an integer value that
specifies the major version of
the Servlet API that the Web
container supports.
public int getMinorVersion() Returns an integer value that
specifies the minor version of
the Servlet API that the Web
container supports.
To use the ServletContext object, we need to retrieve
the ServletContext object in the init() method of the servlet.
The getServletContext() method of the ServletConfiginterface enables
the user to obtain a ServletContext object. The following code snippet
helps to obtain the ServletContext object:
ServletContext sc;
public void init(ServletConfig scfig)
{
sc=[Link]();
}
Once we have obtained the ServletContext object, we can set the
attributes of theServletContext object by using
the setAttribute() method. As the ServletContext object is available to
all the servlets of the Web application, other servlets can retrieve the
attribute from the ServletContext object by using
the getAttribute() method.
Context Initialization Parameter
Context Initialization parameters are name/value pairs that the user can
specify during the deployment of a Web application. The user can use the
initialization parameters to provide information that are accessible to all
servlets of a Web application. For example, we can specify our email ID as
a context initialization parameter. We can then retrieve the value in other
servlets of your Web application that needs to display our email ID.
When we deploy the Web application, the Web container reads the
initialization parameter from the deployment descriptor and initializes the
ServletContext object with it. We can use
the getInitParameter() and getInitParameterNames() methods of the
ServletContext object to retrieve the parameter values in the servlet.
The context-param element of the deployment descriptor specifies the
name/value pair of the context initialization parameter. The following code
snippet shows the context-param element of the deployment descriptor
that specifies a parameter with name as email_id and value
as beginnersbook@[Link]:

<context-param>
<param-name>email_id</param-name>
<param-value>beginnersbook@[Link]</param-value>
</context-param>
ServletContext complete example: To get the initialization
parameters
In this example we have two initialization parameters (user name and
user email) defined in [Link] file and using ServletContext object, we
are fetching the values of these parameters from [Link] file.

[Link]
import [Link].*;
import [Link].*;
import [Link].*;
public class MyServlet extends HttpServlet{
public void doGet(HttpServletRequest request,HttpServletResponse
response)
throws ServletException,IOException
{
[Link]("text/html");
PrintWriter pwriter=[Link]();

//ServletContext object creation


ServletContext scontext=getServletContext();

//fetching values of initialization parameters and printing


it
String userName=[Link]("uname");
[Link]("User name is="+userName);
String userEmail=[Link]("email");
[Link]("Email Id is="+userEmail);
[Link]();
}
}
[Link]
<web-app>
<servlet>
<servlet-name>BeginnersBook</servlet-name>
<servlet-class>MyServlet</servlet-class>
</servlet>
<context-param>
<param-name>uname</param-name>
<param-value>ChaitanyaSingh</param-value>
</context-param>
<context-param>
<param-name>email</param-name>
<param-value>beginnersbook@[Link]</param-value>
</context-param>
<servlet-mapping>
<servlet-name>BeginnersBook</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>

cookies in servlet
In this article, we will discuss cookies usage in servlet. Cookies are small bits of
text files, which are stored in client machine and are mainly used to track the
session information. HTTP cookie is the obviously supported cookie by the
Servlets. This article primarily helps the programmers who are new to cookies.

Cookies

Information which is stored on the client system is called as Cookies. It


has parameters like name, value, path, host, expires and connection type.
We can easily identify the cookies using the combination of cookie name,
path, host and connection type parameters.

Cookies are mainly useful for the following:

 Used to remember the username and password


 E-Commerce
 Focussing Advertising
 Customizing sites

Types of Cookies

We can classify the cookies based on the expires parameter. They are:-

1. Session
2. Persistent

1) SessionCookies

 Session cookies have not expiration time parameter.


 It lives in the memory.
 The web browser is closed then this cookies will dissapear.

2) Persistent Cookies

 Persistent cookies have expiration time parameter.


 This information is stored on hard disk .
 This cookies are removed when the timer expires.
Parameters
 Value parameter is one of the useful information stored into the Cookie.
 Path parameter is part of the server URL after the host name.
 Host parameter represents the Server name otherwise Server’s IP address.
 Expires parameter is used to delete the cookie based on date or time.
 Connection type parameter is used for indicating the type of connection.
How to send Cookies to the Client
It involves the following steps:
1. Create a Cookie object.
2. Set the maximum Age.
3. Place the Cookie in HTTP response header.
1) Create a Cookie object:
For Cookie object creating we have to call the Cookie () constructor with
the corresponding cookie name and value.

2) Set the maximum Age:


Using setMaxAge () method we can provide the maximum age for the
particular cookie in seconds.
3) Place the Cookie in HTTP response header:
We can pass the cookie to the web browser through [Link].
Otherwise cookie will not send to the browser.
How to read Cookies from the Client:
Call [Link], getName and get Value.

Example of cookies in java servlet


The below code can be used to display count of number of visits

[Link]
package [Link];
import [Link];
public class CookieLife extends Cookie
{
public static final intseconds_year = 60*60*24*365;
publicCookieLife(String name, String value)
{
super(name, value);
setMaxAge(seconds_year);
}
}
[Link]
package [Link];
import [Link];
import [Link];
public class CookieUsage
{
public static String getCookieValue(HttpServletRequest req,
String cname, String dvalue)
{
Cookie[] c1= [Link]();
if (c1 != null) {
for(int i=0; i<[Link]; i++) {
Cookie c = cookies[i];
if ([Link]([Link]())) {
return([Link]());
}
}
}
return(dvalue);
}
public static Cookie getCookie(HttpServletRequest req, String
cname) {
Cookie[] ckk = [Link]();
if (ckk != null) {
for(int i=0; i<[Link]; i++) {
Cookie cc = cookies[i];
if ([Link]([Link]())) {
return(cc);
}
}
}
return(null);
}
}
[Link]
package [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class VisitedCount extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse
response)
throwsServletException, IOException {
String cs
=[Link](request,"accesscount","1");
int count =1;
try {
count = [Link](cs);
} catch(NumberFormatException nfe) {
[Link](nfe);
}
CookieLife cl =new
CookieLife("VisitedCount",[Link](count+1));
[Link](cl);
[Link]("text/html");
PrintWriter out = [Link]();
String hd= "Access Count Using Cookies";
String docType =
"<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 "
+"Transitional//EN">n";
[Link](docType +"<HTML>n" +
"<HEAD><TITLE>" + hd+ "</TITLE></HEAD>n" +
"<BODY BGCOLOR="#FDF5E6">n" +
"<CENTER>" +
"<H1>" + hd + "</H1>" +
"<H3>HI!! You have visited the page for " +
count + " times by this browser.</H3>n" +
"</CENTER></BODY></HTML>");
}
}
Conclusion:
This post explains how to utilize the Cookie in an excellent way to store
the session details and used to maintain the user activities. Using
Cookies the user can avoid retyping of data each and every time and
finally concluded with a sample code that illustrates the usage of cookies.

You might also like