Nearby lessons

27 of 34

Servlet - Examples: API & First Servlet

📌 What You Will Learn
  • See complete runnable servlet programs
  • Understand the output of each program
  • Copy and deploy programs in Tomcat

Complete servlet programs for Servlet API, GenericServlet, HttpServlet, and your first servlet.

Servlet API

This package defines several classes and interfaces used for developing protocol independent

servlets(Generic Servlets)

Example01
JCode Cell
1 
2 javax.servlet package
3 javax.servlet.http package
4 javax.servlet:
5

Servlet API

This package defines several classes and interfaces which can be used to develop Http protocol

based servlets.

Important interfaces of javax.servlet package:

1.Servlet

2.ServletRequest

3.ServletResponse

4.ServletConfig

5.ServletContext

6.RequestDispatcher

7.SingleThreadModel

1.Servlet (I):

Every Servlet in Java should implements Servlet Interface either directly OR indirectly.

This Interface defines the most common Methods which are applicable for any Servlet Object.

The Life Cycle Methods of Servlet are defined in this Interface only.

public class FirstServlet implements Servlet

{

}

Example02
JCode Cell
1 
2 javax.servlet.http :
3

Servlet API

For every request web container creates one request object.

ServletRequest object holds end user provided information.

Servlet can use this request object to get end user's provided information.

Example03
JCode Cell
1 
2 ServletRequest(I):
3

Servlet API

For every request web container creates one response object.

Servlet can use response object to prepare and send response to end user.

4.ServletConfig(I):

For every Servlet web container will creates a seperate config object to hold its configuration

information.

Servlet can use this config object to get its configuration information.

Example04
JCode Cell
1 
2 ServletResponse(I):
3

Servlet API

For every web application web container creates a seperate context object to hold application

level configuration information.

Servlet can use this context object to get application level configuration information.

Note: ServletConfig is per Servlet where as ServletContext is per web application.

6.RequestDispatcher(I):

We can use RequestDispatcher to dispatch request from one servlet to another servlet.

Example05
JCode Cell
1 
2 ServletContext(I):
3

Servlet API

Single servlet object can be accessed by multiple threads simultaneously and hence there may be

a chance of data inconsistency problems. i.e servlet by default not thread safe.

To overcome this problem we should go for SingleTheadModel.

If our servlet class implements SingleThreadModel then our servlet object can be accessed by only

one thread at a time.

public class FirstServlet implements Servlet,SingleThreadModel

{

}

The main advantage of SingleThreadModel is threads will be executed one by one and hence data

inconsistency problems will be resolved.

But the main disadvantage of SingleThreadModel is, it increases waiting time of Threads and

creates performance problems.Hence it is not recommended to use SingleThreadModel and it is

deprecated in Servlet 2.4V.

Instead of SingleThreadModel it is recommended to use synchronized keyword.

SingleThreadModel interface does not contain any methods and it is marker interface.Internally

JVM is responsible to provide required ability.

Important classes of javax.servlet package:

1.GenericServlet

2.ServletInputStream

3.ServletOutputStream

4.ServletException

1.GenericServlet:

GenericServlet implements Servlet interface.

GenericServlet acts as base class to develop protocol independent servlets.

Eg:

public class FirstServlet extends GenericServlet

{

}

  • ServletInputStream:

We can use ServletInputStream to read binary data send by end user.

  • ServletOutputStream:

We can use ServletOutputStream to write binary data to the response.

4.ServletException:

while processing our request if servlet faces any problem then we will get ServletException

Example06
JCode Cell
1 
2 SingleThreadModel(I):
3

Servlet(I)

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

This method will be executed automatically by web container for every request to provide

required response.

Total service logic,we have to write in this method only.

3.destroy() method:

public void destroy()

This method will be executed only once by the web container to perform cleanup activities just

before taking servlet object from out of service.

Once destroy() method completes automatically webcontainer destroys that servlet object.

This is usually happens at the time of server shutdown or at the time of application

undeployment.

Note: init(),service() and destroy() methods are called life cycle methods of servlet.

4.getServletConfig():

public ServletConfig getServletConfig()

This method returns ServletConfig object. By using this object servlet can get its configuration

