Beruflich Dokumente
Kultur Dokumente
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.
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
<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.*;
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.
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
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)
//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:
Output:
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:
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:
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:
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:
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:
}
Output:
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:
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:
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:
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() {
}
//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:
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.
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 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:
}
}
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: