Unit-V Servlets: Advanced Java Programming

Download as pdf or txt
Download as pdf or txt
You are on page 1of 24

Advanced Java Programming

Unit-V

Servlets

Servlet technology is used to create web application (resides at server side and generates
dynamic web page).

Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was popular as a server-side programming
language. But there was 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.

1
Advanced Java Programming

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.

________________________________________

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:

1. If number of clients increases, it takes more time for sending response.

2. For each request, it starts a process and Web server is limited to start processes.

3. It uses platform dependent language e.g. C, C++, Perl.

________________________________________

Advantage of Servlets

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, lightweight, 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 memory leak, garbage
collection etc.

2
Advanced Java Programming

4. Secure: because it uses java language.

Servlet Terminology

1. Basics of Servlet

2. HTTP

3. Http Request Methods

4. Difference between Get and Post

5. Anatomy of Get Request

6. Anatomy of Post Request

7. Content Type

There are some key points that must be known by the servlet programmer like server, container,
get request, post request etc. Let's first discuss these points before starting the servlet technology.

The basic terminology used in servlet is given below:

1. HTTP

2. HTTP Request Types

3. Difference between Get and Post method

4. Container

5. Server and Difference between web server and application server

6. Content Type

7. Introduction of XML

8. Deployment

3
Advanced Java Programming

HTTP (Hyper Text Transfer Protocol)

1. Http is the protocol that allows web servers and browsers to exchange data over the web.

2. It is a request response protocol.

3. Http uses reliable TCP connections by default on TCP port 80.

4. It is stateless means each request is considered as the new request. In other words, server
doesn't recognize the user by default.

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

HTTP Request Description

GET Asks to get the resource at the requested URL.

POST Asks the server to accept the body info attached. It is like GET request with extra info
sent with the request.

4
Advanced Java Programming

HEAD Asks for only the header part of whatever a GET would return. Just like GET but with no
body.

TRACE Asks for the loopback of the request message, for testing or troubleshooting.

PUT Says to put the enclosed info (the body) at the requested URL.

DELETE Says to delete the resource at the requested URL.

OPTIONS Asks for a list of the HTTP methods to which the thing at the request URL can
respond

________________________________________

What is the difference between Get and Post?

There are many differences between the Get and Post request. Let's see these differences:

GET POST

1) In case of Get request, only limited amount of data can be sent because data is sent in header.
In case of post request, large amount of datacan be sent because data is sent in body.

2) Get request is not secured because data is exposed in URL bar. Post request is secured
because data is not exposed in URL bar.

3) Get request can be bookmarked Post request cannot be bookmarked

4) Get request is idempotent. It means second request will be ignored until response of first
request is delivered. Post request is non-idempotent

5) Get request is more efficient and used more than Post Post request is less efficient and used
less than get.

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 informations are sent to the server.

5
Advanced Java Programming

Container

It provides runtime environment for JavaEE (j2ee) applications.

It performs many operations that are given below:

1. Life Cycle Management


2. Multithreaded support
3. Object Pooling
4. Security etc.

Server

It is a running program or software that provides services.

There are two types of servers:

1. Web Server
2. Application Server

Web Server

Web server contains only web or servlet container. It can be used for servlet, jsp, struts, jsf etc. It
can't be used for EJB.

Example of Web Servers are: Apache Tomcat and Resin.

6
Advanced Java Programming

Application Server

Application server contains Web and EJB containers. It can be used for servlet, jsp, struts, jsf,
ejb etc.

Example of Application Servers are:

1. JBoss Open-source server from JBoss community.


2. Glassfish provided by Sun Microsystem. Now acquired by Oracle.
3. Weblogic provided by Oracle. It more secured.
4. Websphere provided by IBM.

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
• video/quicktime etc.

7
Advanced Java Programming

Servlet API
1. Servlet API
2. Interfaces in javax.servlet package
3. Classes in javax.servlet package
4. Interfaces in javax.servlet.http package
5. Classes in javax.servlet.http package

The javax.servlet and javax.servlet.http packages represent interfaces and classes for servlet api.

The javax.servlet package contains many interfaces and classes that are used by the servlet or
web container. These are not specific to any protocol.

The javax.servlet.http package contains interfaces and classes that are responsible for http
requests only.

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:

1. Servlet
2. ServletRequest
3. ServletResponse
4. RequestDispatcher
5. ServletConfig
6. ServletContext
7. SingleThreadModel
8. Filter
9. FilterConfig
10. FilterChain
11. ServletRequestListener

8
Advanced Java Programming

12. ServletRequestAttributeListener
13. ServletContextListener
14. ServletContextAttributeListener

Classes in javax.servlet package

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

