You are on page 1of 39

Comspark Info India Pvt Ltd.

CSREDDY

SERVLETS
At the beginning stages of computers we have client server architecture. Where the
main purpose of the server is to share the static resources to the client requirements. In
this case when we send a request to the server machine, server will identify the requested
resource and send back to the client machine as a response. Here server is generating the
response without executing any application at server machine so that this kind of response
is called as static response. As per the application requirements we need to get dynamic
response from server machine. To generate dynamic response server must execute some
applications at server machine, for this we should provide server side applications.
To provide server side programming for the sake of dynamic response we should use
the fallowing server side technologies.
1) CGI
2) Servlets
3) JSP …. Etc

1) To generate dynamic response we have already CGI technology then why


you go for Servlets technology?

CGI:
a) CGI is a technology which was designed on the basis of ‘C’ technology and
some scripting technology. As we know ‘C’ technology is a process based
technology.
b) If we deploy any CGI application at server for every new request came from
client automatically server will create a separate process at server machine.
c) Process is a heavy weight component that’s why to handle it system must
consume more number of system resources.
d) In the above situation if we increase more number of requests to the same
CGI application then server will create more number of processes. This
approach will increase burden to the server machine as a result application
quality could be degraded.

Servlets urtrainer.java@gmail.com 1
Comspark Info India Pvt Ltd. CSREDDY

SERVLETS:
a) Servlets is a server side technology which was designed on the basis of
Java Technology. As we know Java is a Thread Based Technology that’s
why Servlets is also a Thread Based Technology.
b) If we deploy any Servlets application at server machine then for every
new request came from clients automatically servlet may create a
separate thread on the servlet object.
c) If we increase more number of client requests then more number of
threads will be created instead of process.
d) Thread is a light weight component when compare to process that’s why
this approach will not increase burden to the server machine.

2) Write the differences between Servlets and Jsp’s?


a) To design any web application if we use Servlets as a technology then we should
require minimum java knowledge.
To design the same web application if we use JSP as a technology then it is not at
all require to have java knowledge.
b) Servlets are good at the time of pickup the request and process the requests.
Jsp’s are good at the time of delivering the dynamic response to client with very
good look and feel.
c) In case of Servlets we are enable to separate presentation logic and business
logic.
But in case of Jsp’s we are able to separate both presentation logic and business
logic due to the availability of separate tags for presentation and separate tags for business
logic.
d) If we made any modifications on the existed servlet then we should require
recompiling and reloaded to server explicitly.
If we made any modifications on the existed Jsp’s is it not require to recompiling
and reloaded to server explicitly. Why bcz JSP pages are auto compiled and auto loaded.
e) If we go for any MVC Based Web applications where we should use Servlets as a
Controller and Jsp’s as a View Part.
Eg: In Struts Frame Work we will use ActionServlet as a controller and some set of and
some set of Jsp’s as a view part.
Eg: In case of JSF Frame Work we should use FacesServlet as a controller and some set
of Jsp’s as a view part.

MVC Diagram:

Servlets urtrainer.java@gmail.com 2
Comspark Info India Pvt Ltd. CSREDDY

Client Server Architecture:

To design any web application minimum we should require 2-tier architecture i.e.
client server architecture. In this c-s architecture we have mainly three components are
there. They are given bellow.
1) CLIENT
2) PROTOCOL
3) SERVER
CLIENT:
The job of the client machine in client server architecture is to send request and to
get the responses from the server machine.
From client machine to send request and to get the responses we should use a tool
at client machine called as Browser, here Browser is acting like a Client.
In client server architecture we will send request from client to the server by
specifying a string at clients address bar called as URI.

3) Write the differences between URI, URL & URN?

URI (Uniform Resource Identifier) is a string specification which can be used to


refer an object available at server machine. There are two types of URI’s and these are
I) URL: is a string specification which can be used to refer an
object available at server machine through its locator. In case of
Servlets URL Pattern is the Locator.
II) URN: is a string specification which can be used to refer an
object available at server machine through its Logical name. In
case of Servlets Logical Name is a name specified along with the
servlet name tag in web.xml file.
In the web applications almost all the servers are supporting the URL
representation not URN.
SYN:
Protocolname:\\ServerIPAddress:ServerPortNumber\ApplicationContext\
Resource Path [ ?name1:value1&name2:value2…]
4) Write the Difference between IP Address and Port Number?

IP Address is an unique identification to each and every machine over the network,
which could be provided by the network manager.
Port Number is an unique identification to each and every process being executed at
the single machine, which could be provided by the local operating system.
5) What do you mean by Query String?

It is a collection of name value pairs appended to URL in order to send input data to
a particular web resource from client machine.

Servlets urtrainer.java@gmail.com 3
Comspark Info India Pvt Ltd. CSREDDY

PROTOCOL:
It is a set of rules and regulations, which can be used to carry the data from one
machine to another machine over the network.
 The main purpose of protocol in the client server architecture is to carry request from
client to the server and to carry response from server to the client. TCP, IP, UDP,
HTTP, ARP, RARP…… etc
 In general we will use Http protocol in our web applications why?

 In general web application requires a protocol and it must satisfy the fallowing
properties.

 1) Connection less protocol: Not to have physical connection, to have a logical


connection.

 2) Stateless protocol: Not to remember the previous request data at the time of
processing the later request.

 3) A compatible protocol should carry hypertext data: In general we will carry


only hypertext data as a request from client to server and as a response from server
to client.
 Http protocol is a connection less, stateless and a compatible protocol to
carry hypertext data from client to server and from server to client.
6) How Http protocol maintain its stateless nature?

In the web applications we send a request from client machine when protocol will
establish a virtual socket connection in between client and the server.

 After getting the connection, protocol will prepare a request format having header
part and body part, where header part will maintain all the request headers i.e. client
and servers IP Address, Port Numbers, accepted language, client URL ……. Where
Body part will maintain client specified input data.
 After getting the request format protocol will carry request format to the server,
where server will generate response while execution of a particular web application.
 Upon receiving response from server, protocol will prepare response format having
header part and body part. Where header part will maintain response headers like
content type, client URI, Status line. Where body part will maintain server generated
dynamic response.
 After getting the response format protocol will carry that to the client machine.
Where client Browser will take that html response and executed and display the
response on the client Browser.
 When response was reached to the client machine protocol will terminate the
established virtual socket connection.
 The data which we transferred along with the request and along with the response
could be remembered by the protocol up to the existence of virtual socket
connection.

 At the time of processing the later request protocol could not maintain previous
request data; there fore Http protocol is a stateless protocol.

Servlets urtrainer.java@gmail.com 4
Comspark Info India Pvt Ltd. CSREDDY

HTTP PROTOCOL:
 Http protocol will provide an advantage for the developers to specify different types
of request at client machine. This flexibility is possible due to the availability of 7
number of Http methods at Http Protocol.

 As per the Http 1.0 version the Http methods are 1) GET 2) POST 3) HEAD
 As per the Http 1.1 version the Http methods
 1) Options 2) PUT 3) TRACE 4) DELETE

 The common name for all the above Http methods is BIG-7 Http Methods.
 Http 1.1 version has introduced one reserved Http Method that is Connect.
