Sie sind auf Seite 1von 86

SERVLETS

64)What is a web application ?


Any computer application is said to be a web application if its services are accessible through web(internet service).
web application provides online services to users. Therefore ,they are also called as online application.
for eg.online banking application , online insurance application , online reservation etc.
Note:- web application is nothing but a dynamic website.
65)how is web application programming classified (in the context of a web application development) ?
1.Client side (customer side) programming
2.Server side programming (web server)
A piece of code that executed at browser side (infact , by the browser) is nothing but client side programming.
Client side programming is mostly meant for validating the user input.Input validation enforces the user to enter
completer and proper input into the web application.
To provide interaction to the end users we need th have server side programming.
Q.66)What are the web server side technologies ?(i.e we technologies) given by Sun Micro System
for java based web application development ?
1.SERVLET
2.JSP
Q.67)What is not a Servlet ?
Servlet is not a programming language unlike Java.
Servlet is not a software(product) to install into a computer system to develop web applications.
Q.68)What is a "Servlet" ?
Servlet is a Java based Web Technology.
It is a J2EE technology technology
Q.69)What is the purpose of servlet Technology ?
To implement Java Based web server side programming to make the webside dynamic.
i.e. Servlet technology is meant for developing Java based web applications.
Q.70)What is a Servlet ?
A servlet is a web server side Java program*.
A Servlet is a user defined Java class that inherits javax.servlet.Servlet interface.
javax.servlet.Servlet
^
Login Servlet
Q.71)What can a servlet do in a Java web application ?
A servlet being a server side java program can perform the following task.
1.)Capturing the user input
2.)Communicate with the database.
3.)processing of data
4.)Producing the response page
5.)Handling over the response page to the web server.
Q.72)What is the platform for java based web application ?
In the context of computer applications,platform means execution environment ( run time infrastructure).
Java web application is not a J2SE platform . therefore , J2SE platform alone is not sufficient for its running. we
need a J2SE platform.
Web application J2EE application
(web)application J2EE platform
Server (written in java)
JVM J2SE platform
Operating System Real machine
Q.73)What are the main element of application server web in the industry ?
Application server = web server + servlet container (servlet engine) + JSP container ( engine ) + .....
Q.74)What is a Servlet Container (engine) ?
A Servlet container is a specealized software module (of an application server) written in java according to servlet
Servlet Specification whose functionality is to execute user define Servlets.
Note :- As part of Servlet technology development, Sun Micro Systems has 2 thing
1.)API (servlet API)
2.)Specification (a set of rules)

API is for application developers to implement servlet programming and servlet specification
is for Servlet container vendor.
Q.75)How are web resources of a web application are classified ?
1.) Static web resources(passive resources(data))
2.) Dynamic web resources(active resource)
Note :- Every web resource has a URL. client must use this URL to get the resource or to get the service of the
resource.
HTML documents , image files , video and audio files are the examples of static resources.
which web resources provide interaction to the end-users, those are called as active or dynamic resources.
for eg. Servlet & JSP`s
In a Java based web application , Servlets JSP are also called as web components.
Q.76)what are the differences between static webpages and dynamic web pages ?
Note :- Both are developed using types text markup language. both are sent by web server to browser. Both are
executed and rendered(displayed) by browser.
Static page Dynamic page
1.It is a pre-created page 1.It is created on the fly only after receiving the client request based on user input
2.It is stored in the file system of the 2.not stored web server machine
3.No server programming required 3.Server side program creates it. to create it.
4.Its content remains static i.e. doesn`t 4.changes based on user input. change with user interaction/input
Q.77)What are the system requirements to develop and run Java Based Web Application ?
1.)Install JDK (J2SE platform) JVM
2.)Web Application server
for eg.Tomcat
Q.78)What is the life cycle of servlet ?
Servlet container control the life cycle of a Servlet
A Servlet (User define java class) has 4 life cycle phases.
1.instantiation phase
2.initialization phase
3.servicing phase
4.destruction phase
Q.79)What is the general structure of a simple servlet ?
public class MyServlet implement Servlet
{
public void init (ServletConfig config)
{
//resources allocation code
//for eg. database connection code
}//init
public void service(ServletRequest request , ServletResponse response)
{
//client request handling code ( 5 general duties)
}//service
public void destroy()
{
//resource releasing code
//for eg.closeing the database connection
}//destroy
}//MyServlet class(user define java class (web component))
Note :-init,service,destroy method are called as life cycle methods-whenever something happens in the life of a
servlet , servlet container calls these methods and hence the name.
Q.80)Explain about instantiation phase of a servlet ?
servlet container creating the object of a user defined servlet class is nothing but its instantiation phase.
wherever container receives client request for the first time fot the servlet , its creates the instance of the servlet. for
the same online service any number of thing request come afterwords , servlet container
doesn`t create Servlet instance i.e. only one servlet instance (per type) service any number of client requests.
In the life time of a servlet , instantiation happens only once.

servlet container makes a servlet singleton.


servlet instance exist until the application is unloaded i.e. servlet life time is that of the application.
Q.81)Explain about initialization phase of a servlet ?
=>Servlet Container calling init() method of a servlet is nothing but its initialization phase.
Initialization happens only once in the life time of a servlet i.e. Servlet Container call init() method on the servlet
instance only once.
During instantiation phase , servlet instance doesn`t get complete serviceness and therefore it can`t serve the client
request , Servlet Container creates ServletConfig object and calls init method by supplying its reference as
argument. once init method is completing xecuted , servlet acquires servletness completely and ready to serve the
client requests.
whatever resource required to the servlet to serve the client requests are supplied in init method .
for eg. database connection creation.
Q.82)Explain about servicing plase of servlet ?
ServletContainer calling service method of a servlet is nothing but its servicing phase.
Container create ServletRequest object and ServletResponse object and invoke service method by supplying their
references as arguments.
for each client request service method is called once.
within the service method , client request handling code is implemented .
request object is used to compare the user input. response object is used to produce the response page and hand over
to the web server.
Container is multi threaded for each client request , Container create one thread and in that thread request and
response object are created and service method is called thus , a single servlet instance can attend multiple
concurrent request.
Note :- Most of its life a servlet spends in servicing phase.
SC loading servlet class
\/
SC create the instance of the Servlet
\/
SC creating ServletConfig object
\/
SC calling init method
\/
-------->SC creating request & response object
/\ \/
/\ SC calling service method
/\ \/
/\ one
/\<------------------more
request
\/
\/ NO
Servlet waits for client request
Q.83)Explain about destruction phase of a Servlet ?
ServletContainer calling destroy() method of a servlet is nothing but its destruction phase.
is the Servlet --------------NO----->Servlet is not destroyed
Unloaded ?
\/
\/
YES
\/
\/
SC calls destroy() method
\/
\/
SC marks the Servlet instance for

Garbage collector
When the Container receives web application unloading instruction from the administrator , Container calls
destroy() method of the servlet and then marks the servlet instance for garbage collection.
Container calls destroy() method only once in the life time of a servlet.
Destruction phase is given in the life of a servlet to allow the developer to release the resources given to the servlet.
for eg. Closing database the connection.
Q.84)what are the system requirements to develop and run java web application ?
1.install JDK
2.Install web application server for eg. Tomcat 7.
Q.85)How to develop a Java Web Application ?
Java web application development involves the following steps
Step 1. Creating a servlet hierarchy of Directories
Step 2. Developing web resources (both static and dynamic) & helps files of the application.
Step 3. Developing deployment descriptor
Step 4. Configuring the application files.
*Directory Structure :Create a root folder with any name.
within the root folder create a sub folder with name "WEB-INF"
within the WEB-INF folder create "classes" and "lib" folder.
src folder for source file(when develop the application) is optional
BankingApplication
|
|
-------------->WEB-INF
|
|
----------->classes
|
------------>lib
|
----------->src(optional)
Note :- To have a Standard format for a Java web application and also to have web application server vendor
independency , Sun Micro System designed this directory structure.
root folder name generally become the web application name.
*Web resources and helps file development :Accessibility to application requirements we need to develop HTML documents , image files , video files(static
resources) , Servlet and JSP(dynamic resources).
some helper files like css files and other files are also to be developed.
Note:- Web designer generally deal with static resource development and J2EE professionals deal with dynamic web
resources (web components) developments.
*Developing deployment descriptor :Deployment descriptor is an XML document whose standard name is "web.xml".
Application developers describes the web resources details and their Configuration information to the web
application server (and there by to Servlet & JSP Container) using this file.
web application server reads this file at the time of web application development (loading) and knows about the
application. only one "web.xml" per application.
Some of the typing actions performed in web.xml are
1.registering the Servlet.
2.Configuring the HomePage.
3.Configuring the error page.
4.Configuring the filters.
5.Configuring the listeners.
6.giving URL to servlets.
7.specifying the session timeout period.
8.registering the JSP tag libraries.
9.registering the JSP`s etc.

