Sie sind auf Seite 1von 35

Servlets Tutorial - Java Servlets

Overview
Posted by Rakesh Singh

In this servlet tutorial Java Servlets is a web technology for Java. It was the first web
technology for Java and many new web technologies have arrived since. Still, Java
Servlets are very useful, both to know, and for certain use cases.

Java Servlets are part of the Java Enterprise Edition (Java EE). You will need to run
your Java Servlets inside a Servlet compatible "Servlet Container" (e.g. web server) in
order for them to work.

Java Servlets it Java technology for creating the dynamic web applications. Java
Servlets are server side components in Java that runs on Servlet enabled web server
such as Tomcat, Jetty, WebSphere etc.. Java Servlet is much faster then CGI and Perl
since it runs in the same JVM. In case of CGI and Perl separate memory space is
allocated for execution of the program which reduces it's performance.

Servet technology is robust and scalable as it uses the java language. Before Servlet,
CGI (Common Gateway Interface) scripting language was used as a server-side
programming language. But there were many disadvantages of this technology. We
have discussed these disadvantages below.

There are many interfaces and classes in the servlet API such
as Servlet, GenericServlet, HttpServlet, ServletRequest,ServletResponse etc.

What is a Servlet?
Servlet can be described in many ways, depending on the context.
Servlet is a technology i.e. used to create web application.
Servlet is an API that provides many interfaces and classes including
documentations.
Servlet is an interface that must be implemented for creating any servlet.
Servlet is a class that extend the capabilities of the servers and respond to the
incoming request. It can respond to any type of requests.
Servlet is a web component that is deployed on the server to create dynamic web
page.
Servlets Architecture:
Following diagram shows the position of Servelts in a Web Application.
Servlets Tasks:
Servlets perform the following major tasks:

Read the explicit data sent by the clients (browsers). This includes an HTML form on a
Web page or it could also come from an applet or a custom HTTP client program.

Read the implicit HTTP request data sent by the clients (browsers). This includes
cookies, media types and compression schemes the browser understands, and so forth.

Process the data and generate the results. This process may require talking to a
database, executing an RMI or CORBA call, invoking a Web service, or computing the
response directly.

Send the explicit data (i.e., the document) to the clients (browsers). This document can
be sent in a variety of formats, including text (HTML or XML), binary (GIF images),
Excel, etc.

Send the implicit HTTP response to the clients (browsers). This includes telling the
browsers or other clients what type of document is being returned (e.g., HTML), setting
cookies and caching parameters, and other such tasks.

Servlets Packages:
Java Servlets are Java classes run by a web server that has an interpreter that supports
the Java Servlet specification.

Servlets can be created using the javax.servlet and javax.servlet.http packages, which
are a standard part of the Java's enterprise edition, an expanded version of the Java
class library that supports large-scale development projects.

Servlet Life Cycle


Posted by Rakesh Singh

The life cycle of a servlet is controlled by the container in which the servlet has been
deployed. When a request is mapped to a servlet, the container performs the following
steps.
If an instance of the servlet does not exist, the Web container
1. Loads the servlet class.
2. Creates an instance of the servlet class.
3. Initializes the servlet instance by calling the init method init () .
4. Invokes the service method service(), passing a request and response
object.
5. The servlet is terminated by calling the destroy() method.
6. Finally, servlet is garbage collected by the garbage collector of the JVM.
As displayed in the above diagram, there are three states of a servlet: new, ready and
end. The servlet is in new state if servlet instance is created. After invoking the init()
method, Servlet comes in the ready state. In the ready state, servlet performs all the
tasks. When the web container invokes the destroy() method, it shifts to the end state.
1) Servlet class is loaded

The classloader is responsible to load the servlet class. The servlet class is loaded
when the first request for the servlet is received by the web container.
2) Servlet instance is created

The web container creates the instance of a servlet after loading the servlet class. The
servlet instance is created only once in the servlet life cycle.
3) init method is invoked

The web container calls the init method only once after creating the servlet instance.
The init method is used to initialize the servlet. It is the life cycle method of the
javax.servlet.Servlet interface. Syntax of the init method is given below:
view plainprint?

1. public void init(ServletConfig config) throws ServletException

4) service method is invoked


The web container calls the service method each time when request for the servlet is
received. If servlet is not initialized, it follows the first three steps as described above
then calls the service method. If servlet is initialized, it calls the service method. Notice
that servlet is initialized only once. The syntax of the service method of the Servlet
interface is given below:
view plainprint?

1. public void service(ServletRequest request, ServletResponse respo


nse)
2. 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.

A. 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.
view plainprint?