7) Write the differences between GET Request and POST Request?
What are the diff b/w DOGET method & DOPOST Method? (Invalid Question)
1) GET Request is a default request where as POST request is not a default request.
2) GET Request should not have the Body Part where as POST Request should have Body
Part.
3) Due to unavailability of the Body Part with the GET Request if we specify any input data
at client machine then GET Request will carry that to the server through the request
format header part but request format header part should have memory limitation. It
can able to accommodate up to 256 number of characters. Hence GET Request able to
carry less volume of the data.
Due to availability of Body Part in POST Request if we specify any
input data at client machine then POST Request will carry that to the server through
Request Format Body part. Here Request Format Body Part should not have any
memory limitation hence POST Request able to carry large volumes of the data.

4) If we specify any secure data at client machine along with the get request then that
client data will be appended on the client address bar as a query string along with URL.
There fore GET Request will not provide security for the client specified input data.
If we specify any input data with the POST Request at the client
machine then that input data could not appear on the client address bar hence POST
Request will provide security for the client data.
5) In general GET request can be used to download the data from server and POST
Request can be used to upload the data on to the server.
6) In general GET request could support Book Marks at the Browser but POST
Request could not support Book Marks at Browser.
8) What are the differences between GET Request and HEAD Request?
When we send a GET Request for a particular resource available at server machine
then server will send back only the requested resource as a response to the client machine.
If we send HEAD Request for a particular web resource then server will send back
the requested resource as well as the Meta data of the requested resource as a response to
the client machine.
HEAD Request internally uses GET Request.

Servlets urtrainer.java@gmail.com 5
Comspark Info India Pvt Ltd. CSREDDY

OPTIONS Request: This request type can be used to identify which Http Methods could be
supported by the present server available at the server machine.
9) What are the differences between POST Request and PUT Request?
Both POST and PUT Request can be used to upload the data on to the server.
 To upload the data if we use POST Request then it is not mandatory to specify any
location on server machine along with the request at the client machine.
 To upload the data on to the server if we use PUT Request then it is mandatory to
specify particular location on server machine along with the request at client
machine.

 NOTE: almost all the servers are not supporting PUT Request as per their security
constraints.
TRACE Request:
This Request type can be used to check out the working status of a particular
resource available at server machine. TRACE Request is a simulation of echo server.
DELETE Request:
This Request type can be used to delete a particular resource available at server
machine. Almost all the servers are not supporting DELETE Request as per their security
constraints.
Http Status Codes:
 Http protocol has introduced a concept called as Status Codes to get the status of
the request processing from server machine.
 To do the above Http 1.1 version has introduced the fallowing status codes.
Status Code Range Description
1XX 100-199 INFORMATION STATUS CODES
2XX 200-299 SUCCESS RELATED STATUS CODES
3XX 300-399 REDIRECTIONAL STATUS CODES
4XX 400-499 CLIENT SIDE ERRORS
5XX 500-599 SERVER SIDE ERRORS
SERVER:
To the job of the server in Client Server Architecture is to get the request and to
generate the response. If we want to make a machine as a server machine then we need to
install a piece of software called as server software.
Eg:
1) Apache Tomcat
2) BEA Web logic (Oracle)
3) IBM Web sphere
4) Macromedia JRUN
5) Sun Micro Systems J2EE, SUNONE, Glass Fish ……….. etc..
There are two types of servers are there.

Servlets urtrainer.java@gmail.com 6
Comspark Info India Pvt Ltd. CSREDDY

 Web Servers
 Application Servers
10) What are the differences between Web server and Application Server?
> Web servers are the servers which will provide the environment to execute only
Web Applications.
Application Servers are the servers, which will provide the environment to execute
both Web Applications and Distributed Applications.
> Web servers are the servers which will not provide middle ware services like logging,
authentication security, transactions, JNDI ………… etc..
Application Servers are the servers, which will provide all the above specified
middle ware services.
> Web Servers are the servers, which could work with only Web Clients (html clients).
Application Servers are the servers which could work with any kind of clients
(html, wml...) like web clients, mobile clients.
NOTE: Up to Tomcat 4.0 Version Web Server Tomcat 5.0 Version behaves like a
Application Server. Every server trying to convert as Application Server because of Web
Servers bounded nature.
When we install server software on the server machine automatically server
software will be available in the form of the fallowing two modules.
1) Main Server 2) Container
11) What are the differences between Main server and Container?
When we send a request from client to the server then main server will pick up the
request and validate the request data i.e. whether the request data having any harmful
code or not. If the request data validation succeeded then main server will bypass the
request to container.
Container is a component, which will accommodate the Web Applications, upon
receiving a request from main server container will execute the requested web application
and generate the dynamic response. After generating the dynamic response container will
bypass dynamic response to the main server where main server will forward dynamic
response to the protocol.
Types of Containers:
Containers could be classified in the fallowing two ways.
1) As per the technology which we are used.
a) Servlet Container to execute Servlets
b) JSP Container to execute Jsp’s
c) EJB Container to execute EJB Components
d) CGI Container to execute CGI Components. ………. Etc…
2) As per the Containers physical existence there are three types of containers.
i) Standalone Containers: It is an integration of Main Server and Container.
ii) In Process Containers: It is a container existed inside the Main Server.

Servlets urtrainer.java@gmail.com 7
Comspark Info India Pvt Ltd. CSREDDY

iii) Out of Process Container: It is a container existed in out side of the Main Server.
Note: Now a days all the servers are using Standalone Containers for the easy of
maintenance.

Steps to Design Web Application

To design any Web Application we should use the fallowing steps.


1) Prepare Web Applications Directory Structure
2) Design Deployment Descriptor
3) Design the Web Resources as per the Application
Requirements
4) Start the server and execute the Web Application
STEP: 1 Web Applications Directory Structure:
When we install the Tomcat Server automatically Tomcat 5.5 (if the version is 5.5)
folder will be created. Tomcat server provides webapps is a folder to accommodate the
developers Web Applications as Shown bellow.

Tomcat 5.5
bin webapps
lib application folder/ context root
config themes (.css) WEB-INF
common images (.jpg, .img) web.xml classes
log literature (.doc) lib (.jar) .class
work .html .class
.jsp

As per the application requirements we should prepare our own folder under
webapps folder called as application folder/context root.
Application folder includes
1. themes: To maintain cascade style sheets
2. images: To maintain back ground scenarios, logo’s of the organization in the
form of .jif, .jpeg etc...
3. literature: To maintain documentations about the web applications.
4. static resources: .html files
5. dynamic resources: .jsp files
6. WEB-INF: To maintain web applications deployment information. Where WEB-
INF folder includes
a) Deployment Descriptor: To provide the description about the web
applications deployment.

Servlets urtrainer.java@gmail.com 8
Comspark Info India Pvt Ltd. CSREDDY

b) lib folder: To maintain the explicit .jar files which are required for the
web application design.
c) classes: Which includes all the .class files like servlets, filters, listeners ….

The above web application directory structure could be divided into the fallowing two
parts. They are given bellow
1) Public Area/ Client Area: The area which comes under outside of the
WEB-INF folder. If we deploy any resource under public area then client
able to access it with its file name directly.
2) Private Area/ Server Area: The area which comes under inside the
WEB-INF folder is called as private area or server area. If we deploy any
resource under private area then client unable to access that resources
with their names directly, client able to access that resources through
indirection.
In general servlets could be deployed under private area to access these servlets we
must define the uri patterns, through these uri patterns only client able to access the
respective servlet.

STEP: 2 Deployment Descriptor:


It is a web.xml file, which will provide the complete description about the web
applications deployment.
Deployment Descriptor should provide the fallowing
1. servlet configuration
2. filters configuration
3. listeners configuration
4. welcome files configuration
5. initialization parameters
6. context parameters
7. session timed out
8. load-on-start up
9. error pages configuration
10. Security constraints etc…
In general in the web applications we are able to deploy the servlets under
classes folder i.e. private area, where client able to access the servlets through
indirection i.e. through URL pattern.
> To provide the mapping between servlet class and the respective URL pattern as part of
the servlet configuration we will use the fallowing xml tags in web.xml file.
<web-app>
<servlet>
<servlet-name>logical name</servlet-name>
<servlet-class>fully qualified name of servlet</servlet-class>
</servlet>

Servlets urtrainer.java@gmail.com 9
Comspark Info India Pvt Ltd. CSREDDY

<servlet-mapping>
<servlet-name> logical name </servlet-name>
<url-pattern>/url pattern name</url-pattern>
</servlet-mapping>
</web-app>
Eg:
<web-app>
<servlet>
<servlet-name>rep</servlet-name>
<servlet-class>reports</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>rep</servlet-name>
<url-pattern>/report</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>admin.html</welcome-file>
</welcome-file-list>
</web-app>