*Configuring the application files :placing the application into the appropriate folders of the Structure of directories is nothing but
Configuring the application files.
HTML documents , image files or JSP are to be placed in the root folder.
"webxml" should be placed into WEB-INF folder.
class files of the application for eg. servlet class files are to be copie "classes" folder.
jar files of the application are to bbe copied into "lib" folder
for eg. OJDBC14.jar.
root folder
|
|--------->*.HTML
|---------->*.JSP
|----------->image files
|----------->CSS files
|------------>JS files
|
|---------->WEB-INF
|
|--------->web.xml
|----------> classes
||
| |-------> *.class
|
|----------->lib
||
| |-------->*.jar
|
|-------------->src
|
|-------->*.java
Q.86) Develop a Java web application in which , a servlet display "Hello World" web page to the user upon
request.
Structure
Hello World
|--------->WEB-INF
|--------->classes
|---------->lib
|---------->src
Step 2. developing the web resources
In this application we need to have Only one web resource (active) i.e. servlet.
//HellowWorldServler.java
import javax.Servlet.*;
public class HelloWorldServlet implements servlet
{
public void init(ServletConfig config){}//init
public void destroy(){}//destoy
public ServletConfig getServletConfig(){return null;}
public void service(ServletRequest requst, ServletResponse response)throws IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<BODY bgcolor = yellow>");
out.println("<H1>Hello Web World </H1>");
out.println("<\BODY>");
out.println("<\HTML>");

ou.close();
}//service
}//HelloWorldServlet
Note :- before compiling this Servlet , we need to place Servlet-api.jar file in CLASSPATH
for eg. Set Classpath = F:\Apache Software Foundation\Tomcat 6.0\lib\Servlet-api.jar;.;
Step 3 :- Deployment descriptor development
web.xml
<web-app>
<servlet>
<servlet-name>one</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>one</servlet-name>
<url-pattern>.\hello</url-pattern>
</servlet-mapping>
</web-app>
Step 4:- Configuring the application files
Q.87) How to develop the above "HelloWorldApplication" ?
we need to deploy the application and then send the request from the browser with servlet URL.
Installing/Loading the web application into web application server so that its services are available to web client is
nothing but deployment of a web application.
In order to deploy a web application into Tomcat server , copy the root folder (along with files) into
"webapp" folder of tomcat start the( Tomcat )Server.
Into the browser`s URL box specify the following URL
http://localhost:8888/HelloWorldApplication/hello
how where what
Q.88)How mames does a Servlet have in a webappication ?
1.registration name(alias name)//one
2.classname //
3.public URL name //http://localhost:8080/HelloWorldApplication
Q.89)What is the purpose of <servlet> tag in web.xml ?
To register a servlet with ServletContainer
we use <Servlet> tag.
for each servlet we use <Servlet> tag once for registration.
Q.90) What is the purpose of <Servlet-Mapping> tag in web.xml ?
To give public URL name to the Servlet , we use this tag. from the browser , with this name only request should
come to the servlet.
Q.91)What is the limitation in "HelloWorldServlet" of "helloworldapplication" ?
According to the application requirement , only dervice method is sufficient but we are forced to implement other 4
methods also as the Servlet is directly inherits from javax.servlet.Servlet interface. this coding inconvinient can be
overcome if the user defined servlet class inherits from javax.servlet.GenericServlet.
Generic Servlet is an abstract class. in this class, all method of servlet interface are implemented but service method
not. if user defined servlet extends GenericServlet , only service method implementation is mandatory and other
methods if and if required can be implemented.
javax.servlet.Servlet
^implements
^
javax.servlet.GenericServlet
^
^extends
other Servlet

Q.92)Develop a Java web application in which addition use-case is implemented


AdditionApplication
Number.html
WEB-INF
-web.xml
-classes
-AdditionServletApplication.class
-lib
-src
link : http://localhost:8080/AdditionApplication/Number.html
Number.html
_______________________________
| Number 1 : |________| |
||
| Number 2 : |________| |
| |----------------------->AdditionServletApplication
|||
| SUBMIT | |
|_______________________________| |
|
_______________________________ |
|||
|||
| The Sum is ____ |<-----------------------------||
||
|_______________________________|
web.xml
-------<web-app>
<servlet>
<servlet-name>two</servlet-name>//servlet name
<servlet-class>AdditionServletApplication</servlet-class>//web apps get powered from url-pattern it which .class
servlet file to be executed
</servlet>
<servlet-mapping>
<servlet-name>two</servlet-name>//servlet name
<url-pattern>/add</url-pattern>//this /add which mapped with other Servlet or html file where we wrote mapped line
like in html <form Action = ./add>
//means it mapped with http://localhost:8080:AdditionServletApplication old url + add so come to web.xml
//means after any action comes to web.xml this file from here <serlvet-class> which class file to be excuted
</servlet-mapping>
</web-app>
-------------------------------------------------------------------------------Number.html
----------<HTML>
<BODY BGCOLOR="GRAY">
<CENTER><H1>NUMBER ENTRY SCREEN </H1>
<FORM ACTION = "./add">//for action(after cliked submit) pointer comes to web.xml where same mapping
happens (./add) same in web.xml from there
//from there class execution mapping happen
NUMBER 1 : <INPUT TYPE = "text" NAME = "T1" >
NUMBER 2 : <INPUT TYPE = "text" NAME = "T2" >

<BR><BR>
<INPUT TYPE = "SUBMIT" VALUE = "ADD">
</FORM>
</CENTER>
</BODY>
</HTML>
Note:- "T1" is the name of the 1st text box.
technically it is called as request parameter name of 1st text box . similarly , "T2" is the requst parameter name of
second text box.
user entered value is called request paramater value. request parameter is a name ,value pair.
request parameter name = requst parameter value.
for eg.
T1 = 10
T2 = 20
"ACTION" attribute of <FORM> tag is used to specify the URL of the server side programs
that is going to process the from data.
AdditionServletApplication.java
--------------------------------//AdditionServletApplication.java
import javax.servlet.*;
import java.io.*;
import javax.servlet.GenericServlet;
public class AdditionServletApplication extends GenericServlet
{
public void service(ServletRequest request , ServletResponse response)throws IOException,ServletException
{
String a = request.getParameter("T1");//get parameters which are submitted by client on html page
String b = request.getParameter("T2");//get parameters which are submitted by client on html page
int n1 = Integer.parseInt(a);
int n2 = Integer.parseInt(b);
int sum = n1+n2;
response.setContentType("text/html");//send to client type of data = text and extention = html
PrintWriter out = response.getWriter();//out object used to send data to client by response object
out.println("<HTML>");
out.println("<BODY BGCOLOR=yellow>");
out.println("<H1>The sum is : "+sum+"</H1>");
out.println("</BODY>");
out.println("</HTML>");
out.close();
}//service
}//AdditionServletApplication
Q.93)How is a servlet executed ?
When browser sends a request to the web application server with servlet URL, web server provides the connection
to the browser and switch the control to the ServletContainer as the request is for dynamic resources i.e. Servlet.
ServletContainer identifies which Servlet to execute using <servlet-mapping> of web.xml. once it is identifies
the servlet i.e. servlet life cycle Starts.
Q.94)What is request dispatching ?
once servlet delegating the request processing to other Servlet is know as request Dispatching. Purpose of request
dispatching is , to implement inter-communication between servlets. whenever a servlet`s role is to process only a
part of the request, for remaining portion of the request processing it needs to communicate with other servlet of the
application.
Two steps are involve in the implementation of request Dispatching.
Step 1) Creating Request Dispatcher Object.
RequestDispatcher rd = request.getRequestDispatcher("other public URL / servlet name");
Step 2) Call forward() OR include() method on RequestDispatcher Object.
rd.forward(request,response); OR rd.include(request,response);

In forward() mechanism of request dispatching, one servlet gets the client request , does some portion of request
processing and remaining portion of the processing sake it switches the control to another servlet. that servlet
proccess the remaining portion of the request and that servlet only responsible to produce the response for the
client.
________________ forward
|--------------->servlet 1 --------->servlet 2
||
client |<-------------------------------------------|
________________|
In include mechanism of request dispatching , once servlet gets client request , doesn`t some portion of the request
processing and remaining portion of processing sake it switches the control to another serlet, that servlet processes
the remaining portion of the request and 1st servlet only responsible to build the response for the client.
________________ include
|---------------> --------------->
| servlet 1 servlet 2
client |<---------------- <---------------________________|
Q.95)Develop a java web application in which , end-users enter the basic salary into the web form
and gets the net salary (take some ) salary details ?
forwardapplication
basic.html
WEB-INF
src
GrossSalary.java
NetSalary.java
classes
GrossSalary.class
NetSalary.class
lib
http://localhost:8080/forwardapplication
-------------------------------------------------------------------------web.xml
-------------------<web-app>
<servlet>
<servlet-name>three</servlet-name>
<servlet-class>GrossServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>four</servlet-name>
<servlet-class>NetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>three</servlet-name>
<url-pattern>/gross</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>four</servlet-name>
<url-pattern>/net</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>basic.html</welcome-file>
</welcome-file-list>
</web-app>
-----------------------------------------------------------------------

Note:- In this Java web application configuration file , basic.html is made as the home page.
basic.html
------------------------<HTML>
<BODY BGCOLOR="GRAY">
<CENTER><H1>SALARY DETAILS</H1>
<FORM ACTION = "./gross">
BESIC SALARY : <INPUT TYPE = "text" NAME = "basic" >
<BR><BR>
<INPUT TYPE = "SUBMIT" VALUE = "ADD">
</FORM>
</CENTER>
</BODY>
</HTML>
--------------------------------------------------------------------------------------------------GrossServlet.java
------------------------------import javax.servlet.*;
import java.io.*;
public class GrossServlet extends GenericServlet
{
public void service(ServletRequest request , ServletResponse response)throws IOException,ServletException
{
float basic = Float.parseFloat(request.getParameter("basic"));//get basic salary and save it in basic(float)
float da = basic*0.6f;
float hra = basic*0.1f;
float gross = basic+da+hra;
request.setAttribute("gr",gross);
RequestDispatcher rd = request.getRequestDispatcher("/net");
rd.forward(request,response);
}//service
}//class
------------------------------------------------------------------------------------------------------NetServlet.java
------------------------------import javax.servlet.*;
import java.io.*;
public class NetServlet extends GenericServlet
{
public void service(ServletRequest request , ServletResponse response)throws IOException,ServletException
{
float gross = (Float) request.getAttribute("gr");
float dedecutions = gross*0.06f;
float net = gross-dedecutions;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<BODY bgcolor = gray>");
out.println("<H1> Net salary is Rs. "+net+"</H1>");
out.println("</BODY>");
out.println("</HTML>");
out.close();
}//service
}//class
-------------------------------------------------------------------------------------------------------

Q.96)Develop a Java web application to implement the privious use-case with include mechanism of request
dispatcher ?
includeapplication
basic.html
WEB-INF
web.xml
src
GrossServlet.java
NetServlet.java
classes
GrossServlet.class
NetServlet.class
lib
http://localhost:8080/includeapplication/
-------------------------------------------------------------------------------------------------web.xml
------------------------<web-app>
<servlet>
<servlet-name>five</servlet-name>
<servlet-class>GrossServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>six</servlet-name>
<servlet-class>NetServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>five</servlet-name>
<url-pattern>/gross</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>six</servlet-name>
<url-pattern>/net</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>basic.html</welcome-file>
</welcome-file-list>
</web-app>
--------------------------------------------------------------------------------------------------basic.html
-------------------------<HTML>
<BODY bgcolor = "gray">
<H1>Salary Details</H1>
<FORM ACTION = "./gross">
Basic Salary : <INPUT TYPE ="TEXT" Name = "basic">
<BR><BR>
<INPUT TYPE ="SUBMIT" VALUE = "NetSalary">
</FORM>
</BODY>
</HTML>
----------------------------------------------------------------------------------------------------GrossServlet.java
--------------------------------import javax.servlet.*;
import java.io.*;

public class GrossServlet extends GenericServlet


{
public void service(ServletRequest request,ServletResponse response)throws IOException,ServletException
{
float basic = Float.parseFloat(request.getParameter("basic"));
float da = basic*0.06f;
float hra = basic*0.1f;
float gross = basic+da+hra;
request.setAttribute("gr",gross);
RequestDispatcher rd = request.getRequestDispatcher("/net");
rd.include(request,response);
float net =(Float) request.getAttribute("nt");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<BODY bgcolor ='gray'>");
out.println("<H1>Net Salary Rs. = "+net+"</H1>");
out.println("</BODY>");
out.println("</HTML>");
out.close();
}//service
}//class GrossServlet
-------------------------------------------------------------------------------------------------NetServlet.java
----------------------------import javax.servlet.*;
import java.io.*;
public class NetServlet extends GenericServlet
{
public void service(ServletRequest request , ServletResponse response)throws IOException,ServletException
{
float gross =(Float)request.getAttribute("gr");
float dedecutions = gross*0.06f;
float net = gross-dedecutions;
request.setAttribute("nt",net);
}//service
}//class NetSerlvet
----------------------------------------------------------------------------------------------------Q.97)How to store data among the servlets of java web server application ?
whenever web components of a java web application need to store data , we use "Scope" concept.
there are 3 scope in servlet
1.request scope
2.session scope
3.application scope
if a data object stored in request object , it is said to be in request scope.
if a data item is stored in HttpSession, it is said to be in Session scope.
it a data item is stored in ServletContext object , it is said to be in application scope.
There are 4 methods to deal with scoped data
1.setAttribute(String objectname,Object value);
2.Object getAttribute(String objectname);
3.removeAttribute(String objectname);
4.Enumaration getAttributeNames();
1.setAttribute(String objectname,Object value); :-it is used to store and update a value in the scope.
2.Object getAttribute(String objectname); :-is used to delete an item from the scope.
3.removeAttribute(String objectname); :- is used to retrieve data item from the scope.
4.Enumaration getAttributeNames(); :-is used to get all the names and item stored in the scope.

Q.98) Develop a java Web Application to store accounts details(accno,name,balance)


into the database ?
AccountOpeningApplication
--------------------------AccountOpeningApplication
OpenAccount.html
WEB-INF
web.xml
src
AccountOpeningServlet.java
classes
AccountOpeningServlet.class
lib
http://localhost:8080/AccountOpeningApplication
-------------------------------------------------------------------------------------web.xml
-------<web-app>
<servlet>
<servlet-name>seven</servlet-name>
<servlet-class>AccountOpeningServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>seven</servlet-name>
<url-pattern>/openaccount</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>OpenAccount.html</welcome-file>
</welcome-file-list>
</web-app>
OpenAccount.html
---------------<HTML>
<BODY bgcolor= "wheat">
<H1>Account Open Form </H1>
<FORM ACTION = "./openaccount">
Account No. :<INPUT TYPE = "text" NAME = "accno">
<BR>
<BR>
User Name :<INPUT TYPE = "text" NAME = "name">
<BR>
<BR>
User Balance:<INPUT TYPE = "text" NAME = "balance">
<BR>
<BR>
<BR>
<BR>
<INPUT TYPE = "submit" VALUE = "OpenAccount">
</FORM
</BODY>
</HTML>
Servlet Development
---------------------If at all a servlet is required to communicate with the database , that servlet become JDBC client even though it is a
server side program.
*** Connection creation and PreparedStatement creation has to be done in init() method.

*** closing the PreparedStatement and Connection is done in destroy() method.


we need to handle ClassNotFoundException and SQLException (using catch block) binding the 'in' parameter with
user input , Submitting the query and processing the Result(if any) is done in service method.
AccountOpeningServlet.java
---------------------------import javax.servlet.*;
import java.io.*;
import java.sql.*;
public class AccountOpeningServlet extends GenericServlet
{
Connection conn=null;
PreparedStatement ps=null;
public void init(ServletConfig config)//init() also works
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","SYSTEM","riddhi");
ps=conn.prepareStatement("insert into account values(?,?,?)");
}//try
catch(ClassNotFoundException e)
{
System.out.println("Line 18");
}
catch(SQLException e)
{
System.out.println("Line 22");
}
}//init
public void destroy()
{
try{
if(ps!=null)
ps.close();
if(conn!=null)
conn.close();
}
catch(SQLException e)
{
System.out.println("Line 39");
}
}//destroys
public void service(ServletRequest request,ServletResponse response)throws IOException,ServletException
{
int ano = Integer.parseInt(request.getParameter("accno"));
String name = request.getParameter("name");
float bal = Float.parseFloat(request.getParameter("balance"));
try{
ps.setInt(1,ano);
ps.setString(2,name);
ps.setFloat(3,bal);
ps.executeUpdate();//auto-commit enable mode in JDBC but not in Hibernate(auto-commit dosable mode)
}//try
catch(SQLException e)
{

System.out.println("Line 57");
}//catch
//servlet to html page
request.getRequestDispatcher("OpenAccount.html").include(request,response);
//RD rd=r.gRD("OA.html"); rd.include(request,response);
}//service
}//class AccountOpeningServlet
Q.99)What are init Parameter ?
Name , Value pairs of textual information supplied to a servlet during its initialization phase are called as
initialization parameters OR simply init param.
Q.100)How to supply init param to a servlet ?
1.) Through "web.xml"....................
for eg.
<servlet>
<servlet-name>eight</servlet-name>
<servlet-class>AccountOpeningServlet</servlet-class>
<init-param>
<param-name>user name </param-name>
<param-value>SYSTEM</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>riddhi</param-value>
</init-param>
</servlet>
In the above example , 2 init parameter are supplied to the servlet.
first(1st) init param name = username
first1st) init param value = SYSTEM
second(2nd) init param name = password
second(2nd) init param name = riddhi
Q.101)How to retrieve init parameter value in a servlet ?
ServletContainer encapsulats init parameters in ServletConfig Object.
By calling getInitParam() method of ServletConfig Object , we can retrieve the init param value in a servlet.
for eg.
String uname=config.getInitParameter("username");
String pwd = config.getInitParameter("password");
Q.102)What is the purpose of init parameters ?
To prevent hard coding of certain values in a servlet.
For eg:- database connection details.
without changing the source code of the servlet, at different times of deployment , we can supply different values.
Q.103)What is the limitation of GenericServlet ?
GenericServlet can`t provide HTTP specific services to user defined servlet.
for eg:- session tracking , cookie , URL rewriting etc.
In real java web applications ,user defined servlets never directly inherits from GenericServlet.
javax.servlet.http.HttoServlet is used to implement a real servlet
javax.servlet.Servlet interface
^
javax.servlet.GenericServlet abstract class
^
^
javax.servlet.http.HttpServlet abstract class
^
^
User define Servlet concrete class.