information.

Example07
JCode Cell
1 
2 service() method:
3

Servlet(I)

public String getServletInfo()

This method returns information about our servlet like author,version,copyright information

etc..

init()

service()

destroy()

getServletInfo()

getServletConfig()

Note:

init(),service() and destroy() methods are called callback methods because these methods will be

executed automatically by the web container.

getServletConfig() and getServletInfo() methods should be called explicitly by the programmer

based on our requirement and hence these methods are called in line methods.

Steps to develop First web application:

Step-1: Developing servlet by implementing Servlet interface:

Every Servlet in java should implements Servlet interface either directly or indirectly.

Whenever we are implementing Servlet interface compulsary we should provide implementation

for all 5 methods of Servlet interface.

Example08
JCode Cell
1 
2 getServletInfo()
3

FirstServlet.java

The basic purpose of servlet is to provide response to the end user.

We can set content type of response as follows

resp.setContentType("text/html");

MIME Type represents the type of response we are sending to the end user.

The default MIME Type is : text/html

Other popular MIME Types are:

application/pdf

image/jpeg

video/mp4

etc..

We can write text data(character data) to the response by using PrintWriter.

We can get PrintWriter which is pointing to response as follows...

PrintWriter out=resp.getWriter();

By using this PrintWriter if we are writing any text data ,it will be written to response object,which

will be delivered to the end user.

By using SOP() statements if we are writing anything,it will be displayed to the server console and

won't send to the end user.

Note:

Servlet Programs won't be run by programmer and web server is responsible to run. Hence main

method concept is not applicable to servlet classes and we cannot run servlet from command

prompt.

Step 2: Compilation of Servlet class:

After developing servlet class, we have to compile just like our normal java class.

In the servlet program what ever dependent classes we used, are available in servlet-api.jar.

web server vendor is responsible to provide this jar file.

In Tomcat installation this jar file is available in the following location

D:\Tomcat 7.0\lib

Hence to compile a servlet, we have to place this jar file in the classpath.

classpath

D:\Tomcat 7.0\lib\servlet-api.jar

Step-3: Creation of Deployment Descriptor(web.xml):

For every web application we have to provide one xml file named with web.xml. This web.xml file

is also known as Deployment Descriptor.

web container will use this xml file to get information about our servlets.Hence web.xml acts as

guide to web container.

Example09
JCode Cell
1 
2 import javax.servlet.*;
3 import java.io.*;
4 import java.util.*;
5 public class FirstServlet implements Servlet
6 {
7 static
8 {
9 System.out.println("servlet class loading...");
10 }
11 public FirstServlet()
12 {
13 System.out.println("servlet instantiation...");
14 }
15 public void init(ServletConfig config) throws ServletException
16 {
17 System.out.println("init() method execution...");
18 }
19 public void service(ServletRequest req,ServletResponse resp) throws ServletException,IOException
20 {
21 resp.setContentType("text/html");
22 System.out.println("service() method execution...");
23 PrintWriter out=resp.getWriter();
24 out.println("<h1>Welcome Innocent Advanced Java Students</h1>");
25 out.println("<h1>The Server Time is:"+new Date()+"</h1>");
26 }
27 public void destroy()
28 {
29 System.out.println("destroy() method execution...");
30 }
31 public ServletConfig getServletConfig()
32 {
33 return null;
34 }
35 public String getServletInfo()
36 {
37 return "Developed by Durga";
38 }
39 }
40

FirstServlet.java

Step-4: creation of web application folder structure:

Servlet API defines some standard structure for web application

Every web server can able to understand this application structure.

advapps1A

WEB-INF

web.xml

classes

FirstServlet.class

Step-5: Deployment of web application in the web server:

Once we developed web application according standard folder structure, we have to place this

application inside web server. This process is called deployment.

We have to place our application in the Tomcat Server of following location.(D:\Tomcat

7.0\webapps)

Step-6: start server and send the request

Once we deployed application in the web server,we can send the request as follows...

http://localhost:7777/advapps1A/test

Protocol The MachineName of the Application url-pattern
on which Server(Context Root)

is running

The Port Number

on which Server

is running

For the First Request:

servlet loading

Servlet Instantiation

Init Method called

Service Method called

For the Second Request onwards:

Service Method called

Note: At the time of first request servlet class will be loaded and servlet object will be created

followed by init() method execution.Finally service() method will be called.

But for second request onwards only service() method will be called.

Because of this the processing time of first request is more when compared with other requests.

To overcome this problem we should go for <load-on-startup>. If we configured

<load-on-startup> then servlet class loading,servlet instantiation and execution of init() method

will be performed at the time of server start up or at the time of application deployment.

For the first request also only service() method will be called.

We can configure <load-on-startup> in web.xml as follows...

<web-app>

<servlet>

...

<load-on-startup>10</load-on-startup>

</servlet>

.....

</web-app>

The main advantage of <load-on-startup> is all requests will be processed with uniform response

time.

Case 1: without <load-on-startup>:

Example10
JCode Cell
1 
2 <web-app>
3 <servlet>
4 <servlet-name>DemoServlet</servlet-name>
5 <servlet-class>FirstServlet</servlet-class>
6 </servlet>
7
8 <servlet-mapping>
9 <servlet-name>DemoServlet</servlet-name>
10 <url-pattern>/test</url-pattern>
11 </servlet-mapping>
12 </web-app>
13

FirstServlet.java

http://localhost:7777/advapps1A3X/test

Example11
JCode Cell
1 
2 import javax.servlet.*;
3 import java.io.*;
4 import java.util.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test")
7 public class FirstSevlet implements Servlet
8 {
9 static
10 {
11 System.out.println("servlet class loading..");
12 }
13 public FirstSevlet()
14 {
15 System.out.println("Servlet class Instantiation...");
16 }
17 public void init(ServletConfig conf) throws ServletException
18 {
19 System.out.println("Init Method called");
20 }
21 public void service(ServletRequest req , ServletResponse resp) throws ServletException,IOException
22 {
23 System.out.println("Service Method called");
24 resp.setContentType("text/html");
25 PrintWriter out = resp.getWriter();
26 out.println("<html><body bgcolor=green text=white><h1>Welcome Innocent Adv.Java Students<br/>");
27 out.println("The Server Time is :"+new Date()+"</h1></body></html>");
28 }
29 public void destroy()
30 {
31 System.out.println("Destroy Method called");
32 }
33 public ServletConfig getServletConfig()
34 {
35 return null;
36 }
37 public String getServletInfo()
38 {
39 return "written by durga";
40 }
41 }
42

FirstServlet.java

advapps1B

|-- WEB-INF

|-- classes

|--FirstServlet.class

Note:

In the above program two classes are avaialble FirstServlet and GenericServlet. Web container

creates object for FirstServlet class.

If web container calls any method , first it will check whether our FirstServlet class contains that

method or not. If our class contains that method then it will be executed. If our class does not

contain that method then only parent class method(GenericServlet) will be executed.

First priority for our class and then GenericServlet class because object is available for our class.

Internal implementation of GenericServlet:

Example12
JCode Cell
1 
2 import javax.servlet.*;
3 import java.io.*;
4 import javax.servlet.annotation.*;
5 @WebServlet("/test")
6 public class FirstSevlet extends GenericServlet
7 {
8 public void service(ServletRequest req, ServletResponse resp) throws ServletException,IOException
9 {
10 PrintWriter out = resp.getWriter();
11 out.println("<h1>Writing servlet by extending GS is very easy</h1>");
12 }
13 }
14
Output

    <h1>Writing servlet by extending GS is very easy</h1>
          

FirstServlet.java

Case-1: If our servlet class does not contain any init() method:

If our servlet class does not contain any init() method then web container always calls

init(SC config) method of GenericServlet.

Inside this method config object will be saved for the future purpose and calls no-arg init()

method.

web container will check whether our servlet class contains no-arg init() method or not.If our

servlet class does not contain no-arg init() method, then GenericServlet no-arg init() method will

be called, which has empty implementation.

In this case getServletConfig() method returns config object.

CASe 2: If we override init(SC) in our servlet class:

public void init(ServletConfig config)throws SE

{

SOP("initialization activities");

}

Web container will always calls our class init(SC) method. This is way of overriding init() method is

not recommended b'z we are not saving config object for the future purpose. In this case

getServletConfig() method returns null.

Case-3: If we override no-arg init() method:

public void init()throws SE

{

SOP("initialization activities");

}

In this case web container will always calls GenericServlet class init(SC) method, which saves

config object for the future purpose and internally calls no-arg init() method.Then our servlet class

no-arg init() method will be called.

In this case getServletConfig() method returns config object.

Note:

1.If our servlet class does not contain any init()method:

GS: init(SC)===>GS:init()

2.If our servlet class contains init(SC) method

FS:init(SC)

3.If our servlet class contains no-arg init() method:

GS:init(SC) ===>FS:init()

Q.why GenericServlet class contains 2 init() methods?

init(SC) is for web container purpose

init() for programmer purpose

Q.In our servlet which init() method is recommended to override?

no-arg init() method

Q.In GenericServlet class config variable declared as transient. what is the reason?

due to security constraints config object should not be travelled across the network.

Flow Chart For Servlet Life Cycle That extends GenericServlet

If it is for DynamicIf our

Class

doesn't

contains

If our Class contains

If it is Available If it is not Available If our Class

contains

If our Class doesn't contains

javax.servlet.http:

This package contains several classes and interfaces which can be used for developing Http based

servlets.

Important interface of javax.servlet.http package:

1.HttpServletRequest:

It is the child interface of ServletRequest

We can use request object to get end user provided information.

2.HttpServletResponse:

It is the child interface of ServletResponse

We can use response object to prepare and send response to the end user.

3.HttpSession:

We can use HttpSession object to implement session management.

Important classes of javax.servlet.http package:

1.HttpServlet:

It is the child class of GenericServlet.

HttpServlet acts as base class to develop Http based servlets.

  • Cookie:

We can use Cookies in the session management.

Example13
JCode Cell
1 
2 public abstract class GenericServlet implements Servlet, ServletConfig, Serializable
3 {
4 private transient ServletConfig config;
5
6 public void init(ServletConfig config) throws ServletException
7 {
8 this.config = config;
9 init();
10 }
11
12 public void init() throws ServletException
13 {
14 }
15
16 public ServletConfig getServletConfig()
17 {
18 return config;
19 }
20 ::::::::::::::::::::::::::::::::
21 }
22

Response Body

Big-7 HTTP 4. PUT

Methods 5. DELETE

Example14
JCode Cell
1 
2 GET Introduced in HTTP/1.0 V
3 POST
4 HEAD
5

Response Body

::::::::::::::

GET,POST and HEAD introduced in HTTP/1.0V

The first 7 methods are called Big-7 Http Methods

Note:

Until Servlet 2.4V,web server can provide support for the first-7 HTTP methods.But from Servlet

2.5 version onwards web server can provide support for the remaining methods also.

Note:

Being java developer we have to aware only GET and POST methods.

Example15
JCode Cell
1 
2 OPTIONS
3 TRACE Introduced in HTTP/1.1 V
4 CONNECT
5 MOVE
6 LOCK
7

POST Method

from the Server.Information to the Server.
2) Usually GET requests are READ-ONLY.2) Usually POST Requests are WRITE or UPDATE

Operations.

Example16
JCode Cell
1 
2 We can use GET Method to GET Information 1) We can use POST Method to POST
3

POST Method

append to the URL as the Part of Query Stringencapsulated in the Request Body and send to
and send to the Server.the Server.
4) By using GET Request we can send only4) By using POST Request we can send both
Character Data (ASCII) and we cannot sendBinary and Character Data to the Server.

Binary Data like Images.

Example17
JCode Cell
1 
2 End User provided Information will be 3) End User provided Information will be
3

POST Method

limited Amount of Information, which is variedAmount of Information to the Server.

from Browser to Browser.

Example18
JCode Cell
1 
2 By using GET Request we can send only 5) By using POST Request we can send huge
3

POST Method

sensitive Information like User Name, Password sensitive Information like User Name, Password

etc.etc.
7) Book Marking of GET Request is possible.7) Book Marking of POST Request is not

possible.