As part of the web applications we should define the URL patterns in web.xml file by
using the fallowing three approaches.
1) Exact Match Method
2) Directory Match Method
3) Extension Match Method
Exact Match Method:
In case of Exact Match Method we will define a URL pattern in web.xml file, where
client must provide the URL pattern in its URL the same URL pattern defined in web.xml file.
Eg: <url-pattern>/first</url-pattern>
http://localhost:8080/app1/first (valid) http://localhost:8080/app1/first/second (in valid)
http://localhost:8080/app1/second (in valid)
Directory Match Method:
In case of Directory Match Method we will define the URL pattern like bellow.
<url-pattern> /a/* </url-pattern>
In this case client must provide the URL pattern may starts with ‘a’ and may ends with
anything.
http://localhost:8080/app1/a (valid) http://localhost:8080/app1/a/b (valid)
http://localhost:8080/app1/b/a (in valid)
Extension Match Method:
In this case we will define the URL pattern like bellow in web.xml file.

Servlets urtrainer.java@gmail.com 10
Comspark Info India Pvt Ltd. CSREDDY

<url-pattern>*.do </url-pattern>
In this case client must provide the URL pattern may starts with anything and must ends
with the specified extension in web.xml file i.e. (.do)
http://localhost:8080/app1/a.do (valid) http://localhost:8080/app1/a (in valid)
http://localhost:8080/app1/a.xyz (in valid) http://localhost:8080/app1/a/b.do (valid)

STEP: 3
Design Web Resources as for the Application Requirements:
To design a servlet servlet API has provided the fallowing pre defined library in the
form of the packages javax.servlet.*; javax.servlet.http.*;
12) What is meant by servlet and in how many ways we are able to design
servlets?
Servlet is an object available at server machine, which was implemented either
directly or indirectly Servlet Interface. As per the predefined library provided by the Servlet
API there are three ways to design servlets.
Implementing Servlet Interface:
In this case take one user defined class which is implementing Servlet Interface.
public class Myservlet implements Servlet Interface
{
// Body of the Servlet
}
Extending Genericservlet Abstract Class:
In this case take one user defined class which is extending from Genericservlet abstract
class.
public class Myservlet extends Genericservlet
{
// Body of the Servlet
}
Extending Httpservlet Abstract Class:
In this case take one user defined class which is extending from Httpservlet abstract class.
public class Myservlet extends Httpservlet
{
// Body of the Servlet
}
STEP: 4
Start server and access the web application:
After design the web application to execute the web applications we need to start the
server. Here we are able to start the server in the fallowing three ways.
1) Use startup.batch file available in c:\Tomcat5.0\bin\stratup.batch

Servlets urtrainer.java@gmail.com 11
Comspark Info India Pvt Ltd. CSREDDY

2) Use system program Tomcat, for this we are using the path
start-> programs-> Apache Tomcat -> start Tomcat
3) Use system service apache Tomcat for this we are using the path
start-> Run -> services.msc ->ok -> select Apache Tomcat -> click on start
service
First Approach to Design the SERVLET:
In this approach we will take one user defined class, which is implementing Servlet
Interface.
Public interface Servlet
{ public void init(ServletConfig config)throws ServletException;
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException;
public ServletConfig getServletConfig();
public String getServletInfo();
public void destroy();
}
Public class Myservlet implements Servlet
{
//Body of the Servlet Class
}
 Where init() can be used to provide servlet initialization.

 Where service() can be used to provide required service for the request. Service() is
like main() in java applications, which will have the complete application logic and
which could be executed by the container upon receiving a request from the client
machine automatically.
 Where getServletConfig() can be used to return the generated Servlet Config object
reference.
 NOTE: Where ServletConfig is an object, which will maintain the configuration details
of a particular servlet like the logical name of the servlet, initialization parameters
and the reference of the servlet context object.
 Where getServletInfo() can be used to return the generalized description of the
particular servlet.
 Where destroy() can be used to destroy servlet object.
EX: The fallowing example demonstrates how to design a servlet by implementing
the ServletInterface and how to access from client machine?
Firstservletapp - WEB-INF  web.xml, classes  Myservlet.class
Web.xml
<web-app>
<servlet>
<servlet-name>ms</servlet-name>
<servlet-class>Myservlet</servlet-class>

Servlets urtrainer.java@gmail.com 12
Comspark Info India Pvt Ltd. CSREDDY

</servlet>
<servlet-mapping>
<servlet-name>ms</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>
</web-app>
Myservlet.java:
import javax.servlet.*;
import java.io.*;
public class Myservlet implements Servlet
{
public void init(ServletConfig config)throws ServletException
{
}
public ServletConfig getServletConfig()
{
return null;
}
public String getServletInfo()
{
return null;
}
public void destroy()
{
}
public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException
{ res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<body>");
out.println("<h1>");
out.println("Hellow _____First Servlet Using Servlet Interface");
out.println("</h1></body></html>");
}
}
 After getting the Servlets.java file we should compile it and we should keep the
generated .class file under the classes folder.

 To compile the servlets.java files we need to set the class path environment variable
to the location where we have Servlet-api.jar file.

 i.e.set classpath=%classpath%;C:\Tomcat 5.0\Common\lib\Servlet-api.jar;


 set classpath=%classpath%;C:\Tomcat 6.0\ lib\Servlet-api.jar;

Servlets urtrainer.java@gmail.com 13
Comspark Info India Pvt Ltd. CSREDDY

> In the web applications we send a request from client machine when protocol will
establish a virtual socket connection in between client and the server.
 After getting the connection, protocol will prepare a request format having header
part and body part, where header part will maintain all the request headers i.e. client
and servers IP Address, Port Numbers, accepted language, client URL ……. Where
Body part will maintain client specified input data.
 Protocol will carry request format to the server. Main server will pickup the request
and check out whether the request data having any harmful data or not, if the
validation success the main server will by pass the request to the container.
 When container receives a request from main server then container will take the
fallowing steps.
1. Identify the application context and resource name
2. Container will check whether the resource is html or jsp page, if the resource is html
or jsp page then container will search them under the application folder.
3. If the resource name is not having .html or .jsp extension container would
understand the resource name is a URL pattern for a particular servlet
available under classes folder.
4. Container will identify the name and location of the servlet with respect to the url
pattern by gone through web.xml file.
5. When container identifies the requested resource then container will take the
fallowing steps.
I) Servlet loading: Here the container will load the requested servlet byte code to
the memory.
II) Servlet instantiation: Here the container will create an object for loaded
servlet.
III) Servlet initialization: Here the container will execute the init() to perform
initialization of the servlet.
IV) Creating Request and Response Objects: After the servlet initialization
container will create a thread to access service method. To access service()
container must create servlet request and servlet response objects.
V) Generating Dynamic Response: After getting the request and response objects
container will execute service() method, here container will generate dynamic
response to the response object.
VI) Dispatching Dynamic Response to the Client: As part of the executing the
service method when container generated thread reaches to the ending part of
the service method then automatically thread will be in dead state, by this
container will dispatch response to the main server, here main server will by pass
the response to the protocol. Now protocol will prepare a response format having
header part to maintain response headers and having body part to maintain the
dynamic response. Now protocol will carry response to the respective client.

Servlets urtrainer.java@gmail.com 14
Comspark Info India Pvt Ltd. CSREDDY

VII) Destroying Request and Response Objects: When response was reached to
the client machine then protocol will terminate the virtual socket connection; by
this container will destroy request and response objects.
VIII) Servlet Deinstantiation: After destroying request and response objects
container will wait up to some time, depends on the container implementation,
when container identifies no further request for the same resource then container
will destroy the servlet object.
IX) Servlet Unloading: As per the servers memory management container will
unloads the loaded servlet Byte Code.
Drawbacks about first approach of designing:
In this approach if we want to design servlets we need to implement directly servlet
interface i.e. we should provide the implementation for all the methods got declared in
servlet interface irrespective of the application requirement.
This approach will increase burden for the developers and it will increase burden for
the developers and it will increase unnecessary methods in the applications.
For the above requirement sun Microsystems have provided a solution in the form of
Generic Servlet Abstract Class.
Second Approach to Design the Servlets:
In this approach we need to take a user defined class, which is extending from
Generic Servlet Abstract class.
Where Generic Servlet is an abstract class which was implemented directly servlet
interface.
public abstract GenericServlet implements Servlet,ServletConfig,Serializable
{ private transient ServletConfig config;
public void init(ServletConfig config)throws ServletException
{ this.config=config;
init();
}
public void init()
{
}
public abstract void Service(ServletRequest req,ServletResponse res)throws
SevletException,IOException;
publicServletConfig getServletConfig()
{ return config;
}
public String getServletInfo()
{ return null;
}
public void destroy()
{ config=null;
}
}

Servlets urtrainer.java@gmail.com 15
Comspark Info India Pvt Ltd. CSREDDY

public class Myservlet extends GenericServlet


{
public void Service(ServletRequest req,ServletResponse res)throws
SevletException,IOException
{
}
}
 From the above representation Generic Servlet is an Abstract class which was
implemented directly implemented Serializable interface that’s why we are able to
serialize directly Generic Servlet object.
 In predefined Generic Servlet Abstract class config reference variable is
transient that’s why it could not be participated in Generic Servlet object
serialization.
 In predefined Generic Servlet Abstract class init() is overloaded, the second init() is
for the sake of the developers customization in servlet initialization.
 In predefined Generic Servlet Abstract class still service() is an abstract method to
improve the sharability.
EX: The fallowing example demonstrates how to design a servlet by implementing
the ServletInterface and how to access from client machine?
Genericservletapp - WEB-INF  web.xml, classes  Myservlet.class
web.xml:
<web-app>
<servlet>
<servlet-name>gs</servlet-name>
<servlet-class>Myservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>gs</servlet-name>
<url-pattern>/generic</url-pattern>
</servlet-mapping>
</web-app>

Myservlet.java:
import javax.servlet.*;
import java.io.*;
public class Myservlet extends GenericServlet
{ public void service(ServletRequest req,ServletResponse res)throws
ServletException,IOException
{ res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html>");
out.println("<head>");
out.println("</head>");

Servlets urtrainer.java@gmail.com 16
Comspark Info India Pvt Ltd. CSREDDY

out.println("<body bgcolor=lightyellow>");
out.println("<h1>");
out.println("<br><br><hr>");
out.println("Hellow.......... Generic Servlet");
out.println("</h1></body></html>");
}
}
Modifications to first & second approach of designing:
In first approach of designing the servlet container will execute only one init() as
part of the servlet initialization.
But in Generic Servlet flow of execution container will execute two init() as part of
the servlet initialization.

Third Approach to Design the Servlets:


12) What are the differences between GenericServlet and HttpServlet?
> GenericServlet is protocol independent i.e. GenericServlet able to process any kind of
protocol request including Http.
HttpServlet is Http protocol dependent i.e. HttpServlet able to process only Http
Protocol Request.
> GenericServlet will not provide any option for the developers to specify different types
of request at client machine.
HttpServlet will provide an option for the developers to specify different types of
requests at client machine.
> Due to the above reason GenericServlet is not compatible with the protocol but
HttpServlet is very much compatible with the Http Protocol.
Note:
In case of GenericServlet if you specify get request or post request... at client machine the
GenericServlet will treat that request as a normal request and in the normal way
GenericServlet will process that request by executing service().
In case of HttpServlet if we specify Get Request, Post Request... then HttpServlet will
consider that request types and provide a separate execution process like doGet(),doPost()
… respectively.
> In case of GenericServlet as part of the request processing container will execute only one
service method but incase of HttpServlet to process a request container will execute
service(ServletRequest req,ServletResponse res) from where container call the
service(HttpServletRequest req,HttpServletResponse res) and from where container
will call doXXX() depends on the request type.
web.xml:
<web-app>
<servlet>
<servlet-name>ms</servlet-name>
<servlet-class>Myservlet</servlet-class>
</servlet>

Servlets urtrainer.java@gmail.com 17
Comspark Info India Pvt Ltd. CSREDDY

<servlet-mapping>
<servlet-name>ms</servlet-name>
<url-pattern>/http</url-pattern>
</servlet-mapping>
</web-app>

Myservlet.java:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Myservlet extends HttpServlet
{
public void service(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
PrintWriter out=res.getWriter();
java.util.Date now=new java.util.Date();
out.println("Hello Http Servlet");
out.println("Current Date and Time is :"+now);
}
}
Servlet Life Cycle:
When we send a request to the particular servlet then container will perform the
fallowing servlet life cycle mechanisms.

Servlet Loading Container c=Class.forName (myservlet);

Servlet Instantiation c.newInstance ();

Servlet Initialization init ();

Request Processing service ();

Servlet Deinstantiation destroy ();

From the above representation while processing one request if you send many more
number of request then servlet container should not perform servlet loading, servlet

Servlets urtrainer.java@gmail.com 18
Comspark Info India Pvt Ltd. CSREDDY

instantiation, servlet initialization, for the later request directly servlet container will bring
them to the request processing phase.
From the above representation servlets by default able to handle multiple number of
requests at a time i.e. allowing multiple number of threads at a time without having any
side effects. That’s why servlets are by default thread safe.

Load on startup tag:


As part of the web applications in general container will perform servlet loading,
servlet instantiation, and servlet initialization when it receives a request from client machine
after starting the server.
As per the application requirements to improve the performance of the web
application we need to make servlet container to perform servlet loading, servlet
instantiation, and servlet initialization at the time of startup the server.
To achieve the above requirement we should use the fallowing tag in web.xml file.
<web-app>
<servlet>
-----
-----
<load-on-startup> 1 (priority value) </load-on-startup>
</servlet>
----
----
<web-app>
If more than one servlet is having load on startup tag with different values then the servlet
which is having less priority value should have more priority i.e. this servlet could perform
loading, instantiation, initialization in earlier stages at the time of startup the server, which
servlet is having highest priority value then that servlet should have least priority i.e. this
servlet should be perform servlet loading, servlet instantiation, initialization in the later
stages at the time of startup the server.
If more than one servlet having same load on startup value then which servlet
should have highest priority is depending on that container implementation.

Form Design:

In the web application if we want to send any input data from client to server for a
particular server we should require user interface in the form of forms at client machine.
As part of the web application we require to specify different request types at client
machine apart from the default request as per the application requirement.
To specify a particular request type at client machine we should require a user
interface in the form of forms at client machine.
The entire web application quality depends on the fallowing 2 factors in general.
 Less Response Time

Servlets urtrainer.java@gmail.com 19
Comspark Info India Pvt Ltd. CSREDDY

 Very good look and feel of design part


To improve look and feel of the web application we should require very good user
interface in the form of forms at client machine.
In general in the web application if we want to design user interface then
we may use the technologies like AWT, Swings, Html, Jsp, Velocity, Free
markers….
In general we will use Html as a scripting technology to design user forms.

In the web application we are able to design user forms in the fallowing two
ways.
 Form Generation At Deployment
 Form Generation At Request Processing Time.
At the time of designing the web application if we design any html page and if we
keep that under application folder then it is called as “Static Form Generation”.
If we specify the complete html logic inside a servlet and generating form by
executing a particular servlet is called as “Dynamic Form Generation”.
If we specify any input data at client machine in user form then when we submit user
form to the server then client specified input data will stored on the request object in the
form of name value pairs through the protocols request format.
If we want to get the value of particular name value parameter from request object,
we will use the fallowing method from request object.
public String getParameter(String name);
To get all the names of the name value parameters on request object we will use the
fallowing method.
public Enumeration getParameterNames();

13) What is the difference between Parameters and Attributes?

Parameter is a name value pair which could be stored on to the request object at the
time of creation.
Attribute is a name value pair which could be stored on to the request object after
the request object creation, not at the time of creation.
Parameter will specify static inclusion of the data where attribute will specify dynamic
inclusion of the data.
To specify an Attribute into the request object we will use the following method.
public void setAttribute(String name,Objectvalue);
To get the value of particular attribute from request object we will use the fallowing
method.
public Object getAttribute(String name);
To get all the names of the attributes from request object we will use the following
method.
public Enumeration getAttributeNames();

Servlets urtrainer.java@gmail.com 20
Comspark Info India Pvt Ltd. CSREDDY

To get multiple values which are associated with a single name in the request object
we will use the fallowing.
Public String [] getParameterValues(String name);

EX: The fallowing example demonstrates how to design a form at deployment and
how to send input data from this form.
Formapp -> form.html, WEB-INF -> web.xml, classes -> Myservlet.class

Form.html
<html><head><center><b>
<font color="red" size="5">User Details
</font></b></center></head>
<body bgcolor="lightyellow">
<h2>
<form method="POST" action="/formapp1/form">
User Name <input type="text" name="uname"/><br><br>
UserPwd <input type="password" name="upwd"/><br><br>
UserQualification <input type="checkbox" name="bsc" value="BSC"/>Bsc
<input type="checkbox" name="mca" value="MCA"/>Mca
<input type="checkbox" name="mtech" value="MTECH"/>Mtech<br><br>
UserGender <input type="Radio" name="ugen" value="MALE"/>
<input type="Radio" name="ugen" value="FEMALE"/><br><br>
UserLocation<select name="uloc" size="1" maultiple>
<option value="hyderabad">Hyderabad</option>
<option value="banglore">Banglore</option>
<option value="pune">Pune</option>
</select><br><br>
usercoments<textarea name="comments" row="5" cols="10">
</textarea><br><br>
<input type="Submit" value="submit"/>
<input type="Reset" value="reset"/>
</form></h2></body></html>

web.xml:
<web-app>
<servlet>
<servlet-name>f</servlet-name>

Servlets urtrainer.java@gmail.com 21
Comspark Info India Pvt Ltd. CSREDDY

<servlet-class>Myservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>f</servlet-name>
<url-pattern>/form</url-pattern>
</servlet-mapping>
</web-app>
Myservlet.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Myservlet extends HttpServlet
{ protected void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{ res.setContentType("text/html");
PrintWriter out=res.getWriter();
String uname=req.getParameter("uname");
String upwd=req.getParameter("upwd");
String bsc=req.getParameter("bsc");
String mca=req.getParameter("mca");
String mtech=req.getParameter("mtech");
String ugen=req.getParameter("ugen");
String []uloc=req.getParameter("uloc");
String comment=req.getParameter("comment");
out.println("<html>");
out.println("<head><center><b><font color="red" size="6">");
out.println("User Details");
out.println("<br><br><hr>");
out.println("<body bgcolor="lightyellow">");
out.println("<h2>");
out.println("User Name.......... "+uname);
out.println("<br><br>");
out.println("User Qualification<br>");
if(bsc!=null)
out.println(bsc+"<br>");
if(mca!=null)
out.println(mca+"<br>");
if(mtech!=null)
out.println(mtech+"<br>");
out.println("<br>");
out.println("User Gender"+ugen);

Servlets urtrainer.java@gmail.com 22
Comspark Info India Pvt Ltd. CSREDDY

out.println("<br><br>");
out.println("User Locations");
out.println("<br>");
for(int i=0;i<uloc.length;i++)
{ out.println(uloc[i]+"<br>");
}
out.println("<h2></body></html>");
} }
EX: The fallowing example demonstrate how to design a form by executing a
particular servlet (Dynamic form generation) and how to send a request from the
dynamically generated form.

web.xml
<web-app>
<servlet>
<servlet-name>f</servlet-name>
<servlet-class>Myservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>f</servlet-name>
<url-pattern>/form</url-pattern>
</servlet-mapping>
</web-app>
Myservlet.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Myservlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<html><head><center><b><font size='6' color='red'>");
out.println("Employee Details");
out.println("</font></b></center></head>");
out.println("<hr><br><br><h2>");
out.println("<body bgcolor='cyan'>");
out.println("<form method="POST" action='/formapp2/form'>");
out.println("Name <input type="text" name='ename'>");
out.println("<br><br>");
out.println("Age <input type="text" name='eage'>");

Servlets urtrainer.java@gmail.com 23
Comspark Info India Pvt Ltd. CSREDDY

out.println("<br><br>");
out.println("Qualification <input type="text" name='equal'>");
out.println("<br><br>");
out.println("Email <input type="text" name='email'>");
out.println("<br><br>");
out.println("<input type="submit" value='DISPLAY'>");
out.println("<form></body></h2></html>");
}
public void doPost(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String ename=req.getParameter("ename");
String eage=req.getParameter("eage");
String equal=req.getParameter("equal");
String email=req.getParameter("email");
out.println("<body bgcolor='pink'>");
out.println("<h2>");
out.println("Employee Name:"+ename);
out.println("<br><br>");
out.println("Employee Age:"+eage);
out.println("<br><br>");
out.println("Employee Qualification:"+equal);
out.println("<br><br>");
out.println("Email ID:"+email);
out.println("</h2></body>");
}
}

Servlet Config:
Servlet Config is an object which can be used to maintain all the configuration details
of a particular servlet, where that configuration details are like logical name of the servlet,
initialization parameters and reference of Servlet Context Object.
Servlet Config object will be created by the container just after the servlet
instantiation and just before calling init() as part of servlet initialization.
Servlet Config object will be destroyed by the container just before the servlet
Deinstantiation. Due to the above reasons the life of the servlet config object is the life of
servlet.
Servlet Config is an object, which will provide the complete view of a single servlet.
I.e. with respect to the particular servlet an individual servlet config object will be created.

Servlets urtrainer.java@gmail.com 24
Comspark Info India Pvt Ltd. CSREDDY

If we specify any data in Servlet Config object then that data could be shared to
respective servlet only. Due to this reason the scope of the Servlet Config object is
particular servlet only.

 Logical name of the servlet is a name specified along with servlet name tag in
web.xml file. To get the particular servlet we will use the fallowing method from
servlet config object. public String getServletName();

 To get the reference of the Servlet Config object we will use the fallowing method
from servlet interface. public ServletConfig getServletConfig();

 If we want to specify initialization parameters on to the Servlet Config object first we


need to specify them in web.xml file as part of the particular servlet configuration
i.e... Under servlet tag for this we will use fallowing tags in web.xml file.
<web-app>
<servlet>
<init-param>
<param-name>name</param-name>
<param-value>value</param-value>
</init-param>
------
----
</servlet>
----
----
</web-app>
When we send a request to a particular servlet from client machine then container
will go for web.xml file, where container will check whether the servlet is having any
initialization parameters or not, if we have initialization parameters then container will read
them and stored on to the ServletConfig Object at the time of creation.
To get the value of a particular initialization parameter from ServletConfig Object
then we will use the fallowing method.
public String getInitParameter(String name);
To get the names of the initialization parameters from ServletConfig Object we will
use the fallowing method.
public Enumeration getInitParameterNames();
EX: The fallowing example demonstrates how to specify initialization parameters
for a servlet and how to get them from ServletConfig Object?
web.xml
<web-app>
<servlet>
<init-param>
<param-name>a</param-name>
<param-value>abc</param-value>
</init-param>
<init-param>

Servlets urtrainer.java@gmail.com 25
Comspark Info India Pvt Ltd. CSREDDY

<param-name>b</param-name>
<param-value>bcd</param-value>
</init-param>
<servlet-name>ms</servlet-name>
<servlet-class>Myservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ms</servlet-name>
<url-pattern>/config</url-pattern>
</servlet-mapping> </web-app>
Myservlet.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Myservlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{ res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletConfig config=getServletConfig();
out.println("<h1>");
out.println("<a--->"+config.getInitParameter("a"));
out.println("<b--->"+config.getInitParameter("b"));
out.println("<br><br>");
java.util.Enumeration e=config.getInitParameterNames();
while(e.hasMoreElements)
{ out.println(e.nextElement());
out.println("<br><br>");
}
out.println("Logical Name"+config.getServletName();
out.println("</h1>");
}
}
14) What is the difference between ServletConfig and ServletContext Objects?
> ServletConfig is an object, which will provide Configuration details of a particular
servlet like logical name of the servlet, initialization parameters..
ServletContext is an object, which will provide the context details of a particular
web application, like logical name of the web application and context parameters of the web
application.

 ServletConfig is an object, which will provide the complete view of a single


servlet. ServletContext is an object, which will provide the complete view of a
single web application.

Servlets urtrainer.java@gmail.com 26
Comspark Info India Pvt Ltd. CSREDDY

 Servlet Config object will be created by the container just after the servlet
instantiation and just before calling init() as part of servlet initialization.
ServletContext is an object will be created by the container the movement when
we start up the server.

 Servlet Config object will be destroyed by the container just before the servlet
Deinstantiation. Due to the above reasons the scope of the servlet config object is
the scope of the particular servlet only. ServletContext Object will be destroyed by
the container the movement when we shut down server. Due to the above reasons
the scope of the ServletContext Object is the scope of particular web application.

 ServletConfig Object will provide less sharability i.e. if we specify any data onto
the ServletConfig Object then it could be shared to a particular servlet.
ServletContext Object will provide more sharability i.e. if we specify any data onto
the ServletContext Object then that data could be shared to all the number of
resources which are available at the particular web application.

 ServletConfig Object will allow only parameters data i.e. static inclusion of the
data. ServletContext Object will allow both parameters data and dynamic inclusion
of the data.

 ServletConfig Object will be created by the container when it receives a request


from client machine except in load-on-stratup case. ServletContext Object will be
created by the container with or without receiving request from client machine.

To get the reference of the ServletContext Object we will use the fallowing method
from ServletConfig Object or from ServletContext Object.
public ServletContext getServletContext();
To specify logical name for the web application we will use the fallowing tag in
web.xml file.
<web-app>
<display-name>name</display-name>
-----
----
</web-app>
To get the logical name of the web application we will use the fallowing method from
ServletContext Object.
public String getServletContextName();
if we want to specify context parameters on to the ServletContext Object first we
need to define them in the web.xml file, for this we will use the fallowing xml tags in
web.xml file.
<web-app>
<context-param>
<param-name>name</param-name>
<param-value>value</param-value>

Servlets urtrainer.java@gmail.com 27
Comspark Info India Pvt Ltd. CSREDDY

</context-param>
------
</web-app>
When we start the server, automatically container will recognize all the web
applications which were deployed. As part of this container will recognize read and pass the
respective web.xml files.
At the time of recognizing the web.xml file container will read the specified Context
Parameters in the respective web.xml file and store them in the respective servlet Context
Object at the time of creation.
To get the value of a particular Context Parameter we will use the fallowing method
from ServletContext Object.
public String getInitParameter(String name);
To get the all the names of the context parameters from servlet context object we
will use the fallowing method.
public Enumeration getInitParameterNames();
To set an attribute on to the ServletContext Object we will use the fallowing method.
public void setAttribute(String name, Object value);
To get the value of a particular ContextAttribute from servlet Context object we wii
use the fallowing.
public Object getAttribute(String name);
To get all the names of Context Attributes from ServletContext Object we will use the
fallowing method.
public Enumeration getAttributeNames();
15) What is meant by foreign context?
It is a ServletContext Object of another web application being executed at the same
server.
To get the foreign Context Object reference we will use the fallowing method.
public ServletContext getContext(String path);
Almost all the servers are not supporting foreign Context Object as per the security
concerns in this case getContext() will return null as a value.
Ex: Context parameters program?
web.xml
<web-app>
<display-name>mycontextapp</display-name>
<context-param>
<param-name>a</param-name>
<param-value>abc</param-value>
</context-param>
<context-param>
<param-name>b</param-name>

Servlets urtrainer.java@gmail.com 28
Comspark Info India Pvt Ltd. CSREDDY

<param-value>bcd</param-value>
</context-param>
<servlet>
<servlet-name>ms</servlet-name>
<servlet-class>Myservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ms</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>
Myservlet.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Myservlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletConfig config=getServletConfig();
ServletContext context=getServletContext();
String lname=Context.getServletContextName();
out.println("<h1>");
out.println("Logical name:"+lname);
out.println("<br><br>");
out.println("a---->"+context.getInitParameter("a"));
out.println("b---->"+context.getInitParameter("b"));
out.println("<br><br>");
java.util.Enumeration e=context.getInitParameterNames();
while(e.hasMoreElements)
{
out.println(e.nextElement());
out.println("<br><br>");
}
context.setAttribute("1","123");
context.setAttribute("2","234");
out.println("1--->"+context.getAttribute("1"));
out.println("<br><br>");
out.println("2---->"+context.getAttribute("2"));
out.println("<br><br>");

Servlets urtrainer.java@gmail.com 29
Comspark Info India Pvt Ltd. CSREDDY

e=context.getAttributeNames();
while(e.hasMoreElements)
{
out.println(e.nextElement());
out.println("<br><br>");
}
out.println("ForeignContext..."+context.getContext("/configapp"));
out.println("</h1>");
}
}

Servlet Communication:
As part of the web applications design it is not at all suggestible to provide the
complete application logic with in a single servlet. It is suggestible to distribute the web
application logic over many more number of web resources.
Once if you distribute web application logic over many more number of web
resources then to execute the web application we should go for providing the
communication between web resources called as Servlet Communication.
Servlet Communication can be divided into the fallowing two ways.
Servlet Communication

Browser – Servlet Communication Web – Component Communication

 Sending Normal Request Normal Response Include Forward


 Sending Error Messages
 Request Redirection
Request Redirection by Using Hyperlinks
Request Redirection by Setting Response Header
Request Redirection by using Send Redirect ()

 As part of the client server architecture in general client will send request to a
particular servlet, servlet could be executed and generate dynamic response to client
machine. This is best suitable for Browser to Servlet Communication.
 Sending Error Messages:
In general in web applications design servlets needs to generate some error
messages due to client side mistakes / server side mistakes. This is possible with the
Browser to Servlet Communication only.
As per the application requirements if you want to send any error messages in a
standardized pattern from a servlet to the browser then we should use the fallowing
method from servlet Response Object.
public void sendError(int sc, String desc);

Servlets urtrainer.java@gmail.com 30
Comspark Info India Pvt Ltd. CSREDDY

Where Status code should be 5xx


EX: The fallowing application demonstrates how to generate error messages to the
client in a standardized pattern?
Senderrorapp - form.html, WEB-INF - web.xml, classes - ErrorServlet.class
<web-app>
<servlet>
<servlet-name>e</servlet-name>
<servlet-class>Errorservlet</servlet-class></servlet>
<servlet-mapping>
<servlet-name>e</servlet-name>
<url-pattern>/error</url-pattern>
</servlet-mapping></web-app>
Form.html:
<html>
<head><center><b><font size="6" color="red">
ABC Fashoin Show
</font></b></center></head><br><br><br>
<body bgcolor="lightyellow"><h2>
<form method="get" action="/senderrorapp/error">
Name<input type="text" name="uname" /><br><br>
Age<input type="text" name="uage" /><br><br>
<input type="submit" value="Register" />
</form></h2></body></html>

Errorservlet.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Errorservlet extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
String uname=req.getParameter("uname");
int uage=Integer.parseInt(req.getParameter("uage"));
if(uage<18)
{
res.sendError(504,"Sorry U R Not Eligible for this fashoin show");
}
else
{

Servlets urtrainer.java@gmail.com 31
Comspark Info India Pvt Ltd. CSREDDY

out.println("<body bgcolor="pink">");
out.println("<h1>");
out.println("<br><br><br>");
out.println("U R Name:"+uname);
out.println("<br><br>");
out.println("U R Age"+uage);
out.println("U R Registration ID :12345");
out.println("</h1></body>");
}
}
}
Request Redirection:
The process of redirecting a request from one web application to another web
application is called as request re direction. We are able to achieve Request Redirection in
the fallowing three ways.
1) Request Redirection by Using Hyperlinks
2) Request Redirection by Setting Response Header
3) Request Redirection by using Send Redirect () Mechanism
Request Redirection by Using Hyperlinks:
In this approach when we send a request to OLD Web Application client able to
receive a response with a Hyperlink. Customer may click on the Hyperlink automatically a
new request will be send to NEW Web Application. At final client able to receive the required
response from the NEW Web Application.
Hutchapp  WEB-INF  web.xml, classes  Hutch.class
Vodaphoneapp  welcome.html, WEB-INF  classes
Web.xml:
<web-app>
<servlet>
<servlet-name>h</servlet-name>
<servlet-class>Hutch</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>h</servlet-name>
<url-pattern>/hutch</url-pattern>
</servlet-mapping>
</web-app>
Hutch.java:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class Hutch extends HttpServlet
{

Servlets urtrainer.java@gmail.com 32
Comspark Info India Pvt Ltd. CSREDDY

public void doGet(HttpServletRequest req,HttpServletResponse res)throws


ServletException,IOException
{ res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println("<body bgcolor="pink">");
out.println("<h2>");
out.println("<br><br><hr>");
out.println("To get the Services of HUtch Click Here");
out.println("</h2><h1>");
out.println
("<a href="/vodaphoneapp/welcome.html">cc@vodaphone.com</a>");
out.println("</h1></body>"); }}
welcome.html
<html>
<head><h1><center>
Welcome to Vodaphone World
</center></h1>
</head></html>

Drawback:
This approach will provide extra risk by providing hyperlinks to the customers, to click on
the hyperlinks. In business point of view this approach is not at all suggestible that’s why
we should go for an alternative.
Request Redirection by Setting ResponseHeaders:
In this approach when we send a request to OLD Web Application then it will set the
location of the New Web Application as a response header in the response format with the
respective status code.
When client receive the response format client will get new web application URL as a
value of Response Header Location and keep it on its address bar, as per this client browser
will send new request to the new web application automatically without having customer
interaction.
To set new web application URL as a response header first we need to set the
respective status code to the response format, for this we will use the fallowing method.
public void setStatus(int sc);
Where status code should be either
HttpServletResponse.SC_MOVED_TEMPORARLY or
HttpServletResponse.SC_MOVED_PERMANANTLY
To set new web application URL as a response header we will use the fallowing
method from HttpServletResponse Object.
public void setHeader(String name, String url);
Where name should be location.
Ex:
res.setStatus (HttpServletResponse.SC_MOVED_PERMANANTLY);
res.setHeader(“Location”, http://localhost:8080/vodaphoneapp/welcome.html);

Servlets urtrainer.java@gmail.com 33
Comspark Info India Pvt Ltd. CSREDDY

Drawback:
If you want to perform request redirection with this approach every time we should
remember status codes, which is difficult for the developers that’s why we should go for an
alternative.
RequetRedirection by using sendRedirect ()
In this approach to perform Request Redirection we will use the fallowing method
from HttpServletResponse Object.
public void sendRedirect (String url);
res.sendRedirect (“http://localhost:8080/vodaphoneapp/welcome.html);

Web Component Communication:

The process of providing communication between web resources available at server


machine is called as Web Component Communication.

 Web Component Communication could be existed in between servlet to servlet,


servlet to Jsp, Jsp to Jsp, servlet to html, jsp to servlet, Jsp to Html.
 As part of the Web Applications we are able to provide the Web Component
Communication in the fallowing two ways.
 1) include mechanism
 2) forward mechanism
 To provide Web Component Communication in our web applications we should use
the fallowing two steps.
 1) Get Request Dispatched Object
 2) Call either include () or forward () method.

Request Dispatcher Object:


Request Dispatcher is an object, which will provide very good environment to
forward request from one web resource to another web resource or to include another web
resource response to the present web resource response.
To get the Request Dispatcher Object we will use the fallowing mechanisms.
1) From ServletContext Object we will use the fallowing two methods.
i) getRequestDispatcher ();
ii) getNamedDispatcher ();
2) From ServletRequest Object we will use the fallowing method.
i) getRequestDispatcher ();

16) What is the difference between getRequestDispatcher ()


and getNamedDispatcher () from ServletContext Object?

Servlets urtrainer.java@gmail.com 34
Comspark Info India Pvt Ltd. CSREDDY

To get the Request Dispatcher Object we will use getRequestDispatcher () then


we must pass the locator of the target resource as a parameter.
In case of Servlets Locator is a URL pattern.
public RequestDispatcher getRequestDispatcher (String target);
To get the Request Dispatcher Object we will use getNamedDispatcher () then we
must pass Logical Name of the target resource.
In case of servlets logical name is a name specified along with servlet name tag in
web.xml file.
public RequestDispatcher getNamedDispatcher (String target);

17) What is the difference between getRequestDispatcher () from ServletRequest


Object and from ServletContext Object?
To get the Request Dispatcher Object we will use getRequestDispatcher ()
from ServletContext Object then we must pass only Relative path of the target resource.
To get the Request Dispatcher Object we will use getRequestDispatcher ()
from ServletRequest Object we must pass either Relative path or absolute path of the
target resource.
Note: The difference between Relative path and Absolute path is (/) forward slash i.e.
Relative path should prefix with (/) and absolute path should not.
2) After getting RequestDispatcher Object reference we should use either of the
fallowing methods to perform Web Component Communication.
public void include (ServletRequest req, ServletResponse res);
public void forward (ServletRequest req, ServletResponse res);
18) What is the difference between include () and forward () mechanisms?
In case of the include mechanism when we send a request to the first resource,
where container will execute some part of the first resource and generate some response on
to the response object, when container encounter include () then container will bypass the
flow of control to the target resource along with the same request and response objects
“without Refreshing “the response object.
By executing the target resource some more response to be added to the response
object, at the end of the target resource container will dispatch the same request and
response objects to the first resource along with the flow of control without dispatching
response to the client machine. At the end of the first resource container will dispatch the
final response to the client machine. Therefore incase of include mechanism client able to
receive all the resources responses which are included in the request processing.
In case of the forward mechanism when we send a request to the first resource
container will execute some part of first resource and generate response to the response
object, when container encounter forward method then container will dispatch the same
request and response object to the target resource along with the flow of control by
refreshing the response object i.e. by eliminating the previous response at
response object.

Servlets urtrainer.java@gmail.com 35
Comspark Info India Pvt Ltd. CSREDDY

By executing the target resource some response to be added to the response object,
at the end of the target resource container will dispatch the response to the client machine
directly without return to the first resource. Therefore incase of forward mechanism client
able to receive only the target resource response which was included in the request
processing.
19) What is meant by Servlet Chaining?
The process of including many numbers of servlets to process a single request either
by using include mechanism or by using forward mechanism.
20) What is the difference between forward mechanism and sendRedirect ()
mechanism?
Forward mechanism can be used to provide the communication between two web
resources which are available at the same server but sendRedirect() mechanism can be
used to provide the communication between two web resources which are available at the
same server or at different servers.
web.xml:
<web-app>
<servlet>
<servlet-name>l</servlet-name>
<servlet-class>logo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>l</servlet-name>
<url-pattern>/logo</url-pattern>
</servlet-mapping>
<servlet><servlet-name>h</servlet-name>
<servlet-class>home</servlet-class>
</servlet><servlet-mapping><servlet-name>h</servlet-name>
<url-pattern>/home</url-pattern></servlet-mapping>
</web-app>
home.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class home extends HttpServlet
{ public void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{
res.setContentType("text/html");
PrintWriter out=res.getWriter();
ServletConfig config=getServletConfig();
ServletContext context=config.getServletContext();
RequestDispatcher rd=context.getRequestDispatcher("/logo");
rd.include(req,res);

Servlets urtrainer.java@gmail.com 36
Comspark Info India Pvt Ltd. CSREDDY

out.println("<html>");
out.println("<body bgcolor='lightyellow'>");
out.println("<h2>");
out.println("Challa Software Solutions");
out.println("To get the details of this test click the bellow link");
out.println("<br><a
href='/includeapp/mocktestdetails.html'><h1>MockTest Details</h1></a>");
out.println("The First Prize for the topper is 5000");
out.println("</h2></body></html>");
rd=context.getRequestDispatcher("/footer.html");
rd.include(req,res);
}
}
logo.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class logo extends HttpServlet
{ public void doGet(HttpServletRequest req,HttpServletResponse res)throws
ServletException,IOException
{ res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.println(new Date());
out.println("<head><center><b><font color='red' size='5'>
Challa Software Solutions </font></b></center>
</head><br><br>");
}
}
mocktestdetails.html:
<html>
<head><center><h1><b>
<font size='15' color='red'>
Challa Software Solutions</font></b></h1></center>
</head><hr>
<body bgcolor="lightyellow">
<h1><u><b>Test Details
</b></u></h1>
<br><h2>Test type:SCJP
<br>Qualification: Any Graduation
<br>Requirements: Java Knowledge
<br>Entry Fee: Rs 100/-<br><br>

Servlets urtrainer.java@gmail.com 37
Comspark Info India Pvt Ltd. CSREDDY

<h2><b><u>Address</u></b></h2>
<h3>Block -203,204
<br>Cellar<br>Taj Banjara <br> Banjara Hills
<br> HYD-500038</h3><hr><center>copyright@csstechnologies.com
<body></html>

Footer.html:
<br><br>
<hr>
<h3><center>
copyright@csstechnologies.com
</center></h3>

Welcome Files:
Welcome file is a file which could be open for us when we specify up to application
name in URL, specified at the client browser.
To specify a file as a welcome file we should use the fallowing tags in web.xml file.
<web-app>
<welcome-file-list>
<welcome-file>file1</welcome-file>
<welcome-file>file2</welcome-file>
---
</welcome-file-list>
---
</web-app>
From the above tags representation it is possible to specify more than one welcome
file configuration in web.xml file.
From the web.xml file which welcome file could be executed is depending on the
module name which we specified in user URL at client machine.
Container will search for the respective welcome file in the respective module until it
encounter the respective welcome file as per the welcome files order specified in web.xml
file.

Servlets urtrainer.java@gmail.com 38
Comspark Info India Pvt Ltd. CSREDDY

Servlets urtrainer.java@gmail.com 39

You might also like