Q.104)What is the GeneralStructure of a real Servlet ?


import javax.servlet.*;
import javax.http.*;
import java.io.*;
public class MyServlet extends HttpServlet
{
public void init(ServletConfig Config)throws ServletException
{
//resource Allocation
}//init
public void destroy()
{
//resource releasing
}//destroy
public void doGet/doPost(HttpServletRequest request,HttpServletResponse response)throws
ServletException,IOException
{
//client request handling code
}//doGet/doPost ...dervicing code
}//class MyServlet
Note :- if client request is of Get type , servicing method will be doGet();
if client request is of Post type ,servicing method will be doPost();
Q.105)Modify HelloWorldServlet to make it HttpServlet ?
Structure
Hello World
|--------->WEB-INF
|--------->classes
|---------->lib
|---------->src
//HellowWorldServler.java
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
public class ModifiedHelloWorldServlet extends HttpServlet
{
//public String getServletInfo(){return "vitthal";}
//public void init(ServletConfig config){}//init
//public void destroy(){}//destroy
//public ServletConfig getServletConfig(){return null;}
public void doGet(HttpServletRequest requst, HttpServletResponse response)throws IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<BODY bgcolor = yellow>");
out.println("<H1>Modified Hello Web World </H1>");
out.println("</BODY>");
out.println("</HTML>");
out.close();
}//service
}//HelloWorldServlet
Q.44)Who calls doGet()/doPost() of a servlet ?
Servlet Container does not call doGet() or doPost() method , as these methods are do not belong to Servlet interface.
These are not the life cycle method of servlet.
HttpServlet Class has 2 service methods

1.)public service() method which is the life cycle method.


2.)protected service() method which is not life cycle method.
In public service method of HttpServlet 2 things are done
1.)converting ServletRequest into HttpServletRequest and ServletResponse into HttpSaervletResponse
2.)calling protected service method
In protected service() method , 2 things performed
1.)finding the type of client request
2.)calling doGet()/doPost() based on request type.
protected void service(HttpServletRequest request ,HttpServletResponse response)
throws ServletException,IOException
{
String method=request.getMethod();
if(method.equals("GET");
doGet(request,response);
else
doPosT(request,response);
}
public void service(ServletRequest request ,ServletResponse response)
throws ServletException,IOException
{
//ServletRequest typecast with HttpServletRequest
//ServletRresponse typecast with HttpServletResponse
}
ServletContainer calls public service
\/
\/
public service calls protected service
\/
\/
protected service calls doGet/doPost method
Q.45)What happen when request type is "Get: & implemented method is doPost() in any Servlet ?
The following ERROR massage will be display to user " Http method Get is not supported by this URL "
Q.46)What happen when request type is "Post" & implemented method is doGet() in any servlet ?
The following ERROR massage will be display to user " Http method Post is not supported by this URL "
Q.47)How we doGet() method implemented in HttpServlet to display the ERROR massage ?
when request type is "Post" & implemented method is doGet() in any servlet ERROR "HTTP method Post is not
supported by is URL"
Q.48)How we doPost() method implemented in HttpServlet to display the ERROR massage ?
when request type is "Get" & implemented method is doPost() in any servlet ERROR "HTTP method Post is not
supported by is URL"
Q.49)How many methods are abstract in HttpServlet class ?
zero method / 0 method but HttpServlet is abstract class to prevent instantiation of this(HttpServlet) class
Q.50)Explain about the following method call ?
=>response.setContentType("text/html"); this method is used to specify MIME multipurpose mail type/extension.
some MIME type
1.)text.html
2.)image.gif
3.)text.plan
4.)image.jpeg
.
.
.
250).........
Q.51)What are the methods of ServletConfig ?
1.)string getInitParameter(String) this method takes init param name as argument & return init param value.
2.)ServletContext getServletContext(); this method returns the reference of ServletContext Object

3.)string getServletName() return Registration name of a Servlet


4.)Enumaration getInitParameterNames(); this method returns an Enumaration
of strings which are init parameter name.
Enumaration e = Config.getInitParameterName()
while(e.hasMoreElement())
{
String name = (String)e.nextElement();
String pvalue=Config.getInitParameter(pname);
sop(pvalue);
}
Q.52)How many interfaces GenericServlet implement ?
GenericServlet implements 3 interface
1.)javax.servlet.Servlet
2.)javax.servlet.ServletConfig
3.)javax.io.Serializable
GenericServlet implements servlet interfaces that all its subclasses are eligible to act as servlets.
GenericServlet implements ServletConfig interface so that all the 4 mothods of ServletConfig can be used in
doGet/doPost method without the need of ServletConfig reference.
public class SomeServlet extends HttpServlet
{
public void doGet/doPost(....)
{
ServletConfig config = getServletConfig();
ServletContext sc = getServletContext();
String uname = getInitParameter("username");
}
}
GenericServlet implements serializable so that if required , user defined servlet interface either can be stored into the
disk or can be exported via network into the another machine.
Q.53)How many init methods are implemented in GenericServlet (abstract) class ?
2 init methods
1.parameterized init method(life cycle method)
2.non-parameterized init method(non-life cycle)
public abstract GenericServlet implements Servlet,ServletConfig,Serializable
{
ServletConfig _config;
public void init(ServletConfig config)throws ServletException
{
_config = config;
init();
}//override
public void init() throws ServlerException
{
}
..........
}
Note:- For Coding flexibility, always override zero argument init() method in a servlet.
Q.54)What happens if the following code is executed ?
public class SomeServlet extends HttpServlet
{
public void init(ServletConfig config)
{
}//init
public doGet(HttpServletRequest request,HttpServletResponse response)
{
ServletContext sc = getServletContext();

sop(sc);
}//doGet
}//class
O/P = NullPointerException is raised.
Note:-If we override parameterised init method in a user defined servlet , we should not call
ServletConfig reference , otherwise , NullPointerException is raised.
To fix this problem,ensure that GenericServlet provided parameterised init method is executed is
executed.
1.)Don`t override
2.)override only zero argument init method
3.)public void init(ServletConfig config)
{
super.init(config);
//application code.
}
Q.55)Explain about the following statement in a Servlet ?
PrintWriter out = response.getOutputStream(); java.io.PrintWriter is a character oriented output stream It is used to
transfer character oriented data from the Servlet to the destination. If the servlet has to transfer binary data we have
to use the other stream. ServletOutputStream sos = response.hetOutputStream();
Q.56) What is the life time of servlet instance ?
Application life time.
Q.57)What is the life time of ServletConfig Object ?
Its Servlet Life time
Q.58)What is the life time of request and response Object ?
one-request-response cycle , i.e. they created in HEAP just before ServlerContainer calls the service method and
they are destroyed once service method returns control to the Container.
Q.59)How many Servlet Objects ?
one(1) per User defined Servlet class per application.
Q.60)How many ServletConfig Object ?
one(1) per Servlet
Q.61)How many request and response objects ?
one (1) per client request.
Q.62) What are the important interfaces of servlet API that are used in servlet Programming ?
1.ServletConfig //to call all important method of itself(ServletConfig)
2.HttpServletReqiest //taking request from user(user-container-request object)
3.HttpServletResponse //sending response from user(response object-container-user)
4.RequestDispatcher //to connect or interact with other servlet
5.ServletContext //only one object used to share between all servlet of one application
6.HttpSession //for sharing data between all servlet and to session tracking
Note :-These interfaces fecililate Servlet Container Vendor Independent Servlet Programming.
Q.63)Write a piece of code in which , 2 servlet share some data in application scope ?
public class SomeServlet1 extends HttpServlet
{
public void doGet(HttpSetvletRequest request , HttpServletResponse response)
{
ServletContext sc = getServletContext();
sc.setAttribute("gross",5600);
}
}
-----------------------------------------------------------------------------------------public class SomeServlet2 extends HttpServlet
{
public void doGet(HttpSetvletRequest request , HttpServletResponse response)
{
ServletContext scTemp = getServletContext();//not new object created only new reference created
//same object

float gross = (Float)scTemp.getAttribute("gross");


}
}
Q.64)How to create RequestDespatcher Object using ServletContext ?
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher("other web component URL pattern");
OR
ServletContext sc = getServletContext();
RequestDispatcher rd = sc.getNamedRequestDispatcher("registration name of other servlet");
Q.65)How to perform Logging in a Servlet ?
ServletContext has log() method for that purpose.
Q.66)What kind of protocol is Http ?
HTTP is stateless protocol(connectionless protocol)
Note :- FTP is Statefull protocol
A Protocol is said to be stateless if the server is not maintaining prior connections(SESSION TRACKING).
Stateless of HTTP poses challenges to web application developers as end-user . interaction with the application
(website) should be stateful even though the protocol is stateless. //remembering the old user by keeping connection
info in file system is nothing but statefull protocol
Q.67)What is Purpose of SessionTracking ?
To make end-user interaction with website stateful.
Q.68)What is a Session ?
Generally time period between login and logout is nothing but a client Session OR user Session In the Context of
web server side programming , a session is an Object. javax.servlet.http.HttpSession object represent one session. If
a website is providing online service to registered users only , one session object per one logged in user. That session
is maintained until user logs out. If without login , the website is providing online services means , one session
Object per use-case(client log in - log out(guest or permanent user)).
Q.69)What is "Session Tracking" ?
Dealing with the end-user interaction with the application in a series of Client-Server interactions is nothing but
Session Tracking. i.e. dealing with User/client session is nothing but Session Tracking.
Q.70)How to implement Session Tracking in a Java web application ?
three step are involved in the implementation of session tracking
Step 1) Session creation(in fact , getting the reference of HttpSession Object)
for eg. HttpSession session = request.getSession();
Step 2) Dealing with client state (user data) On HttpSession Object , setAttribute() , getAttribute() ,
removeAttribute() and getAttributeNames() methods are called to deal with client state.
Step 3) Ending the Session(destroying the session) A user session can be ended in two ways
a)user explicit logout.
b) session timeout (session expiry)
If user explicitly signs out / logs out , we indicate to the Container to destroy the Session by calling invalidate()
method on HttpSession object.
Q.71)Explain about the following statement in a Servlet ?
HttpSession sesion = request.getSession();
When getSession() method is called on HttpServletRequest object , the following things happens in order .
1.)Container eveluates the request object for incoming session id from the client
2.if(session id is not found in the request object)
2.1)Container creates brand new HttpSession Object. A corresponding session id also created. session id & session
object are maintained by the container as name,value pair(in java.util.Map Object)
2.2)Session id is writtten into HttpResponse object so that it can be sent to the browser.
2.3)HttpSession object reference is returned to the servlet.
2.else(i.e. session id found in the request object)
2.1)Captures the session id from the request object , compare the id with the Map and one the match found , it will
not create the new Session Object.
It retrieves the already existing session object from the Map(name,value pair)
2.2)session id is written into HttpResponse object so that it can be sent to the browser
2.3)HttpSession object reference is returned to the servlet.

Q.72)Deveop Java Web Application in which , 2 servlet share data in session scope?
Source servlet capture the user name , stores in the session scope and produces a hyperlink for the user pointing to
target servlet Target Servlet use name from session scope where source servlet stores the name and print it.
SessionScopeApplication
user.html
WEB-INF
web.xml
src
TargetServlet.java
SourceServlet.java
classes
TargetServlet.class
SourceServlet.class
http://localhost:8080/SessionScopeApplication
web.xml
-------registration names :- eleven and twelve
public URL names :- /source & /target
home page
user.html
---------request type :- GET
request parameter name : user
<form action = "./source">
SourceServlet.java
--------------import javax.servlet.*;
import javax.servlet.http*;
import java.io.*;
public class SourceServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException
{
String username=request.getParameter("user");//get from request(html page)
HttpSession session= request.getSession();
session.setAttribute("user"/*as name*/,username/*value*/);
System.out.println("session id :"+session.getId());
System.out.println("it is new session ? :"+session.isNew());
System.out.println("Default session timeout period in seconds"+session.getMaxInactiveInterval());
session.setMaxInactiveInterval(3600);//60*60=1 minute
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<BODY BGCOLOR = "gray">");
out.println("<A HREF = ./target>Click here to Get USER NAME </A>");
out.println("</BODY>");
out.println("</HTML>");
out.close();
}//doGet service
}//class
public class TargetServlet extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException
{
HttpSession sessionTemp= request.getSession();
String user = (String)sessionTemp.getAttribute("user");

System.out.println("session id :"+session.getId());
System.out.println("it is new session ? :"+session.isNew());
System.out.println("Default session timeout period in seconds"+session.getMaxInactiveInterval());
session.setMaxInactiveInterval(600);//60*60=1 minute
System.out.println("Default session timeout period in seconds"+session.getMaxInactiveInterval());
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<BODY BGCOLOR = "gray">");
out.println("<H2> User Name : "+user+"</H2>);
out.println("</BODY>");
out.println("</HTML>");
out.close();
}//doGet service
}//class
//Refence name can be diffenrent but session hashcode for them....object same
Q.73)What is session time out(sesion expiry) ?
If the user is inactive with the website after a session fro that user is created for more than a specific period of time,
server implicitly destroys the session object and the user is frocibly logged out. this is called as session timeout.
every server has some default session TimeOut period for eg. Tomcat has 30 minutes.
It can be changed in two ways
1.)By calling a method
session.setmaxInactiveInterval(int seconds);
2.)in web.xml
<sessiom-config>
<sessiom-timeout>3</sessiom-timeout>
<sessiom-config>
here , 3 number is for indicating time in minute
3minutes = 180 seconds
Note:- After the session is destroyed , if client request comes , we have to give timeout massage means use the
following method request.isRequestSessionInValid();
Q.75)What is a Cookie in the context of a web application ?
A Cookie is a name,value pair of textual information is exchanged between server and client in a series of clientserver interactions.
server sent Cookie goes to the browser along with HTTP response headers.
browser receives the cookie and returns to the server along with HTTP request headers.
Cookies are of two types
1.)session Cookies
2.)Persistent Cookies.
"Session Cookie: dies once the browsing session ends. i.e. browser is closed.
"Persistent Cookie" is stored in the file system of the client machine.
Note:- During session tracking , session id is exchanged between the server and client as a session cookie only.
"jsessionid" is the name of Cookie that carries the session id. "SESSIONID itself " is the Cookie value.
Q.76)What are the uses of Cookies ?
1.To identify the user/client uniquely in a series of client-server interactions
2.To keep track of user name and user preferences(details).
3.To promote target web advertisement.
Q.77) How to implement persistant Cookie Concept in a java web application ?
Step 1) create as many Cookie Object as required by instantiating
javax.servlet.http.Cookie class.
Cookie c = new Cookie("sport", cricket);
Step 2) Make the Cookie Persistant.
c.setMaxAge(365*24*60*60)//1year
Step 3) send the Cookie to the Client
response.addCookie(c);
Step 4) Capture the incoming Cookies(from the client)

Cookie c[] = request.getCookie();


Cookie class has getName() method that return the name of the Cookie and getValue()
method returns to retrieve the value of the Cookie.
Q.79)What is URL rewriting ?
Appending session-id to the URL is called as URL rewriting.//(aading session-id to URL) if Cookies are disable ,
session tracking fails as browser does not add resend Cookie.
URL rewriting facilitates the smooth functioning of session trackking even though Cookies are disabled at client
side.
By calling encodeURL() method on the HttpServletResponse object , URL rewriting is implemented.
Q.80)Develop a web application in which URL rewriting is implemented ?
URLRewritingApplication
user.html
WEB-INF
web.xml
SRC
SourceServlet.java
TargetServlet.java
classes
SourceServlet.class
TargetServlet.class
lib
http://localhost:8080/URLRewritingApplication
Note:- user.html , web.xml & TargetServlet.java from "sessionscopeapplication" Ealier code in SourceServlet.java
out.println("<A HREF = ./target> click here to go target page </A>");
modified code in SourceServlet.java
String newURL = response.encodeURL("./target");
out.println("<A HREF> "+newURL+"click here to go target page </A>");
Q.81)What are hidden fields ?
Invisible fields of a HTML form are nothing but hidden form fields.
A hidden form fields is created as follows <Input type = "hidden" name="user" value="scott" >
hidden form fields request parameters are stored in "request" object at server side by calling getParameter() method
on request object , hidden form field is captured at server side .
Note:- there is no special API to deal with hidden form field as their is no difference between hidden from & visible
form fields. To store some data to(for) the user invisibily from a web-site which is required in next request response
cycle , hidden form field are used.
Q.83)What is filter ?
A filter is a container managed public userdefined java class that implements javax.servlet.Filter interface whose
instance intercepts a web component in its request-response cycle.
|
client------------> |---F>ilter| ------------->User Defined
server<----------- |<---------|<-------------Servlet class
||
||
|
| WEB SERVER
Filter can either assist the web component or can moniter the activities of web-component. A filter can pre-process
the client request & Post-process the web-component response.
Q.84)What is the general structure of a filter ?
public class MyFilter implements Filter
{
public void init(FilterConfig config)
{
//Resource Allocation if any
}//init(life cycle method)
public void destroy()
{

//Resource releasing
}//destroy(life cycle method)
public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain)
{
//Pre-Processing if any
chain.doFilter(request,response);
//switch to web component or to next filter in the chain
}//doFilter(life cycle method)
}//MyFilter class
ServletContainer controls the life cycle if a filter , as soon as the web application is deployed and before any client
request comes, ServletContainer create filter instance and calls its init() method i.e. filter is pre-initialazed bydefault , where as , a servlet is not pre-initialized instantiation and initialization & destruction happens only once in a
filterlife time. When application s unloaded OR the container is shutdown ,container invoke destroy method of
the filter. For each client request ServletContext calls doFilter() method of Filter once.
The Duty of the Filter is implemented in the life cycle method doFilter();
Q.85)What is filter chaining ?
Applying multiple filters for the some web component is called as filter chining Filter chianing is implemented in
web.xml
Q.86)How to register filter with a container ?
<web-app>
//........other code
<filter>
<filter-name>
Autheticate
</filter-name>
<filter-class>
AuthenticationApplicationFilter
</filter-class>
</filter>
<filter>
<filter-name>
HitCount
</filter-name>
<filter-class>
HitCountApplicationFilter
</filter-class>
</filter>
//.........other code
</web-app>
Q.87)How to apply a filter to a Servlet ?
<filter-mapping>
<filter-name>Authenticate</filter-name>
<url-pattern>/ServletName</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>HitCount</filter-name>
<url-pattern>/ServletName</url-pattern>
</filter-mapping>
Note:-Here, Multiple filters are applied to the some servlet and hence filter chaining.
Q.88)Develop a Java In which filter chaining is implemented ?
refer handout//printed Notes
|
client------------> |--->Filter|--->Filter| ------------->User Defined
server<----------- |<---------|<---------|<-------------Servlet class
| | HitCount
| | Filter SomeServlet

|Authentication
| Filter
| WEB SERVER
Q.89)What are the methods of filter Config ?
1.)getFilterName() :- return the registration name of the filter.
2.)getServletContext();
3.)getInitParameter();
4.)getInitParameterNames();
Q.90)What is the method of FilterChaining ?
doFilter(ServletRequest,ServletResponse) method is used to switch the control
from one filter to another or to a web component.
Q.91)How to implement event handling in a java web application ?
In a java web application the following are some of the events
1.)Application Deployed
2.)Application UnDeployed
3.)User Logged in
4.)User Logged out
5.)User added an item to shopping cart etc.
Dealing with events & performing some usefull task whenever such event occurs is nothing but event handling in a
Java web application.
Event Handling provides some extra Facility & Fexibility to the application.
Event Handling in Java Web-Application involves following steps
1.)Develop a listener class
2.)Implement event handler in that listener class
3.)register the listener with the container
4.)any userdefined public java class that implement XYZ listener interface is eligible to act as a listener class.
This library listener interface provides event handling methods.
in userdefined listener classes , override those event handler methods and write code to perform the required task.
<listener>
<listener-class>
SomeListener
</listener-class>
</listener>
Using the above tags , a listener is registered with the container
Q.92)How to know the number of users that are active with website which provides services only to
registered user ?
import javax.servlet.http.*;
public class ActiveUserCountListener implement HttpServletListener
{
int count;
public void sessionCreated(HttpSessionEvent e)
{
count++;
//and other logic
}//sessionCreated
public void sessionDestroyed(HttpSessionEvent e)
{
count--;
//non-active destroyed
}
}//ActiveUserCountListener
<web-app>
<listener>
<listener-class>
ActiveUserCountListener
</listener-class>

</listener>
</web-app>
Q.93)How to implement the following Task In a Java web-application ?
1.)Database connection has to be generete as soon as application is deployed.
2.)Make that connection available to all the Servlet of the application.
3.)close the connection only when application is undeployed.
------------------------------------------------------------------import javax.servlet.*;
public class ApplicationListener implement HttpServletListener
{
Connection conn;
public void contextCreated(ServlerContextEvent e)
{
Class.forName("orcle.jdbc.driver.OracleDriver");
conn=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521","SYSTEM","riddhi");
ServletContext sc = e.getServletContext();
sc.setAttribute("connection",conn);
}//contextCreated
public void contextDestroyed(ServletContextEvent e)
{
conn.close();
}//contextDestroyed
Note:-In every Servlet`s service method are write following code
Coonection conn = (Connection)getServletContext().getAttribute("connection");
}//ApplicationListener
Q.106)Modify AdditionServlet to make it HttpServlet ?
//AdditionServletApplication.java
import javax.servlet.*;
import java.io.*;
import javax.servlet.http.*;
public class ModifiedAdditionServletApplication extends HttpServlet
{
public void doGet(HttpServletRequest request , HttpServletResponse response)throws IOException
{
String a = request.getParameter("T1");
String b = request.getParameter("T2");
int n1 = Integer.parseInt(a);
int n2 = Integer.parseInt(b);
int sum = n1+n2;
//int sum=100;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<HTML>");
out.println("<BODY BGCOLOR=yellow>");
out.println("<H1>The sum is : "+sum+"</H1>");
out.println("</BODY>");
out.println("</HTML>");
out.close();
}//service
}//AdditionServletApplication

Servlet overview
Web application:
A web application or website is an application program which accessed over a network connection using HTTP and
often runs inside a web browser.
Web browser:
A web browser is a program which is act as an interface between user and web application e.g. Internet Explorer,
Chrome, Safari, Mozilla firefox etc.
CGI (Common gateway interface):
CGI was the first protocol or way of communication between web server and program. It passes a request from a
web user to an application program and receives data back to forward to the web user i.e. It is responsible for
dynamic content generation.
Advantages of CGI:
1. 1. Technology portability: CGI programming can be written in variety of languages like c, c++, perl.
2. 2. Web server portability: All service providers support CGI Programs.
Disadvantages:
1. 1. Response time is high.
2. 2. CGI scripts are platform-dependent.
3. 3. For every request, a new process will be started and web server is limited to start processes.
4. 4. CGI programs are not object oriented always.
Servlet overcomes the above disadvantages.
Servlet as technology:
As a technology servlet provides a model of communication between a web user request and the application or
program on the web server.
Servlet as component:
As a component servlet is a program which is executed in web server and responsible for dynamic content
generation.
Main tasks of servlet:
1. 1. Read the implicit and explicit data sent by web browser.
2. 2. Generate result by processing the data.
3. 3. Send the implicit and explicit data as a response to the web browser.
Servlet Packages:
javax.servlet and javax.servlet.http packages contains the classes and interfaces for servlet API. These packages are
the standard part of Javas enterprise edition.
javax.servlet contains a number of classes and interfaces which are mainly used by servlet container.
javax.servlet.http contains a number of classes and interfaces which are mainly used by http protocol.
Differences between CGI and Servlet.
CGI
Servlet
1. 1. CGI is process based. For every request a
1. 1. Servlet is thread based. For every
new process will be started.
request a new thread will be started.
2. 2. Concurrency problems cant occur in CGI
2. 2. Concurrency problems can occur in
because it is process based.
servlet because it is thread based.
3. 3. Platform dependent.
3. 3. Platform independent.
4. 4. Can be written in variety of languages like c,
4. 4. Can be written only in java.
c++, perl.
5. 5. Response time is low.
5. 5. Response time is high.
Life cycle of a servlet
Life cycle of a servlet is managed by web container.
Servlet life cycle steps:
1. 1. Load Servlet Class.
2. 2. Create Servlet instance.
3. 3. Call init() method.
4. 4. Call service() method.
5. 5. Call destoy() method.

1. Load Servlet Class: Web container loads the servlet when the first request is received. This step is executed only
once at the time of first request.
2. Create Servlet instance: After loading the servlet class web container creates the servlet instance. Only one
instance is created for a servlet and all concurrent requests are executed on the same servlet instance.
3. Call init() method: After creating the servlet instance web container calls the servlets init method. This method
is used to initialize the servlet before processing first request. It is called only once by the web container.
4. Call service() method: After initialization process web container calls service method. Service method is called
for every request. For every request servlet creates a separate thread.
5.Call destoy() method: This method is called by web container before removing the servlet instance. Destroy
method asks servlet to releases all the resources associated with it. It is called only once by the web container when
all threads of the servlet have exited or in a timeout case.
Servlet interface in java
Servlet interface:
Servlet interface contains the common methods for all servlets i.e. provides the common behaviour for all servlets.
public interface Servlet
Servlet interface is in javax.servlet package (javax.servlet.Servlet).
Methods of servlet interface:
1. init(ServletConfig config): It is used to initialize the servlet. This method is called only once by the web
container when it loads the servlet.
Syntax: public void init(ServletConfig config)throws ServletException
2. service(ServletRequest request,ServletResponse response): It is used to respond to a request. It is called for
every new request by web container.
Syntax: public void service(ServletRequest req,ServletResponse res)throws ServletException, IOException
3. destroy(): It is used to destroy the servlet. This method is called only once by the web container when all threads
of the servlet have exited or in a timeout case.
Syntax: public void destroy()
4. getServletConfig(): It returns a servlet config object. This config object is passed in init method. Servlet config
object contains initialization parameters and startup configuration for this servlet.
Syntax: public ServletConfig getServletConfig()
5. getServletInfo(): It returns a string of information about servlets author, version, and copyright etc.
Syntax: public String getServletInfo()
Servlet Hello World example by implementing Servlet interface.

HelloWorld.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* This servlet program is used to print "Hello World" on
* client browser by implementing servlet interface.
* @author javawithease
*/
public class HelloWorld implements Servlet {
private static final long serialVersionUID = 1L;
//no-argument constructor.
public HelloWorld() {
}
ServletConfig config=null;
@Override
public void init(ServletConfig config) throws ServletException {
this.config = config;
System.out.println("Do initialization here.");
}
@Override
public void destroy() {
System.out.println("Do clean-up process here.");
}
@Override
public ServletConfig getServletConfig() {
return config;
}
@Override
public String getServletInfo() {
return "www.javawithease.com";
}
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello World example using " +
"servlet interface.</h1>");

out.close();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>
com.javawithease.business.HelloWorld
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>
Output:

Download this example.


GenericServlet class in java
GenericServlet class:
GenericServlet class implements the Servlet and ServletConfig interfaces. GenericServlet is protocol-independent.
It not provides the implementation of service method.

public abstract class GenericServlet implements Servlet, ServletConfig


GenericServlet class is in javax.servlet package (javax.servlet.GenericServlet).
Methods of GenericServlet class:
1. init(ServletConfig config): It is used to initialize the servlet. This method is called only once by the web
container when it loads the servlet.
Syntax: public void init(ServletConfig config)throws ServletException
2. service(ServletRequest request,ServletResponse response): It is used to respond to a request. It is called for
every new request by web container.
Syntax: public abstract void service(ServletRequest req,ServletResponse res)throws ServletException,
IOException
3. destroy(): It is used to destroy the servlet. This method is called only once by the web container when all threads
of the servlet have exited or in a timeout case.
Syntax: public void destroy()
4. getServletConfig(): It returns a servlet config object. This config object is passed in init method. Servlet config
object contains initialization parameters and startup configuration for this servlet.
Syntax: public ServletConfig getServletConfig()
5. getServletInfo(): It returns a string of information about servlets author, version, and copyright etc.
Syntax: public String getServletInfo()
6. Init(): It is a convenience method which can be overridden so that there is no need to call super.init(config).
Syntax: public void init() throws ServletException
7. getServletContext():It returns the ServletContext object in which this servlet is running.
Syntax: public ServletContext getServletContext()
8. getInitParameter(String name): It returns the value for given parameter name. It returns null if parameter not
exist.
Syntax: public String getInitParameter(String name)
9. getInitParameterNames(): It returns the names of the servlets initialization parameters defined in web.xml file.
Syntax: public Enumeration getInitParameterNames()

10. getServletName(): It returns the name of this servlet object.


Syntax: public String getServletName()
11. log(String msg): This method writes the specified message to the servlet log file.
Syntax: public void log(String msg)
12. log(String msg,Throwable t): This method writes an explanatory message and a stack trace for a
given exception to the servlet log file.
Syntax: public void log(String msg,Throwable t).
Servlet Hello World example by extending GenericServlet class.
HelloWorld.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* This servlet program is used to print "Hello World" on
* client browser using GenericServlet class.
* @author javawithease
*/
public class HelloWorld extends GenericServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor.
public HelloWorld() {
}
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello World example using" +
" GenericServlet class.</h1>");
out.close();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>

<web-app id="WebApp_ID" version="2.4"


xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>
com.javawithease.business.HelloWorld
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>

Output:

Download this example.


HttpServlet class in java
HttpServlet class:
HttpServlet class extends the GenericServlet. It is protocol-dependent.

public abstract class HttpServlet extends GenericServlet


HttpServlet class is in javax.servlet.http package (javax.servlet.http.HttpServlet).
Methods of HttpServlet class:
1. service(ServletRequest req,ServletResponse res):Dispatches the requests to the protected service method. It
converts the request and response object into http type before dispatching request.
Syntax: public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException
2. service(HttpServletRequest req, HttpServletResponse res):Receives HTTP requests from the
public service method and dispatches the request to the doXXX methods defined in this class.
Syntax: protected void service(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException
3. doGet(HttpServletRequest req, HttpServletResponse res): This method is called by web container for
handling GET requests.
Syntax: protected void doGet(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException
4. doPost(HttpServletRequest req, HttpServletResponse res): This method is called by web container for
handling POST requests.
Syntax: protected void doPost(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException
5. doHead(HttpServletRequest req, HttpServletResponse res): This method is called by web container for
handling HEAD requests.
Syntax: protected void doHead(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException
6. doOptions(HttpServletRequest req, HttpServletResponse res): This method is called by web container for
handling OPTIONS requests.
Syntax: protected void doOptions(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException
7. doPut(HttpServletRequest req, HttpServletResponse res): This method is called by web container for
handling PUT requests.
Syntax: protected void doPut(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException

8. doTrace(HttpServletRequest req, HttpServletResponse res): This method is called by web container for
handling TRACE requests.
Syntax: protected void doTrace(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException
9. doDelete(HttpServletRequest req, HttpServletResponse res): This method is called by web container for
handling DELETE requests.
Syntax: protected void doDelete(HttpServletRequest req, HttpServletResponse res) throws
ServletException,IOException
10. getLastModified(HttpServletRequest req): It returns the time the HttpServletRequest object was last
modified since midnight January 1, 1970 GMT. It returns a negative number if time is unknown.
Syntax: protected long getLastModified(HttpServletRequest req)
Servlet Hello World example by extending HttpServlet class.

HelloWorld.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This servlet program is used to print "Hello World"
* on client browser using HttpServlet class.
* @author javawithease
*/
public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor.
public HelloWorld() {
}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello World using HttpServlet class.</h1>");
out.close();
}
}

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>
com.javawithease.business.HelloWorld
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>
Output:

Download this example.


Deployment Descriptor: web.xml file
Deployment Descriptor:

In a java web application a file named web.xml is known as deployment descriptor. It is a xml file and <web-app> is
the root element for it. When a request comes web server uses web.xml file to map the URL of the request to the
specific code that handle the request.
Sample code of web.xml file:
<web-app>
<servlet>
<servlet-name>servletName</servlet-name>
<servlet-class>servletClass</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletName</servlet-name>
<url-pattern>*.*</url-pattern>
</servlet-mapping>
</web-app>
How web.xml works:
When a request comes it is matched with url pattern in servlet mapping attribute. In the above example all urls
mapped with the servlet. You can specify a url pattern according to your need. When url matched with url pattern
web server try to find the servlet name in servlet attributes same as in servlet mapping attribute. When match found
control is goes to the associated servlet class.
Servlet Hello World example by extending HttpServlet class.

HelloWorld.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This servlet program is used to print "Hello World"
* on client browser using HttpServlet class.
* @author javawithease
*/
public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor.
public HelloWorld() {

}
protected void doGet(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello World using HttpServlet class.</h1>");
out.close();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>HelloWorld</servlet-name>
<servlet-class>
com.javawithease.business.HelloWorld
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorld</servlet-name>
<url-pattern>/HelloWorld</url-pattern>
</servlet-mapping>
</web-app>
Output:

Download this example.


welcome-file-list in web.xml
welcome-file-list:
The welcome-file-list attribute of web.xml file is used to define the list of welcome files.
Sample code of welcome-file-list attribute in web.xml:
<web-app>
//other attributes
<welcome-file-list>
<welcome-file>home.html</welcome-file>
<welcome-file>welcome.html</welcome-file>
</welcome-file-list>
//other attributes
</web-app>
How it works:
First web server looks for welcome-file-list if it exist then it looks for file defined in first welcome-file. If this file
exists then control is transferred to this file otherwise web server will look at the next welcome file and so on.
If the welcome-file-list is not exists or files defined in welcome-file-list are not exists then server will looks at the
default welcome files in following order index.html, index.htm, index.jsp, default.html, default.htm and default.jsp.

Default welcome file list:


<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
Example of welcome-file-list:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<welcome-file-list>
<welcome-file>welcome.html</welcome-file>
</welcome-file-list>
</web-app>
welcome.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>welcome</title>
</head>
<body>
<h1>This is a welcome file list program.</h1>
</body>
</html>
Output:

Download this example.


load-on-startup in web.xml
load-on-startup:
The load-on-startup is the sub attribute of servlet attribute in web.xml. It is used to control when the web server
loads the servlet. As we discussed that servlet is loaded at the time of first request. In this case response time is
increased for first request. If load-on-startup is specified for a servlet in web.xml then this servlet will be loaded
when the server starts. So the response time will not increase for fist request.
Any positive or negative value can be passed in the load-on-startup. If positive value is passed then all servlets
having load-on-startup sub attribute will be loaded when server starts but a servlet having low positive value will be
loaded first. In case of negative value servlet will be loaded at the time of first request.
Sample code of load-on-startup in web.xml.
<web-app>
//other attributes
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>com.javawithease.business.Servlet1 </servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet>
<servlet-name>servlet2</servlet-name>
<servlet-class> com.javawithease.business.Servlet2</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet>
<servlet-name>servlet3</servlet-name>
<servlet-class> com.javawithease.business.Servlet3</servlet-class>
<load-on-startup>-1</load-on-startup>
</servlet>
//other attributes
</web-app>

In the above example Servlet1 and Servlet2 will be loaded when server starts because positive value is passed in
there load-on-startup. Servlet3 will be loaded at the time of first request because negative value is passed in there
load-on-startup.
RequestDispacher interface
RequestDispacher is an interface that provides the facility to forward a request to another resource or include the
content of another resource. RequestDispacher provides a way to call another resource from a servlet. Another
resource can be servlet, jsp or html.
Methods of RequestDispacher interface:
1. forward(ServletRequest request,ServletResponse response): This method forwards a request from a servlet to
another resource on the server.
Syntax:public void forward(ServletRequest request,ServletResponse response)throws ServletException,
IOException
2. include(ServletRequest request,ServletResponse response): This method includes the content of a resource in
the response.
Syntax: public void include(ServletRequest request,ServletResponse response)throws ServletException,
IOException
How to get an object of RequestDispacher.
RequestDispacher object can be gets from HttpServletRequest object.ServletRequests
getRequestDispatcher()method is used to get RequestDispatcher object.
RequestDispatcher requestDispatcher = request.getRequestDispatcher(/another resource);
After creating RequestDispatcher object you call forword or include method as per your requirement.
requestDispatcher.forward(request, response);
or
requestDispatcher.include(request, response);
Example:
LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;
/**
* This class is used for authentication process.
* @author javawithease
*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor
public LoginServlet() {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws
ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//get parameters from request object.
String userName =
request.getParameter("userName").trim();
String password =
request.getParameter("password").trim();
//check for null and empty values.
if(userName == null || userName.equals("")
|| password == null || password.equals("")){
out.print("Please enter both username" +
" and password. <br/><br/>");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);
}//Check for valid username and password.
else if(userName.equals("jai") &&
password.equals("1234")){
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("WelcomeServlet");
requestDispatcher.forward(request, response);
}else{
out.print("Wrong username or password. <br/><br/>");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);
}
}
}
WelcomeServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This class is used to show the message
* when user logged in successfully.
*/
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor
public WelcomeServlet() {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>You are logged " +
"in successfully.</h1>");
out.println("</html></body>");
}
}
login.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<form action="LoginServlet" method="post">
Username:<input type="text" name="userName"/>
<br/><br/>
Password:<input type="password" name="password"/>
<br/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>
com.javawithease.business.LoginServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>
com.javawithease.business.WelcomeServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
Output:

Enter username: jai and password:1234

Click on login button.

Download this example.


sendRedirect in servlet
sendRedirect() is the method of HttpServletResponse interface which is used to redirect response to another
resource.
Syntax: response. sendRedirect(relative url);
Difference between sendRedirect and RequestDispatcher.
SendRedirect
RequestDispatcher
1. 1. Creates a new request from the client
1. 1. No new request is created.
browser for the resource.
2. 2. Not accept relative url so can go only
2. 2. Accept relative url so control can go inside or
inside the server.
outside the server.
3. 3. New url cant be seen in browser.
3. 3. New url can be seen in browser.
4. 4. Work on request object.
4. 4. Work on response object.
Example:
LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This class is used for authentication process.
* @author javawithease
*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor
public LoginServlet() {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//get parameters from request object.
String userName =
request.getParameter("userName").trim();
String password =
request.getParameter("password").trim();
//check for null and empty values.
if(userName == null || userName.equals("")
|| password == null || password.equals("")){
out.print("Please enter both username " +
"and password. <br/><br/>");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);
}//Check for valid username and password.
else if(userName.equals("jai") && password.equals("1234")){
response.sendRedirect("WelcomeServlet");
}else{
out.print("Wrong username or password. <br/><br/>");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);
}
}
}
WelcomeServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;
/**
* This class is used to show the
* message when user logged in successfully.
*/
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor
public WelcomeServlet() {
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><body>");
out.println("<h1>You are logged in " +
"successfully.</h1>");
out.println("</html></body>");
}
}
login.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<form action="LoginServlet" method="post">
Username:<input type="text" name="userName"/>
<br/><br/>
Password:<input type="password" name="password"/>
<br/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<servlet>

<servlet-name>LoginServlet</servlet-name>
<servlet-class>
com.javawithease.business.LoginServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>
com.javawithease.business.WelcomeServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
Output:

Enter username: jai and password:1234

Click on login button.

Servlet Init parameters and ServletConfig interface


Init parameters:
Init parameters refers to the initialization parameters of a servlet or filter. <init-param> attribute is used to define a
init parameter. <init-param> attribute has two main sub attributes <param-name> and <param-value>. The <paramname> contains the name of the parameter and <param-value> contains the value of the parameter.
ServletConfig interface:
ServletConfig interface is used to access the init parameters.
Methods of ServletConfig interface:
1. getInitParameter(String name): Returns the value of the specified parameter if parameter exist otherwise return
null.
Syntax: public String getInitParameter(String name)
2. getInitParameterNames(): Returns the names of init parameters as Enumeration if servlet has init parameters
otherwise returns an empty Enumeration.
Syntax: public Enumeration getInitParameterNames()
3. getServletContext():Returns an instance of ServletContext.
Syntax: public ServletContext getServletContext()
4. getServletName():Returns the name of the servlet.
Syntax: public String getServletName()