1. GenericServlet
2. ServletInputStream
3. ServletOutputStream
4. ServletRequestWrapper
5. ServletResponseWrapper
6. ServletRequestEvent
7. ServletContextEvent
8. ServletRequestAttributeEvent
9. ServletContextAttributeEvent
10. ServletException
11. UnavailableException

Interfaces in javax.servlet.http package

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

1. HttpServletRequest
2. HttpServletResponse
3. HttpSession
4. HttpSessionListener
5. HttpSessionAttributeListener
6. HttpSessionBindingListener
9
Advanced Java Programming

7. HttpSessionActivationListener
8. HttpSessionContext (deprecated now)

Classes in javax.servlet.http package

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

1. HttpServlet
2. Cookie
3. HttpServletRequestWrapper
4. HttpServletResponseWrapper
5. HttpSessionEvent
6. HttpSessionBindingEvent
7. HttpUtils (deprecated now)

Servlet Interface
1. Servlet Interface
2. Methods of Servlet interface

Servlet interface provides common behaviour 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.

10
Advanced Java Programming

Method Description

public void init(ServletConfig config) initializes the servlet. It is the life cycle method of servlet and
invoked by the web container only once.

public void service(ServletRequest provides response for the incoming request. It is invoked at
request,ServletResponse response) each request by the web container.

public void destroy() is invoked only once 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.

Servlet Example by implementing Servlet interface

Let's see the simple example of servlet by implementing the servlet interface.

It will be better if you learn it after visiting steps to create a servlet.

File: First.java

1. import java.io.*;
2. import javax.servlet.*;
3.
4. public class First implements Servlet{
5. ServletConfig config=null;
6.
7. public void init(ServletConfig config){
8. this.config=config;

11
Advanced Java Programming

9. System.out.println("servlet is initialized");
10. }
11.
12. public void service(ServletRequest req,ServletResponse res)
13. throws IOException,ServletException{
14.
15. res.setContentType("text/html");
16.
17. PrintWriter out=res.getWriter();
18. out.print("<html><body>");
19. out.print("<b>hello simple servlet</b>");
20. out.print("</body></html>");
21.
22. }
23. public void destroy(){System.out.println("servlet is destroyed");}
24. public ServletConfig getServletConfig(){return config;}
25. public String getServletInfo(){return "copyright 2007-1010";}
26.
27. }

GenericServlet class
1. GenericServlet class
2. Methods of GenericServlet class
3. Example of GenericServlet class

12
Advanced Java Programming

GenericServlet class implements Servlet, ServletConfig andSerializable interfaces. It provides


the implementaion of all the methods of these interfaces except the service method.

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:

1. public void init(ServletConfig config) is used to initialize the servlet.


2. 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.
3. public void destroy() is invoked only once throughout the life cycle 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.
6. public void init() it is a convenient method for the servlet programmers, now there is no
need to call super.init(config)
7. public ServletContext getServletContext() returns the object of ServletContext.
8. public String getInitParameter(String name) returns the parameter value for the given
parameter name.
9. public Enumeration getInitParameterNames() returns all the parameters defined in the
web.xml file.
10. public String getServletName() returns the name of the servlet object.
11. public void log(String msg) writes the given message in the servlet log file.

13
Advanced Java Programming

12. public void log(String msg,Throwable t) writes the explanatory message in the servlet
log file and a stack trace.

Servlet Example by inheriting the GenericServlet class

Let's see the simple example of servlet by inheriting the GenericServlet class.

It will be better if you learn it after visiting steps to create a servlet.

File: First.java

1. import java.io.*;
2. import javax.servlet.*;
3.
4. public class First extends GenericServlet{
5. public void service(ServletRequest req,ServletResponse res)
6. throws IOException,ServletException{
7.
8. res.setContentType("text/html");
9.
10. PrintWriter out=res.getWriter();
11. out.print("<html><body>");
12. out.print("<b>hello generic servlet</b>");
13. out.print("</body></html>");
14.
15. }
16. }

14
Advanced Java Programming

HttpServlet class
1. HttpServlet class
2. Methods of HttpServlet class

The HttpServlet class extends the GenericServlet class and implements Serializable interface.
It provides http specific methods such as doGet, doPost, doHead, doTrace etc.

Methods of HttpServlet class

There are many methods in HttpServlet class. They are as follows:

1. 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.
2. 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.
3. protected void doGet(HttpServletRequest req, HttpServletResponse res) handles the
GET request. It is invoked by the web container.
4. protected void doPost(HttpServletRequest req, HttpServletResponse res) handles the
POST request. It is invoked by the web container.
5. protected void doHead(HttpServletRequest req, HttpServletResponse res) handles
the HEAD request. It is invoked by the web container.
6. protected void doOptions(HttpServletRequest req, HttpServletResponse res) handles
the OPTIONS request. It is invoked by the web container.
7. protected void doPut(HttpServletRequest req, HttpServletResponse res) handles the
PUT request. It is invoked by the web container.
8. protected void doTrace(HttpServletRequest req, HttpServletResponse res) handles
the TRACE request. It is invoked by the web container.
9. protected void doDelete(HttpServletRequest req, HttpServletResponse res) handles
the DELETE request. It is invoked by the web container.