Example19
JCode Cell
1 
2 Security is less and hence we cannot send 6) Security is more and hence we can send
3

POST Method

Request:Request:
Typing URL in the Address Bar and enterSubmitting the HTML FORM with
Clicking Hyper LinkMethod Attribute of POST Value.

Submitting the HTML FORM with

Method Attribute of GET Value.

Example20
JCode Cell
1 
2 Caching of GET Request is possible. 8) Caching of POST Request is not possible.
3 GET Request is Idempotent. 9) POST Request is not Idempotent.
4 GET Request is safe. 10) POST Request is not safe.
5 There are multiple ways to send GET 11) There is only one way to send POST
6

HttpServlet

Example21
JCode Cell
1 
2 public void service(ServletRequest req,ServletResponse resp)throws SE,IOE
3 protected void service(HttpServletRequest req,HttpServletResponse resp)throws SE,IOE
4

Demo Program for developing servlet by extending HttpServlet

Example22
JCode Cell
1 
2 <html>
3 <body><h1> This is HttpServletDemo to send Post request</h1>
4 <form action = "/advapps1C/test" method="POST">
5 Enter Name :<input type="text" name="uname"><br/>
6 <input type="submit" value="Login">
7 </form>
8 </body>
9 </html>
10

FirstServlet.java

advapps1C

|-- login.html

|-- WEB-INF

|-- classes

|--FirstServlet.class

If we are sending GET request then doGet() method will be executed and if we are sending POST

request then doPost() method will be executed.

Life cycle of HttpServlet:

  • Whenever we submit form ,browser prepares HttpRequest and send to the server.

2.Web server checks whether request is for static or for dynamic information.

3.If the request is for static information then web server provides the required response if it is

available,otherwise it will send 404 status code saying requested resource is not available.

4.If the request is for dynamic information then web server forwards the request to web

container.

5.web container will identify corresponding servlet class based on url pattern and with the help of

web.xml

6.web container will check whether servlet object is available or not.

7.If the servlet object is not available then web container loads servlet class,instantiate servlet and

execute init() method.

[ execution of init() method is exactly same as GenericServlet life cycle]

8.web container creates ServletRequest and ServletResponse objects and invokes public service()

method by passing these as arguments.

9.web container will check whether our servlet class contains public service(SR,SR) method or not.

If our servlet class contains public service(SR,SR) method then it will be executed and provides

required response.

10.If our servlet class does not contain public service() method then parent class(HttpServlet)

public service(SR,SR) method will be executed, which is implemented as follows...

public void service(SR req, SR resp) throws SE, IOE

{

HttpServletRequest request=(HSR)req;

HttpServletResponse response=(HSR)resp;

service(request, response);

}

Inside HttpServlet public service() method, req and resp objects will be type casted to

HttpServletRequest and HttpServletResponse and then invoke protected service(HSR,HSR)

method.

web container will check whether our servlet class contains protected service(HSR,HSR) method or

not.

If our servlet class contains protected service(HSR,HSR) method then it will be executed and

provide required response to the end user.

If our servlet class does not contain protected service() method then web container will execute

HttpServlet protected service() method.

HttpServlet protected service() method will identify request method(like get,post etc) and invoke

corresponding doXxx() method.

protected void service(HSR req,HSR resp)throws SE,IOE

{

String method = req.getMethod();

if(method.equals("GET"))

{

doGet(req,resp);

} else

if(method.equals("POST"))

{

doPost(req, resp);

}

...

else

{

return 501 status code saying http method not implemented.

}

}

webcontainer will check whether our servlet class contains the corresponding doXxx() method or

not.If our servlet class contains doXxx() method then it will be executed and provide required

response.

If our servlet class does not contain doXxx() method then parent class HttpServlet doXxx() method

will be executed,which is implemented as follows...

protected void doGet(HSR req,HSR resp)throws SE,IOE

{

return 405|400 status code saying Http Method GET is not supported by this url.

}

HttpServlet doXxx() method wont do anything and just it will share error information to the end

user.

Note:

Web Container will always calls the methods in the following order

public service(SR,SR)

protected service(HSR,HSR)

public doXxx(HSR,HSR)