Example:
InitParamExample.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This class is used to show the use of init parameters.
* @author javawithease
*/
public class InitParamExample extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor
public InitParamExample() {
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//get ServletConfig object.
ServletConfig config=getServletConfig();
//get init parameter from ServletConfig object.
String appUser = config.getInitParameter("appUser");
out.print("<h1>Application User: " + appUser + "</h1>");
out.close();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<servlet>
<servlet-name>InitParamExample</servlet-name>
<servlet-class>
com.javawithease.business.InitParamExample

</servlet-class>
<init-param>
<param-name>appUser</param-name>
<param-value>jai</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>InitParamExample</servlet-name>
<url-pattern>/InitParamExample</url-pattern>
</servlet-mapping>
</web-app>
Output:

Download this example.


Servlet context parameters and ServletContext interface
Context parameters:
Context parameters refers to the initialization parameters for all servlets of an application. <context-param> attribute
is used to define a context parameter. <context-param> attribute has two main sub attributes <param-name> and
<param-value>. The <param-name> contains the name of the parameter and <param-value> contains the value of
the parameter.
ServletContext interface:
ServletContext interface is used to access the context parameters.

Commonly used methods of ServletContext interface:


1. getInitParameter(String name): Returns the value of the specified parameter if parameter exist otherwise return
null.
Syntax: public String getInitParameter(String name)
2. getInitParameterNames(): Returns the names of context parameters as Enumeration if servlet has context
parameters otherwise returns an empty Enumeration.
Syntax: public Enumeration getInitParameterNames()
3. setAttribute(String name,Object object): Binds the specified object to the specified attribute name and put this
attribute in application scope.
Syntax: public void setAttribute(String name,Object object).
4. getAttribute(String name): Returns the specified attribute if exist otherwise returns null.
Syntax: public Object getAttribute(String name)
5. removeAttribute(String name): Removes the specified attribute.
Syntax: public void removeAttribute(String name).
Example:
ContextParamExample.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This class is used to show the use of context parameters.
* @author javawithease
*/
public class ContextParamExample extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor.
public ContextParamExample() {
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)

throws ServletException, IOException {


response.setContentType("text/html");
PrintWriter out = response.getWriter();
//get ServletContext object.
ServletContext context=getServletContext();
//get context parameter from ServletContext object.
String appUser = context.getInitParameter("appUser");
out.print("<h1>Application User: " + appUser + "</h1>");
out.close();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<servlet>
<servlet-name>ContextParamExample</servlet-name>
<servlet-class>
com.javawithease.business.ContextParamExample
</servlet-class>
</servlet>
<context-param>
<param-name>appUser</param-name>
<param-value>jai</param-value>
</context-param>
<servlet-mapping>
<servlet-name>ContextParamExample</servlet-name>
<url-pattern>/ContextParamExample</url-pattern>
</servlet-mapping>
</web-app>
Output:

Download this example.


Servlet Hello World Example using annotation.
ServletAnnotationExample.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This servlet program is used to print "Hello World" on
* client browser using annotations.
*/
@WebServlet("/HelloWorld")
public class ServletAnnotationExample extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor
public ServletAnnotationExample() {
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<h1>Hello World example using annotations.</h1>");
out.close();
}

}
Output:

Download this example.


Session management and cookies in servlet
Session:
Session is a time interval devoted to an activity.
Session Tracking:
Session Tracking or session management is a way of maintaining the state of the user.
Need of Session Tracking:
As we discussed in earlier tutorials we are using HTTP for completing request response cycle. HTTP is a stateless
protocol which means when a new request comes it cant keep any record or state of previous request of the user.
Thats why we need session tracking for maintaining the state of the user.
Way of Session Tracking in servlet:
1.
2.
3.
4.

1. Cookie.
2. Hidden form field.
3. Url rewriting.
4. HttpSession.

Cookie in servlet
Cookie:
A cookie is a small piece of information as a text file stored on clients machine by a web application.
How cookie works?
As HTTP is a stateless protocol so there is no way to identify that it is a new user or previous user for every new
request. In case of cookie a text file with small piece of information is added to the response of first request. They

are stored on clients machine. Now when a new request comes cookie is by default added with the request. With
this information we can identify that it is a new user or a previous user.
Types of cookies:
1. Session cookies/Non-persistent cookies: These types of cookies are session dependent i.e. they are accessible as
long as session is open and they are lost when session is closed by exiting from the web application.
2. Permanent cookies/Persistent cookies: These types of cookies are session independent i.e. they are not lost
when session is closed by exiting from the web application. They are lost when they expire.
Advantages of cookies:
1. 1. They are stored on client side so dont need any server resource.
2. 2. and easy technique for session management.
Disadvantages of cookies:
1. 1. Cookies can be disabled from the browser.
2. 2. Security risk is there because cookies exist as a text file so any one can open and read users information.
Cookie Class:
Cookie class provides the methods and functionality for session management using cookies. Cookie class is in
javax.servlet.http
Package javax.servlet.http.Cookie.
Commonly used constructor of Cookie class:
1. Cookie(String name,String value): Creates a cookie with specified name and value pair.
Syntax: public Cookie(String name,String value)
Commonly used methods of cookie class:
1. setMaxAge(int expiry):Sets the maximum age of the cookie.
Syntax: public void setMaxAge(int expiry)
2. getMaxAge(): Returns the maximum age of the cookie. Default value is -1.
Syntax: public int getMaxAge()
3. setValue(String newValue): Change the value of the cookie with new value.
Syntax: public void setValue(String newValue)
4. getValue(): Returns the value of the cookie.
Syntax: public String getValue()
5. getName(): Returns the name of the cookie.
Syntax: public String getName()
How to create cookie?
HttpServletResponse interfaces addCookie(Cookie ck) method is used to add a cookie in response object.
Syntax: public void addCookie(Cookie ck)
Example:
//create cookie object
Cookie cookie=new Cookie(cookieName,cookieValue);
//add cookie object in the response
response.addCookie(cookie);
How to get cookie?
HttpServletRequest interfaces getCookies() method is used to get the cookies from request object.
Syntax: public Cookie[] getCookies()
Example:
//get all cookie objects.
Cookie[] cookies = request.getCookies();
//iterate cookies array to get individual cookie objects.
for(Cookie cookie : cookies){
out.println(Cookie Name: + cookie.getName());
out.println(Cookie Value: + cookie.getValue());
}
How to remove or delete cookies?
Cookies can be removed by setting its expiration time to 0 or -1. If expiration time set to 0 than cookie will be
removed immediately. If expiration time set to -1 than cookie will be removed when browser closed.

Example:
//Remove value from cookie
Cookie cookie = new Cookie(cookieName, );
//Set expiration time to 0.
cookie.setMaxAge(0);
//add cookie object in the response.
response.addCookie(cookie);
Session management example using cookie:
CreateCookieServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This class is used to create cookies.
* @author javawithease
*/
public class CreateCookieServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor
public CreateCookieServlet() {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//get parameters from request object.
String userName = request.getParameter("userName").trim();
String password = request.getParameter("password").trim();
//check for null and empty values.
if(userName == null || userName.equals("") ||
password == null || password.equals("")){
out.print("Please enter both username " +
"and password. <br/><br/>");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);
}//Check for valid username and password.
else if(userName.equals("jai") && password.equals("1234")){
//create cookie objects.
Cookie cookie1 = new Cookie("userName",userName);
Cookie cookie2 = new Cookie("password",password);
//add cookie in the response object.

response.addCookie(cookie1);
response.addCookie(cookie2);
out.print("<h3>Cookies are created. Click on the " +
"below button to get cookies.");
out.print("<form action='GetCookieServlet' method='POST'>");
out.print("<input type='submit' value='Get Cookie'>");
out.print("</form>");
out.close();
}else{
out.print("Wrong username or password. <br/><br/>");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);
}
}
}
GetCookieServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This class is used to get cookies.
* @author javawithease
*/
public class GetCookieServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor
public GetCookieServlet() {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
Cookie cookies[] = request.getCookies();
for(Cookie cookie : cookies){
out.println("Cookie Name: " + cookie.getName());
out.println("Cookie Value: " + cookie.getValue());
out.println("");
}
out.println("Click on the below button to delete cookies.");
out.print("<form action='DeleteCookieServlet' method='POST'>");
out.print("<input type='submit' value='Delete Cookies'>");
out.print("</form>");

out.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
DeleteCookieServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This class is used to delete cookies.
* @author javawithease
*/
public class DeleteCookieServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor
public DeleteCookieServlet() {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try{
Cookie cookies[] = request.getCookies();
out.print("Deleted cookie are:");
for(Cookie cookie : cookies){
cookie.setMaxAge(0);
out.println("Cookie name: " + cookie.getName());
}
out.close();
}catch(Exception e){
e.printStackTrace();
}
}
}
login.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>

</head>
<body>
<form action="CreateCookieServlet" method="post">
Username:<input type="text" name="userName"/>
<br/><br/>
Password:<input type="password" name="password"/>
<br/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>CreateCookieServlet</servlet-name>
<servlet-class>
com.javawithease.business.CreateCookieServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CreateCookieServlet</servlet-name>
<url-pattern>/CreateCookieServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>GetCookieServlet</servlet-name>
<servlet-class>
com.javawithease.business.GetCookieServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetCookieServlet</servlet-name>
<url-pattern>/GetCookieServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>DeleteCookieServlet</servlet-name>
<servlet-class>
com.javawithease.business.DeleteCookieServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DeleteCookieServlet</servlet-name>
<url-pattern>/DeleteCookieServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>

<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
Output:

Enter username: jai and password: 1234


Click on login button.

Click on Get Cookie button to get cookies.

Click on delete button to delete cookies.

Download this example.


Hidden field in servlet
Hidden field:
Hidden field is an input text with hidden type. This field will not be visible to the user.
Syntax:<input name=fieldName value=fieldValue type=hidden/>
How to get hidden field value in servlet?
HttpServletRequest interfaces getParameter() method is used to get hidden field value in servlet.
Syntax: String value = request.getParameter(fieldName);
Note: Hidden field only works in case of form submission so they will not work in case of anchor tag as no form
submission is there.
Advantages of hidden field:
1. All browsers support hidden fields.
2. Simple to use.
Disadvantages of hidden fields:
1. Not secure.
2. Only work in case of form submission.
Session management example using hidden field:
SetHiddenFieldServlet.java
import java.io.IOException;

import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This class is used to set values in hidden fields.
* @author javawithease
*/
public class SetHiddenFieldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor.
public SetHiddenFieldServlet() {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//get parameters from request object.
String userName = request.getParameter("userName").trim();
String password = request.getParameter("password").trim();
//check for null and empty values.
if(userName == null || userName.equals("") ||
password == null || password.equals("")){
out.print("Please enter both username " +
"and password. <br/><br/>");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);
}//Check for valid username and password.
else if(userName.equals("jai") && password.equals("1234")){
out.println("Logged in successfully.<br/>");
out.println("Click on the below button to see " +
"the values of Username and Password.<br/>");
out.print("<form action='GetHiddenFieldServlet'" +
" method='POST'>");
out.print("<input type='hidden' name='userName'" +
" value='" + userName + "'>");
out.print("<input type='hidden' name='password'" +
" value='" + password + "'>");
out.print("<input type='submit' value='See Values'>");
out.print("</form>");
out.close();
}else{
out.print("Wrong username or password. <br/><br/>");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);

}
}
}
GetHiddenFieldServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This class is used to get hidden fields values.
* @author javawithease
*/
public class GetHiddenFieldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor.
public GetHiddenFieldServlet() {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//get parameters from request object.
String userName = request.getParameter("userName").trim();
String password = request.getParameter("password").trim();
out.println("Username: " + userName + "<br/><br/>");
out.println("Password: " + password);
out.close();
}
}
login.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<form action="SetHiddenFieldServlet" method="post">
Username:<input type="text" name="userName"/>