15
Advanced Java Programming

10. protected long getLastModified(HttpServletRequest req) returns the time when


HttpServletRequest was last modified since midnight January 1, 1970 GMT.

Life Cycle of a Servlet (Servlet Life Cycle)


1. Life Cycle of a Servlet
1. Servlet class is loaded
2. Servlet instance is created
3. init method is invoked
4. service method is invoked
5. destroy method is invoked

The web container maintains the life cycle of a servlet instance. Let's see the life cycle of the
servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

16
Advanced Java Programming

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.

17
Advanced Java Programming

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:

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:

public void service(ServletRequest request, ServletResponse response) throws Servlet


Exception, IOException

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:

public void destroy()

18
Advanced Java Programming

Steps to create a servlet example

Steps to create the servlet using Tomcat server

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the application

There are given 6 steps to create a servlet example. These steps are required for all the servers.

The servlet example can be created by three ways:

1. By implementing Servlet interface,


2. By inheriting GenericServlet class, (or)
3. By inheriting HttpServlet class

The mostly used approach is by extending HttpServlet because it provides http request specific
method such as doGet(), doPost(), doHead() etc.

Here, we are going to use apache tomcat server in this example. The steps are as follows:

1. Create a directory structure


2. Create a Servlet
3. Compile the Servlet
4. Create a deployment descriptor
5. Start the server and deploy the project
6. Access the servlet

19
Advanced Java Programming

1)Create a directory structures

The directory structure defines that where to put the different types of files so that web
container may get the information and respond to the client.

The Sun Microsystem defines a unique standard to be followed by all the server vendors. Let's
see the directory structure that must be followed to create the servlet.

As you can see that the servlet class file must be in the classes folder. The web.xml file must be
under the WEB-INF folder.

2)Create a Servlet
There are three ways to create the servlet.

1. By implementing the Servlet interface


2. By inheriting the GenericServlet class

20
Advanced Java Programming

3. By inheriting the HttpServlet class

The HttpServlet class is widely used to create the servlet because it provides methods to
handle http requests such as doGet(), doPost, doHead() etc.

In this example we are going to create a servlet that extends the HttpServlet class. In this
example, we are inheriting the HttpServlet class and providing the implementation of the
doGet() method. Notice that get request is the default request.

DemoServlet.java

1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class DemoServlet extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
7. {
8. res.setContentType("text/html");//setting the content type
9. PrintWriter pw=res.getWriter();//get the stream to write the data
10.
11. //writing html in the stream
12. pw.println("<html><body>");
13. pw.println("Welcome to servlet");
14. pw.println("</body></html>");
15.
16. pw.close();//closing the stream
17. }}

21
Advanced Java Programming

3)Compile the servlet

For compiling the Servlet, jar file is required to be loaded. Different Servers provide different jar
files:

Jar file Server

1) servlet-api.jar Apache Tomcat

2) weblogic.jar Weblogic

3) javaee.jar Glassfish

4) javaee.jar JBoss

Two ways to load the jar file


1. set classpath
2. paste the jar file in JRE/lib/ext folder

Put the java file in any folder. After compiling the java file, paste the class file of servlet
in WEB-INF/classesdirectory.

4)Create the deployment descriptor (web.xml file)

The deployment descriptor is an xml file, from which Web Container gets the information
about the servet to be invoked.

The web container uses the Parser to get the information from the web.xml file. There are many
xml parsers such as SAX, DOM and Pull.

22
Advanced Java Programming

There are many elements in the web.xml file. Here is given some necessary elements to run the
simple servlet program.

web.xml file

1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>sonoojaiswal</servlet-name>
10. <url-pattern>/welcome</url-pattern>
11. </servlet-mapping>
12.
13. </web-app>

Description of the elements of web.xml file

There are too many elements in the web.xml file. Here is the illustration of some elements that is
used in the above web.xml file. The elements are as follows:

<web-app> represents the whole application.

<servlet> is sub element of <web-app> and represents the servlet.

<servlet-name> is sub element of <servlet> represents the name of the servlet.

<servlet-class> is sub element of <servlet> represents the class of the servlet.

23
Advanced Java Programming

<servlet-mapping> is sub element of <web-app>. It is used to map the servlet.

<url-pattern> is sub element of <servlet-mapping>. This pattern is used at client side to


invoke the servlet.

5)Start the Server and deploy the project

To start Apache Tomcat server, double click on the startup.bat file under apache-tomcat/bin
directory.

24

You might also like