1. public void doGet(HttpServletRequest request,


2. HttpServletResponse response)
3. throws ServletException, IOException {
4. // Servlet code
5. }

B. 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.
view plainprint?

1. public void doPost(HttpServletRequest request,


2. HttpServletResponse response)
3. throws ServletException, IOException {
4. // Servlet code
5. }
5) destroy method is invoked

The web container calls the destroy method before removing the servlet instance from
the service. It gives the servlet an opportunity to clean up any resource for example
memory, thread etc. The syntax of the destroy method of the Servlet interface is given
below:
view plainprint?

1. public void destroy()


Architecture Diagram:
The following figure depicts a typical servlet life-cycle scenario.
First the HTTP requests coming to the server are delegated to the servlet
container.
The servlet container loads the servlet before invoking the service() method.
Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance of the servlet.

Servlet API
Posted by Rakesh Singh

The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.
Let's see what are the interfaces of javax.servlet package.

Interfaces in javax.servlet package


There are many interfaces in javax.servlet package. They are as follows:
Servlet
ServletRequest
ServletResponse
RequestDispatcher
ServletConfig
ServletContext
SingleThreadModel
Filter
FilterConfig
FilterChain
ServletRequestListener
ServletRequestAttributeListener
ServletContextListener
ServletContextAttributeListener

Classes in javax.servlet package


There are many classes in javax.servlet package. They are as follows:

GenericServlet
ServletInputStream
ServletOutputStream
ServletRequestWrapper
ServletResponseWrapper
ServletRequestEvent
ServletContextEvent
ServletRequestAttributeEvent
ServletContextAttributeEvent
ServletException
UnavailableException

Interfaces in javax.servlet.http package


There are many interfaces in javax.servlet.http package. They are as follows:
HttpServletRequest
HttpServletResponse
HttpSession
HttpSessionListener
HttpSessionAttributeListener
HttpSessionBindingListener
HttpSessionActivationListener
HttpSessionContext (deprecated now)
Classes in javax.servlet.http package
There are many classes in javax.servlet.http package. They are as follows:
HttpServlet
Cookie
HttpServletRequestWrapper
HttpServletResponseWrapper
HttpSessionEvent
HttpSessionBindingEvent

Hello World Example in Servlet


Interface
Posted by Rakesh Singh

Servlets are Java classes which service HTTP requests and implement
the javax.servlet.Servlet interface. Web application developers typically write servlets
that extend javax.servlet.http.HttpServlet, an abstract class that implements the
Servlet interface and is specially designed to handle HTTP requests.

Servlet Interface-
Servlet interface provides common behavior to all the servlets.

Servlet interface needs to be implemented for creating any servlet (either directly or
indirectly). It provides 3 life cycle methods that are used to initialize the servlet, to
service the requests, and to destroy the servlet and 2 non-life cycle methods.

Methods of Servlet interface


There are 5 methods in Servlet interface. The init, service and destroy are the life
cycle methods of servlet. These are invoked by the web container.

Method Description
1. public void init(ServletConfig config) initializes the servlet. It is the life
cycle method of servlet and invoked by the web container only once.
2. public void service(ServletRequest request,ServletResponse
response) provides response for the incoming request. It is invoked at each
request by the web container.
3. public void destroy() is invoked only once and indicates that servlet is
being destroyed.
4. public ServletConfig getServletConfig() returns the object
of ServletConfig.
5. public String getServletInfo() returns information about servlet such as
writer, copyright, version etc.

Hello World Example in Servlet:


Following is the sample source code structure of a servlet example to write Hello World:

// Import required java libraries


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

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException


{
// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

// Actual logic goes here.


PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy()


{
// do nothing.
}
}
Compiling a Servlet:
Let us put above code if HelloWorld.java file and put this file in D:\Servlet
(Windows) or /usr/Servlet (Unix) then you would need to add these directories as well
in CLASSPATH.\

Assuming your environment is setup properly, go in Servlet directory and


compile HelloWorld.java as follows:
If the servlet depends on any other libraries, you have to include those JAR files on
your CLASSPATH as well. I have included onlyservlet-api.jar JAR file because I'm not
using any other library in Hello World program.

If everything goes fine, above compilation would produce HelloWorld.class file in the
same directory. Next section would explain how a compiled servlet would be deployed
in production.

Servlet Deployment:
By default, a servlet application is located at the path C:\Program Files (x86)\Apache
Software Foundation\Tomcat 7.0\webapps\ROOT\ and the class file would reside
in C:\Program Files (x86)\Apache Software Foundation\Tomcat
7.0\webapps\ROOT\WEB-INF\classes.

If you have a fully qualified class name of com.dineshonjava.MyServlet, then this


servlet class must be located in C:\Program Files (x86)\Apache Software
Foundation\Tomcat 7.0\webapps\ROOT\WEB-
INF/classes/com/dineshonjava/MyServlet.class.

For now, let us copy HelloWorld.class into /webapps/ROOT/WEB-INF/classes and


create following entries in web.xml file located in C:\Program Files (x86)\Apache
Software Foundation\Tomcat 7.0\webapps\ROOT\/webapps/ROOT/WEB-INF/

<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>HelloWorld</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>

Now let us start tomcat server using C:\Program Files (x86)\Apache Software
Foundation\Tomcat 7.0\bin\startup.bat (on windows) or /bin/startup.sh (on
Linux/Solaris etc.) and finally type http://localhost:8080/HelloWorld in browser's
address box. If everything goes fine, you would get following result:
What is web application servlet
Posted by Rakesh Singh

A web application is a dynamic extension of a web or application server. There are two
types of web applications:
Presentation-oriented: A presentation-oriented web application generates
interactive web pages containing various types of markup language (HTML, XML, and
so on) and dynamic content in response to requests.
Service-oriented: A service-oriented web application implements the endpoint of
a web service. Presentation-oriented applications are often clients of service-oriented
web applications.
In the Java 2 platform, web components provide the dynamic extension capabilities for
a web server. Web components are either Java servlets, JSP pages, or web service
endpoints. The interaction between a web client and a web application is illustrated in
following Figure. The client sends an HTTP request to the web server. A web server
that implements Java Servlet and JavaServer Pages technology converts the request
into an HTTPServletRequest object. This object is delivered to a web component, which
can interact with JavaBeans components or a database to generate dynamic content.
The web component can then generate an HTTPServletResponse or it can pass the
request to another web component. Eventually a web component generates a
HTTPServletResponse object. The web server converts this object to an HTTP
response and returns it to the client.
Servlets are Java programming language classes that dynamically process requests
and construct responses. JSP pages are text-based documents that execute as servlets
but allow a more natural approach to creating static content. Although servlets and JSP
pages can be used interchangeably, each has its own strengths. Servlets are best
suited for service-oriented applications (web service endpoints are implemented as
servlets) and the control functions of a presentation-oriented application, such as
dispatching requests and handling nontextual data. JSP pages are more appropriate for
generating text-based markup such as HTML, Scalable Vector Graphics (SVG),
Wireless Markup Language (WML), and XML.

Since the introduction of Java Servlet and JSP technology, additional Java technologies
and frameworks for building interactive web applications have been developed. These
technologies and their relationships are illustrated in following

Notice that Java Servlet technology is the foundation of all the web application
technologies. Each technology adds a level of abstraction that makes web application
prototyping and development faster and the web applications themselves more
maintainable, scalable, and robust.

Web components are supported by the services of a runtime platform called a web
container. A web container provides services such as request dispatching, security,
concurrency, and life-cycle management. It also gives web components access to APIs
such as naming, transactions, and email.

Certain aspects of web application behavior can be configured when the application is
installed, or deployed, to the web container. The configuration information is maintained
in a text file in XML format called a web application deployment descriptor (DD).

Advantages of Servlets over CGI


Posted by Rakesh Singh

What is web application?


A web application is an application accessible from the web. A web application is
composed of 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.

Advantages of Servlets over CGI


Servlets are server side components that provides a powerful mechanism for
developing server web applications for server side. Earlier CGI was developed to
provide server side capabilities to the web applications. Although CGI played a major
role in the explosion of the Internet, its performance, scalability and reusability issues
make it less than optimal solutions. Java Servlets changes all that. Built from ground up
using Sun's write once run anywhere technology java servlets provide excellent
framework for server side processing.

Using servlets web developers can create fast and efficient server side applications and
can run it on any servlet enabled web server. Servlet runs entirely inside the Java
Virtual Machine. Since the servlet runs on server side so it does not depend on browser
compatibility.

Servlets have a number of advantages over CGI and other API's. They are:

1. Platform Independence
Servlets are written entirely in java so these are platform independent. Servlets can run
on any Servlet enabled web server. For example if you develop an web application in
windows machine running Java web server, you can easily run the same on apache
web server (if Apache Serve is installed) without modification or compilation of code.
Platform independency of servlets provide a great advantages over alternatives of
servlets.
2. Performance
Due to interpreted nature of java, programs written in java are slow. But the java
servlets runs very fast. These are due to the way servlets run on web server. For any
program initialization takes significant amount of time. But in case of servlets
initialization takes place first time it receives a request and remains in memory till times
out or server shut downs. After servlet is loaded, to handle a new request it simply
creates a new thread and runs service method of servlet. In comparison to traditional
CGI scripts which creates a new process to serve the request.
3. Extensibility
Java Servlets are developed in java which is robust, well-designed and object oriented
language which can be extended or polymorphed into new objects. So the java servlets
take all these advantages and can be extended from existing class to provide the ideal
solutions.
4. Safety
Java provides very good safety features like memory management, exception handling
etc. Servlets inherits all these features and emerged as a very powerful web server
extension.
5. Secure
Servlets are server side components, so it inherits the security provided by the web
server. Servlets are also benefited with Java Security Manager.

CGI(Common Gateway Interface)


CGI technology enables the web server to call an external program and pass HTTP
request information to the external program to process the request. For each request, it
starts a new process.

Disadvantages of CGI
There are many problems in CGI technology:
If number of clients increases, it takes more time for sending response.
For each request, it starts a process and Web server is limited to start processes.
It uses platform dependent language e.g. C, C++, perl.
Advantage of Servlet
There are many advantages of Servlet over CGI. The web container creates threads for
handling the multiple requests to the servlet. Threads have a lot of benefits over the
Processes such as they share a common memory area, lighweight, cost of
communication between the threads are low. The basic benefits of servlet are as
follows:
1. better performance: because it creates a thread for each request not
process.
2. Portability: because it uses java language.
3. Robust: Servlets are managed by JVM so no need to worry about
momory leak, garbage collection etc.
4. Secure: because it uses java language.

Servlets - Form Data & Basics of


Web
Posted by Rakesh Singh

Basics of Web-
There are some key points that must be known by the servlet programmer. Let's first
briefly discuss these points before starting the servlet. These are:
HTTP
HTTP Request Types
Difference between Get and Post method
Container
Server
Difference between web server and application server
Content Type
Introduction of XML
Deployment
HTTP (Hyper Text Transfer Protocol)
Http is the protocol that allows web servers and browsers to exchange data over the
web.It is a request response protocol.

Http Request Methods


Every request has a header that tells the status of the client. There are many request
methods. Get and Post requests are mostly used. The http request methods are:
GET
POST
HEAD
PUT
DELETE
OPTIONS
TRACE
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.There are many content types:
text/html
text/plain
application/msword
application/vnd.ms-excel
application/jar
application/pdf
application/octet-stream
application/x-zip
images/jpeg
vedio/quicktime etc.
GET method:
The GET method sends the encoded user information appended to the page request.
The page and the encoded information are separated by the ? character as follows:
http://www.dineshonjava.com/login?key1=value1&key2=value2
The GET method is the defualt method to pass information from browser to web server
and it produces a long string that appears in your browser's Location:box. Never use the
GET method if you have password or other sensitive information to pass to the server.
The GET method has size limtation: only 1024 characters can be in a request string.

Anatomy of Get Request


As we know that data is sent in request header in case of get request. It is the default
request type. Let's see what information are sent to the server.

This information is passed using QUERY_STRING header and will be accessible


through QUERY_STRING environment variable and Servlet handles this type of
requests using doGet() method.
GET Method Example Using URL:
Here is a simple URL which will pass two values to HelloForm program using GET
method.
http://localhost:8080/HelloServlet?user_name=Dinesh&password=Sweety
Below is HelloServlet.java servlet program to handle input given by web browser. We
are going to use getParameter() method which makes it very easy to access passed
information:

// Import required java libraries


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

// Extend HttpServlet class


public class HelloServlet extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Using GET Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title +
"</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title +
"</h1>\n" +
"<ul>\n" +
" <li><b>User Name</b>: "
+ request.getParameter("user_name") +
"\n" +
" <li><b>Password</b>: "
+ request.getParameter("password") +
"\n" +
"</ul>\n" +
"</body></html>");
}
}
Compiling a Servlet:
Let us put above code if HelloWorld.java file and put this file in D:\Servlet (Windows) or
/usr/Servlet (Unix) then you would need to add these directories as well in
CLASSPATH.\

Assuming your environment is setup properly, go in Servlet directory and compile


HelloServlet.java as follows:

If the servlet depends on any other libraries, you have to include those JAR files on your
CLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using
any other library in Hello World program.

If everything goes fine, above compilation would produce HelloServlet.class file in the
same directory. Next section would explain how a compiled servlet would be deployed
in production.

Servlet Deployment:
By default, a servlet application is located at the path C:\Program Files (x86)\Apache
Software Foundation\Tomcat 7.0\webapps\ROOT\ and the class file would reside in
C:\Program Files (x86)\Apache Software Foundation\Tomcat 7.0\webapps\ROOT\WEB-
INF\classes.
For now, let us copy HelloServlet.class into /webapps/ROOT/WEB-INF/classes and
create following entries in web.xml file located in C:\Program Files (x86)\Apache
Software Foundation\Tomcat 7.0\webapps\ROOT\/webapps/ROOT/WEB-INF/

<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
POST method:
A generally more reliable method of passing information to a backend program is the
POST method. This packages the information in exactly the same way as GET
methods, but instead of sending it as a text string after a ? in the URL it sends it as a
separate message. This message comes to the backend program in the form of the
standard input which you can parse and use for your processing. Servlet handles this
type of requests using doPost() method.

Anatomy of Post Request


As we know, in case of post request original data is sent in message body. Let's see
how informations are passed to the server in case of post request.

Reading Form Data using Servlet:


Servlets handles form data parsing automatically using the following methods
depending on the situation:
getParameter(): You call request.getParameter() method to get the value of a
form parameter.
getParameterValues(): Call this method if the parameter appears more than
once and returns multiple values, for example checkbox.
getParameterNames(): Call this method if you want a complete list of all
parameters in the current request.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloServlet extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Using POST Method to Read Form Data";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>User Name</b>: "
+ request.getParameter("user_name") + "\n" +
" <li><b>Password</b>: "
+ request.getParameter("password") + "\n" +
"</ul>\n" +
"</body></html>");
}
// Method to handle POST method request.
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}

Difference between GenericServlet


and HttpServlet
Posted by Rakesh Singh

GenericServlet class implements Servlet, ServletConfig and Serializable interfaces. It


provides the implementaion of all the methods of these interfaces except the service
method. GenericServlet may be directly extended by a servlet, although it's more
common to extend a protocol-specific subclass such as HttpServlet.

GenericServlet makes writing servlets easier. It provides simple versions of the lifecycle
methods init and destroy and of the methods in the ServletConfig interface.
GenericServlet also implements the log method, declared in the ServletContext
interface.

GenericServlet class can handle any type of request so it is protocol-independent.

You may create a generic servlet by inheriting the GenericServlet class and providing
the implementation of the service method.

Methods of GenericServlet class


There are many methods in GenericServlet class. They are as follows:
public void init(ServletConfig config) is used to initialize the servlet.
public abstract void service(ServletRequest request, ServletResponse
response) provides service for the incoming request. It is invoked at each time when
user requests for a servlet.
public void destroy() is invoked only once throughout the life cycle and
indicates that servlet is being destroyed.
public ServletConfig getServletConfig() returns the object of ServletConfig.
public String getServletInfo() returns information about servlet such as writer,
copyright, version etc.
public void init() it is a convenient method for the servlet programmers, now
there is no need to call super.init(config)
public ServletContext getServletContext() returns the object of
ServletContext.
public String getInitParameter(String name) returns the parameter value for
the given parameter name.
public Enumeration getInitParameterNames() returns all the parameters
defined in the web.xml file.
public String getServletName() returns the name of the servlet object.
public void log(String msg) writes the given message in the servlet log file.
public void log(String msg,Throwable t) writes the explanatory message in the
servlet log file and a stack trace.

Difference between HttpServlet and GenericServlet-


javax.servlet.GenericServlet
Signature: public abstract class GenericServlet extends java.lang.Object
implements Servlet, ServletConfig, java.io.Serializable
GenericServlet defines a generic, protocol-independent servlet.
GenericServlet gives a blueprint and makes writing servlet easier.
GenericServlet provides simple versions of the lifecycle methods init and
destroy and of the methods in the ServletConfig interface.
GenericServlet implements the log method, declared in the ServletContext
interface.
To write a generic servlet, it is sufficient to override the abstract service method.

javax.servlet.http.HttpServlet
Signature: public abstract class HttpServlet extends GenericServlet implements
java.io.Serializable
HttpServlet defines a HTTP protocol specific servlet.
HttpServlet gives a blueprint for Http servlet and makes writing them easier.
HttpServlet extends the GenericServlet and hence inherits the
properties GenericServlet.
Servlet Example by inheriting the GenericServlet class-
Let's see the simple example of servlet by inheriting the GenericServlet class.

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

public class HelloServlet extends GenericServlet{


public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{

res.setContentType("text/html");

PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");

}
}

Class HttpServlet
Posted by Rakesh Singh

The HttpServlet class extends the GenericServlet class and implements Serializable
interface. It provides http specific methods such as doGet, doPost, doHead, doTrace
etc. The javax.servlet.http.HttpServlet class is a slightly more advanced base class than
the GenericServlet.