Flow Chart For Servlet Life Cycle That extends HttpServlet

RequestWeb Server
If it is for Static, Web Server providedWeb
Response if it is available, otherwiseServer Checks
provide 404 Error Response, sayingwhether the Request
requested Resource not availableis for Static OR
Dynamic?Servlet Class loading Usually these Steps will be

Servlet Instantiation performed at the time of

If it is for DynamicFirst Request.

If we configure

Web Server Forwards Request to Web<load-on-startup> then,
Container. Web Container Identifythese will be performed at
corresponding Servlet Class based oneither Server Start up OR
URL & with the help of web.xmlat the time of Application

Deployment

WebIf it is not
Container ChecksAvailableExecution of init()

whether the Servlet

Object is available

OR not?

If it is Available

Web Container calls

public service (SR, SR) Method

Browser

Execute our ClassIf our ClassWeb
public service (SR, SR)containsContainer will Check
Method and providewhether our Class contain
Responsepublic service (SR, SR) Method

OR not?

If our Class does not contains

Web Container will call HttpServlet

public service (SR, SR). It will Typecast

SR and SR Objects into HSR and HSR

and invoke

protected service (HSR, HSR) Method

Execute our ClassIf our ClassWeb
protected servicecontainsContainer will Checks
(HSR, HSR)whether our Class contain
Method and provideprotected service (HSR, HSR)
ResponseMethod OR not?

If our Class does not contains

Web Container will execute HttpServlet protected service

(HSR, HSR). Internally it will Identify Request Method and

invoke the corresponding doXxx() Method

Execute our ClassIf our ClassWeb
doXxx ()containsContainer will Check
Method and providewhether our Servlet Class
Responsecontains the corresponding

doXxx() Method OR not?

If our Class does not contains

Web Container will execute HttpServlet

doXxx() Method which provide 400/405 Status

Response saying Http Method Xxx not supported

by this URL.

Finally Web Container will call destroy()

HUDA Maitrivanam, Ameerpet,

Case-1:

If our servlet class contains public service(SR,SR) method then for any type of request(like get,post

etc)

only this public service(SR,SR) method will be executed.

case-2:

If our servlet class contains both public service(SR,SR) and protected service(HSR,HSR) then public

service(SR,SR) method will be executed for any type of request(like get,post etc)

case-3:

If our servlet class contains protected service() and doGet() methods,then for any type of request

including GET, protected service() method will be executed.

*case-4:

If we are sending GET request but our servlet does not contain doGet() method and it contains

doPost() method,then HttpServlet doGet() method will be executed which returns error

information

HTTP Status 405 - HTTP method GET is not supported by this URL

case-5:

If we are sending POST request,but our servlet class does not contain doPost() method and it

contains doGet() method then HttpServlet doPost() method will be executed which returns error

information

HTTP Status 405 - HTTP method POST is not supported by this URL

case-6:

To provide common response for both GET and POST requests,we have to implement our servlet

as follows..

Example23
JCode Cell
1 
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 import java.io.*;
5 import javax.servlet.annotation.*;
6 @WebServlet("/test")
7 public class FirstSevlet extends HttpServlet
8 {
9 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10 {
11 PrintWriter out = resp.getWriter();
12 out.println("<h1>This is from doGET()method...</h1>");
13 }
14 public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
15 {
16 PrintWriter out = resp.getWriter();
17 out.println("<h1>This is from doPOST()method...</h1>");
18 }
19 }
20
Output

    <h1>This is from doGET()method...</h1>
    <h1>This is from doPOST()method...</h1>
          

FirstServlet.java

Example24
JCode Cell
1 
2 public class FirstSevlet extends HttpServlet
3 {
4 public void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
5 {
6 PrintWriter out = resp.getWriter();
7 out.println("<h1>This is common response for both GET and Post methods...</h1>");
8 }
9 public void doPost(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException
10 {
11 doGet(req,resp);
12 }
13 }
14
Output

    <h1>This is common response for both GET and Post methods...</h1>
          
📝 Key Takeaways
  • Every example is complete and compiles as-is
  • Examples are grouped by topic
  • Typing programs is the fastest way to learn servlets