Nearby lessons
27 of 34Servlet - Examples: API & First Servlet
- 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)
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
{
}
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.
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.
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.
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
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.
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.
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.
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 Machine | Name 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>:
FirstServlet.java
http://localhost:7777/advapps1A3X/test
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:
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 Dynamic | If 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.
Response Body
Big-7 HTTP 4. PUT
Methods 5. DELETE
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.
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.
POST Method
| append to the URL as the Part of Query String | encapsulated in the Request Body and send to |
|---|---|
| and send to the Server. | the Server. |
| 4) By using GET Request we can send only | 4) By using POST Request we can send both |
| Character Data (ASCII) and we cannot send | Binary and Character Data to the Server. |
Binary Data like Images.
POST Method
| limited Amount of Information, which is varied | Amount of Information to the Server. |
|---|
from Browser to Browser.
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.
POST Method
| Request: | Request: |
|---|---|
| Typing URL in the Address Bar and enter | Submitting the HTML FORM with |
| Clicking Hyper Link | Method Attribute of POST Value. |
Submitting the HTML FORM with
Method Attribute of GET Value.
HttpServlet
Demo Program for developing servlet by extending HttpServlet
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
| Request | Web Server |
|---|---|
| If it is for Static, Web Server provided | Web |
| Response if it is available, otherwise | Server Checks |
| provide 404 Error Response, saying | whether the Request |
| requested Resource not available | is for Static OR |
| Dynamic? | Servlet Class loading Usually these Steps will be |
Servlet Instantiation performed at the time of
| If it is for Dynamic | First Request. |
|---|
If we configure
| Web Server Forwards Request to Web | <load-on-startup> then, |
|---|---|
| Container. Web Container Identify | these will be performed at |
| corresponding Servlet Class based on | either Server Start up OR |
| URL & with the help of web.xml | at the time of Application |
Deployment
| Web | If it is not | |
|---|---|---|
| Container Checks | Available | Execution 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 Class | If our Class | Web |
|---|---|---|
| public service (SR, SR) | contains | Container will Check |
| Method and provide | whether our Class contain | |
| Response | public 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 Class | If our Class | Web |
|---|---|---|
| protected service | contains | Container will Checks |
| (HSR, HSR) | whether our Class contain | |
| Method and provide | protected service (HSR, HSR) | |
| Response | Method 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 Class | If our Class | Web |
|---|---|---|
| doXxx () | contains | Container will Check |
| Method and provide | whether our Servlet Class | |
| Response | contains 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..
FirstServlet.java
- Every example is complete and compiles as-is
- Examples are grouped by topic
- Typing programs is the fastest way to learn servlets