The HttpServlet class reads the HTTP request, and determines if the request is an
HTTP GET, POST, PUT, DELETE, HEAD etc. and calls one the corresponding
method.

Similar to the GenericServlet class this class is also abstract and we extend it make the
SubClass work like a servlet. The SubClass must override one of the following
methods:-
doGet() - for HTTP GET requests
doPost() - for HTTP POST requests
doDelete() - for HTTP DELETE requests
doPut() - for HTTP PUT requests
init()/destroy() - for managing the resources during the life of the servlet
getServletInfo() - this method is used by the servlet to provide information about
itself

service() method of HTTPServlet class is not abstract as was the case in the
GenericServlet class and there is hardly any need to override that method as by default
it contains the capability of deciding the type of the HTTP request it receives and based
on that it calls the specific method to do the needful. For example, if an HTTP GET
request calls the servlet then the service nethod of the HTTPServlet class determines
the request type (it'll find it to be GET) and subsequently calls doGet() method to serve
the request.

Methods of HttpServlet class

public void service(ServletRequest req,ServletResponse res) dispatches the


request to the protected service method by converting the request and response object
into http type.
protected void service(HttpServletRequest req, HttpServletResponse
res) receives the request from the service method, and dispatches the request to the
doXXX() method depending on the incoming http request type.
protected void doGet(HttpServletRequest req, HttpServletResponse
res) handles the GET request. It is invoked by the web container.
protected void doPost(HttpServletRequest req, HttpServletResponse
res) handles the POST request. It is invoked by the web container.
protected void doHead(HttpServletRequest req, HttpServletResponse
res) handles the HEAD request. It is invoked by the web container.
protected void doOptions(HttpServletRequest req, HttpServletResponse
res) handles the OPTIONS request. It is invoked by the web container.
protected void doPut(HttpServletRequest req, HttpServletResponse
res) handles the PUT request. It is invoked by the web container.
protected void doTrace(HttpServletRequest req, HttpServletResponse
res) handles the TRACE request. It is invoked by the web container.
protected void doDelete(HttpServletRequest req, HttpServletResponse
res) handles the DELETE request. It is invoked by the web container.
protected long getLastModified(HttpServletRequest req) returns the time
when HttpServletRequest was last modified since midnight January 1, 1970 GMT.

To respond to e.g. HTTP GET requests only, you will extend the HttpServlet class, and
override the doGet() method only. Here is an example:
view plainprint?

1. public class SimpleHttpServlet extends HttpServlet {


2.
3. protected void doGet( HttpServletRequest request,
4. HttpServletResponse response)
5. throws ServletException, IOException {
6.
7. response.getWriter().write("<html><body>GET response</body>
</html>");
8. }
9. }
If you want to handle both GET and POST request from a given servlet, you can
override both methods, and have one call the other. Here is how:
view plainprint?

1. public class SimpleHttpServlet extends HttpServlet {


2.
3. protected void doGet( HttpServletRequest request,
4. HttpServletResponse response)
5. throws ServletException, IOException {
6.
7. doPost(request, response);
8. }
9.
10. protected void doPost( HttpServletRequest request,
11. HttpServletResponse response)
12. throws ServletException, IOException {
13.
14. response.getWriter().write("GET/POST response");
15. }
16. }

I would recommend you to use the HttpServlet instead of the GenericServlet whenever
possible. HttpServlet is easier to work with, and has more convenience methods than
GenericServlet.
HttpRequest
Posted by Rakesh Singh

The HttpServlet class request processing methods take two parameters.


1. javax.servlet.http.HttpRequest
2. javax.servlet.http.HttpResponse
For instance, here is the signature of the HttpServlet.doGet() method:

protected void doGet(


HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

The purpose of the HttpRequest object is to represent the HTTP request a browser
sends to your web application. Thus, anything the browser may send, is accessible via
the HttpRequest.

The HttpRequest object has a lot of methods, so I will just cover the most commonly
used here.
1. Parameters
2. Headers
3. InputStream
4. Session
5. ServletContext
Parameters
The request parameters are parameters that are sent from the browser along with the
request. Request parameters are typically sent as part of the URL (in the "query string"),
or as part of the body of an HTTP request. For instance:
http://www.dineshonjava.com/somePage.html?param1=hello&m2=world

Notice the "query string" part of the URL: ?param1=hello&m2=world This part
contains two parameters with parameter values:

param1=hello
param2=world

You can access these parameters from the HttpRequest object like this:

protected void doGet(


HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
String param1 = request.getParameter("param1");
String param2 = request.getParameter("param2");

}
You would use the same code, if the request parameters were sent in the body part of
the HTTP request. If no parameter exists with the given name, null is returned.

In general, if the browser sends an HTTP GET request, the parameters are included in
the query string in the URL. If the browser sends an HTTP POST request, the
parameters are included in the body part of the HTTP request.

Headers
The request headers are name, value pairs sent by the browser along with the HTTP
request. The request headers contain information about e.g. what browser software is
being used, what file types the browser is capable of receiving etc. In short, at lot of
meta data around the HTTP request.

You can access the request headers from the HttpRequest object like this:

String contentLength = request.getHeader("Content-Length");


This example reads the Content-Length header sent by the browser.

The Content-Length header contains the number of bytes sent in the HTTP request
body, in case the browser sends an HTTP POST request. If the browser sends an
HTTP GET request, the Content-Length header is not used, and the above code will
return null.

In general, If no header exists with the name passed to getHeader(), null is returned.
InputStream
If the browser sends an HTTP POST request, request parameters and other potential
data is sent to the server in the HTTP request body. It doesn't have to be request
parameters that is sent in the HTTP request body. It could be pretty much any data, like
a file or a SOAP request (web service request).

To give you access to the request body of an HTTP POST request, you can obtain an
InputStream pointing to the HTTP request body. Here is how it is done:

InputStream requestBodyInput = request.getInputStream();


NOTE: You will have to call this method before calling any getParameter() method,
because calling the getParameter() method on an HTTP POST request will cause the
servlet engine to parse the HTTP request body for parameters. Once parsed, you
cannot access the body as a raw stream of bytes anymore.

What you do with the data read from the InputStream is up to you. The servlet engine
does not help you parse or interprete that data. You just get it raw.
Session
It is possible to obtain the session object from the HttpRequest object too.

The session object can hold information about a given user, between requests. So, if
you set an object into the session object during one request, it will be available for you
to read during any subsequent requests within the same session time scope.

Here is how you access the session object from the HttpRequest object:

HttpSession session = request.getSession();

ServletContext
You can access the ServletContext object from the HttpRequest object too. The
ServletContext contains meta information about the web application. For instance, you
can access context parameters set in the web.xml file, you can forward the request to
other servlets, and you can store application wide parameters in the ServletContext too.

Here is how you access the ServletContext object from the HttpRequest object:

ServletContext context = request.getSession().getServletContext();


As you can see, you have to first get the session object, to get access to the
ServletContext object.

HttpResponse Servlet
Posted by Rakesh Singh

The HttpServlet class request processing methods take two parameters.


1. javax.servlet.http.HttpRequest
2. javax.servlet.http.HttpResponse
The HttpServletResponse object generates a response to return to the requesting
client. Its methods allow you to set the response header and the response body.

The first line of the Response


header (response.setContentType("text/html");) identifies the MIME type of the
response. The following three lines are often placed in servlet code to prevent Web
browsers and proxy servers from caching dynamically-generated Web pages. If you
want your dynamic Web page to be cached, remove these three lines of code.

The response object also has the getWriter() method to return a PrintWriter object.
The print() and println() methods of thePrintWriter object write the servlet response
back to the client.
For instance, here is the signature of the HttpServlet.doGet() method:

protected void doGet(


HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {

}
In this text I will look at the HttpResponse object.

The purpose of the HttpResponse object is to represent the HTTP response your web
application sends back to the browser, in response to the HTTP request the browser
send to your web application.

Methods to Set HTTP Response Header:


There are following methods which can be used to set HTTP response header in your
servlet program. These methods are available with HttpServletResponse object.

1 String encodeRedirectURL(String url)


Encodes the specified URL for use in the sendRedirect method or, if encoding is not
needed, returns the URL unchanged.
2 String encodeURL(String url)
Encodes the specified URL by including the session ID in it, or, if encoding is not
needed, returns the URL unchanged.
3 boolean containsHeader(String name)
Returns a boolean indicating whether the named response header has already been
set.
4 boolean isCommitted()
Returns a boolean indicating if the response has been committed.
5 void addCookie(Cookie cookie)
Adds the specified cookie to the response.
6 void addDateHeader(String name, long date)
Adds a response header with the given name and date-value.
7 void addHeader(String name, String value)
Adds a response header with the given name and value.
8 void addIntHeader(String name, int value)
Adds a response header with the given name and integer value.
9 void flushBuffer()
Forces any content in the buffer to be written to the client.
10 void reset()
Clears any data that exists in the buffer as well as the status code and headers.
11 void resetBuffer()
Clears the content of the underlying buffer in the response without clearing headers or
status code.
12 void sendError(int sc)
Sends an error response to the client using the specified status code and clearing the
buffer.
13 void sendError(int sc, String msg)
Sends an error response to the client using the specified status.
14 void sendRedirect(String location)
Sends a temporary redirect response to the client using the specified redirect location
URL.
15 void setBufferSize(int size)
Sets the preferred buffer size for the body of the response.
16 void setCharacterEncoding(String charset)
Sets the character encoding (MIME charset) of the response being sent to the client, for
example, to UTF-8.
17 void setContentLength(int len)
Sets the length of the content body in the response In HTTP servlets, this method sets
the HTTP Content-Length header.
18 void setContentType(String type)
Sets the content type of the response being sent to the client, if the response has not
been committed yet.
19 void setDateHeader(String name, long date)
Sets a response header with the given name and date-value.
20 void setHeader(String name, String value)
Sets a response header with the given name and value.
21 void setIntHeader(String name, int value)
Sets a response header with the given name and integer value.
22 void setLocale(Locale loc)
Sets the locale of the response, if the response has not been committed yet.
23 void setStatus(int sc)
Sets the status code for this response.

The HttpResponse object has a lot of methods, so I will just cover the most commonly
used here. The rest you can read about in the JavaDoc, if you are interested. The parts
I will cover are:
1. Writing HTML
2. Headers
3. Content-Type
4. Writing Text
5. Content-Length
6. Writing Binary Data
7. Redirecting to a Different URL
8. Writing HTML

To send HTML back to the browser, you have to obtain the a PrintWriter from the
HttpResponse object. Here is how:

PrintWriter writer = response.getWriter();


writer.write("<html><body>GET/POST response</body></html>");
Headers
Just like the request object, the HttpRequest can contain HTTP headers. Headers must
be set before any data is written to the response. You set a header on the response
object like this:

response.setHeader("Header-Name", "Header Value");


As you can see, a response header is a name, value pair.

Content-Type
The Content-Type header is a response header that tells the browser the type of the
content you are sending back to it. For instance, the content type for HTML is text/html.
Similarly, if what you send back to the browser is plain text, you use the content type
text/plain.

Here is how you set the Content-Type header on the HttpResponse object:

response.setHeader("Content-Type", "text/html");

Writing Text
You can write text back to the browser instead of HTML, like this:

response.setHeader("Content-Type", "text/plain");

PrintWriter writer = response.getWriter();


writer.write("This is just plain text");
First the Content-Type header is set to text/plain. Then a plain text string is written to
the writer obtained from the response object.

Content-Length
The Content-Length header tells the browser how many bytes your servlet is sending
back. If you are sending binary data back you need to set the content length header.
Here is how:

response.setHeader("Content-Length", "31642");

Writing Binary Data


You can also write binary data back to the browser instead of text. For instance, you
can send an image back, a PDF file or a Flash file or something like that.
Again, you will first have to set the Content-Type header to the type matching the data
you are sending back. For instance, the content type for a PNG image is image/png.

You can search for "mime types" in your favourite search engine to find a list of mime
types (content types), so you can find the mime type for the content you are sending
back.

In order to write binary data back to the browser you cannot use the Writer obtained
from response.getWriter(). Afterall, Writer's are intended for text.

Instead you have to use the OutputStream obtained from


the response.getOutputStream() method. Here is how:

OutputStream outputStream = response.getOutputStream();


outputStream.write(...);
Redirecting to a Different URL
You can redirect the browser to a different URL from your servlet. You cannot send any
data back to the browser when redirecting. Here is how you redirect:

response.sendRedirect("http://www.dineshonjava.com");
Create the HTTP response
After the servlet request code, add the response code:

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

public class ServletSample extends HttpServlet


{

public void doGet (HttpServletRequest request, HttpServletResponse


response)
throws ServletException, IOException
{

Enumeration keys;
String key;
String myName = "";
keys = request.getParameterNames();
while (keys.hasMoreElements())
{
key = (String) keys.nextElement();
if (key.equalsIgnoreCase("myName")) myName =
request.getParameter(key);
}
System.out.println("Name = ");
if (myName == "") myName = "Hello";
response.setContentType("text/html");
response.setHeader("Pragma", "No-cache");
response.setDateHeader("Expires", 0);
response.setHeader("Cache-Control", "no-cache");

PrintWriter out = response.getWriter();


out.println("<html>");
out.println("<head><title>Just a basic servlet</title></head>");
out.println("<body>");
out.println("<h1>Just a basic servlet</h1>");
out.println ("<p>" + myName + ", this is a very basic servlet.");
out.println("</body></html>");
out.flush();

}
}

Das könnte Ihnen auch gefallen