<br/><br/>
Password:<input type="password" name="password"/>
<br/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>SetHiddenFieldServlet</servlet-name>
<servlet-class>
com.javawithease.business.SetHiddenFieldServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SetHiddenFieldServlet</servlet-name>
<url-pattern>/SetHiddenFieldServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>GetHiddenFieldServlet</servlet-name>
<servlet-class>
com.javawithease.business.GetHiddenFieldServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetHiddenFieldServlet</servlet-name>
<url-pattern>/GetHiddenFieldServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
Output:

Enter username: jai and password: 1234


Click on login button.

Click on See Values.

Download this example.


URL rewriting in servlet
URL rewriting:
URL rewriting is a way of appending data at the end of URL. Data is appended in name value pair form. Multiple
parameters can be appended in one URL with name value pairs.
Syntax: URL?paramName1=paramValue1& paramName2=paramValue2
How to get parameter value from url in servlet?
HttpServletRequest interfaces getParameter() method is used to get parameter value from url in servlet.
Syntax: String value = request.getParameter(fieldName);
Advantages of URL rewriting:
1.
2.

1. As data is appended in the URL it is easy to debug.


2. It is browser independent.

Disadvantages of URL rewriting:


1.
2.

1. Not secure because data is appended in the URL.


2. Cant append large no. of parameters because URL length is limited.

Session management example using URL rewriting:


SetUrlParameterServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This class is used to set the parameters in the url.
* @author javawithease
*/
public class SetUrlParameterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor.
public SetUrlParameterServlet() {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//get parameters from request object.
String userName = request.getParameter("userName").trim();
String password = request.getParameter("password").trim();
//check for null and empty values.
if(userName == null || userName.equals("") ||
password == null || password.equals("")){
out.print("Please enter both username and " +
"password. <br/><br/>");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);
}//Check for valid username and password.
else if(userName.equals("jai") && password.equals("1234")){
out.println("Logged in successfully.<br/>");
out.println("Click on the below link to see " +
"the values of Username and Password.<br/>");
out.println("<a href='GetUrlParameterServlet?userName="
+userName+"&password="+password+"'>Click here</a>");
}else{
out.print("Wrong username or password. <br/><br/>");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);
}
}
}
GetUrlParameterServlet.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This class is used to get the parameter values from url.
* @author javawithease
*/
public class GetUrlParameterServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor.
public GetUrlParameterServlet() {
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//get parameters from request object.
String userName = request.getParameter("userName").trim();
String password = request.getParameter("password").trim();
out.println("Username: " + userName + "<br/><br/>");
out.println("Password: " + password);
out.close();
}
}
login.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<form action="SetUrlParameterServlet" method="post">
Username:<input type="text" name="userName"/>
<br/><br/>
Password:<input type="password" name="password"/>
<br/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>

web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>SetUrlParameterServlet</servlet-name>
<servlet-class>
com.javawithease.business.SetUrlParameterServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SetUrlParameterServlet</servlet-name>
<url-pattern>/SetUrlParameterServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>GetUrlParameterServlet</servlet-name>
<servlet-class>
com.javawithease.business.GetUrlParameterServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>GetUrlParameterServlet</servlet-name>
<url-pattern>/GetUrlParameterServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
Output:

Enter username: jai and password: 1234

Click on login button.

Click on the link.

Download this example.


HttpSession in servlet
HttpSession:

HttpSession is an interface that provides a way to identify a user in multiple page requests. A unique session id is
given to the user when first request comes. This id is stored in a request parameter or in a cookie.
How to get session object?
HttpServletRequest interfaces getSession() method is used to get the session object.
Syntax: HttpSession session = request.getSession();
How to set attribute in session object?
HttpSession interfaces setAttribute() method is used to set attribute in session object.
Syntax: public void setAttribute(String name,Object value);
Example: session.setAttribute(attName, attValue);
How to get attribute from session object?
HttpSession interfaces getAttribute() method is used to get attribute from session object.
Syntax: public Object getAttribute(String name);
Example: String value = (String) session.getAttribute(attName);
Session management example using HttpSession:
LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* This class is used to set values in session.
* @author javawithease
*/
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor
public LoginServlet() {
}

protected void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//get parameters from request object.
String userName = request.getParameter("userName").trim();
String password = request.getParameter("password").trim();
//check for null and empty values.
if(userName == null || userName.equals("") ||
password == null || password.equals("")){
out.print("Please enter both username " +
"and password. <br/><br/>");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);
}//Check for valid username and password.
else if(userName.equals("jai") && password.equals("1234")){
HttpSession session=request.getSession();
session.setAttribute("userName",userName);
session.setAttribute("password",password);
out.println("Logged in successfully.<br/>");
out.println("Click on the below link to see " +
"the values of Username and Password.<br/>");
out.println("<a href='DisplaySessionValueServlet'>" +
"Click here</a>");
out.close();
}else{
out.print("Wrong username or password. <br/><br/>");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);
}
}
}
DisplaySessionValueServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* This class is used to get values from session.
* @author javawithease
*/
public class DisplaySessionValueServlet extends HttpServlet {
private static final long serialVersionUID = 1L;

//no-argument constructor
public DisplaySessionValueServlet() {
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//get parameters from session object.
HttpSession session=request.getSession(false);
String userName =(String)session.getAttribute("userName");
String password =(String)session.getAttribute("password");
out.println("Username: " + userName + "<br/><br/>");
out.println("Password: " + password);
out.close();
}
}
login.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<form action="LoginServlet" method="post">
Username:<input type="text" name="userName"/>
<br/><br/>
Password:<input type="password" name="password"/>
<br/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<servlet>
<servlet-name>LoginServlet</servlet-name>

<servlet-class>
com.javawithease.business.LoginServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>DisplaySessionValueServlet</servlet-name>
<servlet-class>
com.javawithease.business.DisplaySessionValueServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DisplaySessionValueServlet</servlet-name>
<url-pattern>/DisplaySessionValueServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>
Session management example using HttpSession:

Enter username: jai and password: 1234

Click on login button.

Click on the link.

Download this example.

Servlet filter in java


Servlet filter:
Servlet filters are the objects which are used to perform some filtering task. A filter can be applied to a servlet, jsp or
html.
Servlet filters are mainly used for following tasks:
1.
2.

1. Pre-processing: Servlet filter is used for pre-processing of request before it accesses any resource at
server side.
2. Post-processing: Servlet filter is used for post-processing of response before it sent back to client.

How to create a filter?


Implement javax.servlet.Filter interface to create a filter.
Filter interface:
To create a filter you have to implement filter interface. Filter interface is in javax.servlet package
javax.servlet.Filter. It provides life cycle methods of a filter.
Methods of filter interface:
1. init(FilterConfig config): This method is used to initialize the filter. It is called only once by web container.
Syntax: public void init(FilterConfig config)
2. doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain): This method is
used for performing pre-processing and post-processing tasks. It is called every time for a request/response comes
for a resource to which filter is mapped.
Syntax: public void doFilter(HttpServletRequest request,HttpServletResponse response, FilterChain chain)
3. destroy(): This method is called only once by the web container when filter is taken out of the service.
Syntax: public void destroy()
FilterChain interface:
FilterChain object is used to call the next filter or a resource if it is the last filter in filter chaining.
Method of FilterChain interface:
1. doFilter(HttpServletRequest request, HttpServletResponse response): This method is used to call the next
filter in filter chaining.

Syntax: public void doFilter(HttpServletRequest request, HttpServletResponse response) throws


IOException, ServletException
How to define a filter in web.xml?
<filter> attribute is used to define a filter in web.xml.
Syntax:
<web-app>
//Other attributes.
<filter>
<filter-name>filterName </filter-name>
<filter-class>filterClass</filter-class>
</filter>
<filter-mapping>
<filter-name>filterName</filter-name>
<url-pattern>urlPattern</url-pattern>
</filter-mapping>
//Other attributes.
</web-app>

Example:
LoginFilter.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**

* This class is used as a filter.


* @author javawithease
*/
public class LoginFilter implements Filter {
private static final long serialVersionUID = 1L;
public void init(FilterConfig filterConfig)
throws ServletException {
}
public void doFilter(ServletRequest request,
ServletResponse response, FilterChain chain)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//get parameters from request object.
String userName = request.getParameter("userName").trim();
String password = request.getParameter("password").trim();
//check for null and empty values.
if(userName == null || userName.equals("") ||
password == null || password.equals("")){
out.print("Please enter both username " +
"and password. <br/><br/>");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);
}//Check for valid username and password.
else if(userName.equals("jai") && password.equals("1234")){
chain.doFilter(request, response);
}else{
out.print("Wrong username or password. <br/><br/>");
RequestDispatcher requestDispatcher =
request.getRequestDispatcher("/login.html");
requestDispatcher.include(request, response);
}
}
public void destroy() {
}
}
WelcomeServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* This class is used to print login message
* if user logged in successfully.
*/
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor
public WelcomeServlet() {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<h1>You are logged in successfully.</h1>");
out.close();
}
}
login.html
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01
Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login</title>
</head>
<body>
<form action="WelcomeServlet" method="POST">
Username:<input type="text" name="userName"/>
<br/><br/>
Password:<input type="password" name="password"/>
<br/><br/>
<input type="submit" value="login"/>
</form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<servlet>

<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>
com.javawithease.business.WelcomeServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>
<filter>
<filter-name>LoginFilter</filter-name>
<filter-class>
com.javawithease.business.LoginFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>LoginFilter</filter-name>
<url-pattern>/WelcomeServlet</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>login.html</welcome-file>
</welcome-file-list>
</web-app>

Output:

Enter username: jai and password: 1234

Click on login button.

Download this example.


FilterConfig interface
FilterConfig object is created and used by web container to pass init parameters to a filter during initialization.
Methods of FilterConfig interface:
1. getFilterName(): Returns the name of the filter defined in web.xml.
Syntax: public String getFilterName()

2. getInitParameter(String name): Returns the value of the specified parameter.


Syntax: public String getInitParameter(String name)
3. getInitParameterNames(): Returns the names of all parameters as Enumeration.
Syntax:public Enumeration getInitParameterNames()
4. getServletContext(): Returns the object of ServletContext.
Syntax: public ServletContext getServletContext()
Example:
MyFilter.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
/**
* This class is used as a filter.
* @author javawithease
*/
public class MyFilter implements Filter {
private static final long serialVersionUID = 1L;
private FilterConfig filterConfig;
public void init(FilterConfig filterConfig)
throws ServletException {
this.filterConfig = filterConfig;
}
public void doFilter(ServletRequest request,
ServletResponse response,FilterChain chain)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//get parameters from filterConfig object.
String appUser = filterConfig.getInitParameter("appUser");
if(appUser.equals("jai")){
chain.doFilter(request, response);
}
else {
out.print("Invalid application user.");

}
}
public void destroy() {
}
}
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This class is used to print login
* message if user logged in successfully.
*/
public class WelcomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//no-argument constructor
public WelcomeServlet() {
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<h1>Valid application user.</h1>");
out.close();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<servlet>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>
com.javawithease.business.WelcomeServlet
</servlet-class>
</servlet>
<servlet-mapping>

<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>
com.javawithease.business.MyFilter
</filter-class>
<init-param>
<param-name>appUser</param-name>
<param-value>jai</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/WelcomeServlet</url-pattern>
</filter-mapping>
</web-app>
Output:

Download this example.

Das könnte Ihnen auch gefallen