[go: up one dir, main page]

0% found this document useful (0 votes)
52 views122 pages

Unit 3 Servlet

The document discusses servlets, which are Java classes that extend the functionality of web servers by dynamically generating web pages. Servlets improve upon earlier technologies like CGI by handling each request with a lightweight Java thread instead of a heavy OS process. This makes servlets more scalable and portable. The servlet lifecycle involves initialization via the init() method, handling requests via the service() and doGet()/doPost() methods, and cleanup via the destroy() method. Servlets offer advantages over CGI like session tracking, handling cookies, and allowing data sharing between servlets.

Uploaded by

rocky170104
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
52 views122 pages

Unit 3 Servlet

The document discusses servlets, which are Java classes that extend the functionality of web servers by dynamically generating web pages. Servlets improve upon earlier technologies like CGI by handling each request with a lightweight Java thread instead of a heavy OS process. This makes servlets more scalable and portable. The servlet lifecycle involves initialization via the init() method, handling requests via the service() and doGet()/doPost() methods, and cleanup via the destroy() method. Servlets offer advantages over CGI like session tracking, handling cookies, and allowing data sharing between servlets.

Uploaded by

rocky170104
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 122

Unit-3

Servlet API and Overview


What is Servlet?
Servlet is java class which extends the functionality of web server by dynamically generating
web pages.
Servlet: Basic Terms
Before looking into Servlet, we will see some important keywords about web application.

Web Client: We will call browsers (IE, Chrome, Mozilla etc.)


as a Client, which helps in communicating with the server
Http Request

Server and Client (browser) will


communicate with each other with the
help of HTTP protocol.

Web Server is the one which takes the Server


Client Http Response client request, process the request and
sends back the response.
Introduction
Servlet technology is used to create Dynamic web application
Servlet technology is robust and scalable .
Before Servlet, CGI (Common Gateway Interface) scripting language was popular as a
server-side programming language, but there were many disadvantages of this technology.

Changes with respect to time

1. To retrive server’s current


DATE and Time
2. News paper clippings
3. Online Shopping
e.g. Virtual Dressing Room
..
.
Why we need Servlet?
Nowadays everything is available on Internet.
Starting from e-banking, e-commerce everything is available through internet. We call all
these applications as Web applications.
Hey Server, I want to display given
name in my web page Sorry, I can’t do
that Dynamic
computation

Hi,
ButIIam Servlet.
have an
Let me help you to
application named
display
SERVLET,given name
which
in
canyour web page.
process your
request

Client Server
Dynamic Response
Scripting Language
Server-Side Client-Side
Scripting Language Scripting Language

PHP JavaScript
ASP.NET VBScript
(C# OR Visual Basic) HTML (Structure)
C++ CSS (Designing)
Java and JSP AJAX
Python jQuery etc.
Ruby on Rails etc.

Client-side scripting is an
Server-side scripting is often
important part of the Dynamic
used to provide a customized
HTML. Usually run on client’s
interface for the user.
browser.
CGI (Common Gateway Interface)
CGI was the 1st server-side scripting technique for creating dynamic content.
CGI is used to execute a program that resides in the server to process data or access
databases to produce the relevant dynamic content.
For each request CGI Server receives, It creates new Operating System Process.

If the number of requests from the client increases then more time it will take to respond to
the request.
As programs executed by CGI Script are written in the native languages such as C, C++, perl
which are not portable.
Comparing Servlet with CGI
CGI programs are used to execute programs written inside the native language.
While in Servlet, all the programs are compiled into the Java bytecode, which is then run in
the Java virtual machine.
In Servlet, all the requests coming from the Client are processed with the threads instead of
the OS process.
Summary: CGI vs Servlet
CGI Servlet
CGI was not portable. Servlets are portable.
In CGI each request is handled by heavy In Servlets each request is handled by
weight OS process. lightweight Java Thread.
Session tracking and caching of previous Session tracking and caching of previous
computations cannot be performed. computations can be performed
CGI cannot handle cookies. Servlets can handle cookies.
CGI does not provide sharing property. Servlets can share data among each other.
CGI is more expensive than Servlets Servlets is inexpensive than CGI.
Servlet Packages
Package javax.servlet
Servlet interface needs to be
Interface
implemented for creating any servlet. It
Servlet provides 3 life cycle methods.

Implemented by
It provides implementation of methods of
GenericServlet Servlet interfaces.
extended by
Contains interface and abstract class for
Class

HttpServlet servlet that understands HTTP protocol.


extended by Package: javax.servlet.http

MyServlet User defined Servlet class.


Servlet Life Cycle

init() destroy()
Servlet
In Service

i. Servlet class is loaded.


ii. Servlet instance is
created.
iii. init() method is service()
invoked.

Servlet Container
Servlet Life Cycle: init()
Servlet class is loaded
The classloader is responsible to load the servlet class. The servlet class is loaded when the first request
for the servlet is received by the web container.
Servlet instance is created
The web container creates the instance of a servlet after loading the servlet class. The servlet instance is
created only once in the servlet life cycle.
Init() method is invoked
The web container calls the init method only once after creating the servlet instance. The init method is
used to initialize the servlet.
Syntax
public void init(ServletConfig config) throws ServletException
{
//initialization…
}
A servlet configuration object used by a servlet
container to pass information to a servlet during
initialization process.
Servlet Life Cycle: Service()
The service() method is the main method to perform the actual task.
The servlet container (i.e. web server) calls the service() method to handle requests coming
from the client( browsers) and to write the response back to the client.
Each time the server receives a request for a servlet, the server spawns a new thread and
calls service.
Syntax
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
{

}
The service() method checks the HTTP request type (GET, POST, PUT, DELETE, etc.) and calls
doGet, doPost, doPut, doDelete, etc. methods as appropriate.
The doGet() and doPost() are most frequently used methods with in each service request.
Servlet Life Cycle: Destroy()
The destroy() method is called only once at the end of the life cycle of a servlet.
This method gives your servlet a chance to close
database connections,
halt background threads,
write cookie lists or hit counts to disk, and
perform other such cleanup activities.
After the destroy() method is called, the servlet object is marked for garbage collection.
Syntax
public void destroy()
{
// Finalization code...
}
Servlet Life Cycle
doGet() v/s doPost()
doGet()
A GET request results from request for a URL or from an HTML form, should be handled by doGet()
method.
Syntax
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code …
}

doPost()
A POST request results from an HTML form that specifically lists POST as the METHOD and it should be
handled by doPost() method.
Syntax
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws ServletException, IOException
{
// Servlet code …
}
doGet() vs doPost()
doGet() doPost()
In this method, parameters are appended to the URL In doPost(), parameters are sent in separate line in the
and sent along with header information body
Maximum size of data that can be sent using doGet() There is no maximum size for data
is 240 bytes
Parameters are not encrypted Parameters are encrypted here
Application: Application:
Used when small amount of insensitive data like a Used when comparatively large amount of sensitive
query has to be sent as a request. data has to be sent.
It is default method. E.g. submitting sign_in or login form.
doGet() is faster comparatively doPost() is slower compared to doGet() since
doPost() does not write the content length
Servlet Life Cycle: Servlet Code
MyServlet.Java
1 import java.io.*;
2 import javax.servlet.*;
3
4 public class MyServlet1 extends GenericServlet
5 {
6 public void init() throws ServletException
7 {//Initailization Code
8 }
9
10 public void service(ServletRequest request,ServletResponse response) throws
11 ServletException,IOException
12 {//Servlet code
13 }
14
15 public void destroy()
16 {//Finalization Code
17 }
18 }
Steps to run Servlet Program in Netbeans
Step 1: Open Netbeans IDE, Select File -> New Project
Steps for Servlet Program
Step 2: Select Java Web -> Web Application, then click on Next
Steps for Servlet Program
Step 3: Give a name to your project and click on Next,
Steps for Servlet Program
Step 4: and then, Click Finish
Steps for Servlet Program

complete directory structure required for the Servlet Application will be created
lly by the IDE.
Steps for Servlet Program
Step 6: To create a Servlet, open Source Package, right click on default
packages -> New -> Servlet.
Steps for Servlet Program
Step 7: Give a Name to your Servlet class file
Steps for Servlet Program

It will add servlet


information to
web.xml file

Web.xml is the
configuration file of
web applications in
java.
Step 8: Write servlet code: MyServlet.java
MyServet1.java
1 import java.io.*;
2 import javax.servlet.*;
3
4 import javax.servlet.http.*;
5 public class MyServlet1 extends HttpServlet
6 { String msg="";
7
PrintWriter out;
8
9 public void init() throws ServletException
10 { msg="hello world: my first servlet program"; }
11
public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException
12
13 {
14 response.setContentType("text/html");
15 out=response.getWriter();
16
17 out.println(msg);
18 }
19 public void destroy()
20
21 { out.close();
22 }
23 }
24
MIME: Multipurpose Internet Mail Extensions
A MIME type nomenclature includes a type and subtype separated by a forward slash.
It is a HTTP header that provides the description about what are you sending to the browser.
text/html
text/plain
text/css
text/richtext
application/msword
application/jar
application/pdf
images/jpeg images/png images/gif
audio/mp3
video/mp4
MIME is a standard set to Internet to notify the format of the file contents.
Steps for Servlet Program
Step 9: open web.xml

Configuration of servlet
using <servlet>

It is used to map
Servlet to
specific URL Map the servlet to a URL. This can be done using
<servlet-mapping> element.
Steps for Servlet Program

Step 11: Run your application, right click on your Project and select Run
Java Servlet

1
2

5
3

Ref: https://www.ntu.edu.sg/home/ehchua/programming/java/JavaServlets.html
javax.servlet Interface

It is used to get configuration


Javax.servlet
information from web.xml file. If the
configuration information is modified
ServletConfig from the web.xml file, we don't need to
change the servlet.

ServletContext It provides an interface between the


container and servlet. It is global to
entire web application

ServletRequest It is used to provide the client request


information to a servlet such as content
type, content length, parameter names
ServletResponse and values, header informations,
attributes
It contains various methods that enable
a servlet to respond to the client
requests. A servlet can send the
response either as character or binary
data.
Types of Servlet
Generic Servlet
javax.servlet (package)
extends javax.servlet.Servlet
service method
service(ServletRequest req, ServletResponse res)

Http Servlet
javax.servlet.http (package)
extends javax.servlet.HttpServlet
doGet(), doPost()
doGet(HttpServletRequest req,HttpServletResponse res)
doPost(HttpServletRequest req,HttpServletResponse res)
GenericServlet vs HttpServlet
GenericServlet HttpServlet
javax.servlet.GenericServlet javax.servlet.http.HttpServlet
It defines a generic, protocol-independent It defines a HTTP protocol specific servlet.
servlet.
GenericServlet is a super class of HttpServlet HttpServlet is a sub class of GenericServlet
class. class.
Can handle all types of protocols only HTTP specific protocols.
It supports only one abstract method:service() It support doGet(), doPost() etc.
Deployment Descriptor
Located @ WEB-INF directory
File known as web.xml
It controls the behavior of Java Servlet
What does it contain?
XML Header
DOCTYPE
Web-app element
The Web-app element should contain a servlet element with 3 sub-element.
▪ <servlet-name>: name used to access java servlet
▪ <servlet-class>: class name of java servlet
▪ <init-param>: for initialization parameter
Deployment Descriptor: web.xml
<?xml version="1.0" encoding="UTF-8"?>
xml header
<!DOCTYPE web-app

PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"

"http://java.sun.com/dtd/web-app_2_3.dtd"> Document Type Definition


<web-app>

<servlet> Configures a web application.


<servlet-name>MyServlet</servlet-name>
Name used to access
<servlet-class>MyServlet</servlet-class>
Java Servlet
<init-param>

<param-name>name</param-name> Name of servlet .java


<param-value>cxcy</param-value> class
</init-param>

</servlet>
Used to pass parameters to a servlet from the web.xml file.
<servlet-mapping>
map the servlet to a URL
<servlet-name>MyServlet</servlet-name> or URL pattern
<url-pattern>/MyServlet</url-pattern>

</servlet-mapping> Controls behavior of


</web-app>
Servlet
Program to call servlet from html file
Write a java Servlet program to call servlet from html hyperlink.
2.html
1 <html>
2 <head>
3 <title> HyperLinkDemo </title>
4 </head>
5 <body>
6 <a href ="/ServletDemo2/HyperLinkDemo">HyperLinkDemo.java </a>
7 </body>
8 </html>
Servlet Program: HyperLinkDemo.java
HyperLinkDemo.java
1 import javax.servlet.*;
2 import javax.servlet.http.*;
3 import java.io.*;
4 public class HyperLinkDemo extends HttpServlet
5 { String msg="";
6 PrintWriter out;
7 public void init(ServletConfig config)throws ServletException
8 { msg="hello world! MY first Servlet Program...";
9 }
10 public void doGet(HttpServletRequest request,HttpServletResponse
11 response) throws ServletException,IOException
12 { response.setContentType("text/html");
13 out=response.getWriter();
14 out.println("<h1>"+msg+"</h1>");
15 }
16 public void destroy()
17 { out.close();
18 }
19 }
doGet()
1.html
1 <html>
2 <head>
3 <title> DoGetDemo </title>
4 </head>
5 <body>
6 <form action="/ServletDemo2/DoGetDemo">
7 Enter Email:<input type="text" name="email">
8 <p><input type="submit"></p>
9 </form>
10 </body>
11 </html>
doGet()
DoGetDemo.java
1 import javax.servlet.*;
2 import javax.servlet.http.*;
3 import java.io.*;
4 public class DoGetDemo extends HttpServlet
5 { PrintWriter out;
6 public void init(ServletConfig config)throws ServletException
7 {
8 }
9 public void doGet(HttpServletRequest request,HttpServletResponse response)throws
10 ServletException,IOException
11 {
12 String email=request.getParameter("email");
13 response.setContentType("text/html");
14 out =response.getWriter();
15 out.println("my email:"+email); String getParameter(String name)
16 }
Returns the value of a request
17 public void destroy()
18 { out.close();
parameter as a String
19 }
20 }
doPost()
Write a Servlet program to enter two numbers and find maximum among them.
max.html
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title> Maximum number </title>
5 </head>
6 <body>
7 <form action="/ServletTemp/Max" method="POST" >
8 <p>Enter No-1:<input type="text" name="no1"></p>
9 <p>Enter No-2:<input type="text" name="no2"></p>
10 <p><input type="submit"></p>
11 </form>
12 </body>
13 </html>
doPost()
Max.java
1 import java.io.*;
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 public class Max extends HttpServlet
5 {
6 public void doPost(HttpServletRequest request, HttpServletResponse response)throws
7 ServletException,IOException
8 { int n1=0,n2=0;
9 response.setContentType("text/html");
10 PrintWriter out=response.getWriter();
11 n1=Integer.parseInt(request.getParameter("no1"));
12 n2=Integer.parseInt(request.getParameter("no2"));
13 if(n1>n2)
14 out.println("n1="+n1+"is max number");
15 else if(n2>n1)
16 out.println("n2="+n2+"is max number");
17 else if(n1==n2)
18 out.println("n1= "+n1+"and n2= "+n2+"are equal numbers");
19 }
20 }

Using doPost()
ServletConfig Interface
It is used to get configuration information from web.xml file.
If the configuration information is modified from the web.xml file, we don't need to change
the servlet.
Method :
String getInitParameter(String name) Returns the parameter value for the specified parameter name.

Example

String str = config.getInitParameter("name")

web.xml
<init-param>
<param-name>name</param-name>
Servlet Config: web.xml
<web-app>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>MyServlet</servlet-class>
<init-param>
The name attribute is used together with the value attribute
<param-name>name</param-name> to specify parameters for the plugin specified with the
<object> tag.
<param-value>cxcy</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>MyServlet</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
</web-app>
Servlet Config: MyServlet.java
MyServlet.java
1 import javax.servlet.*;
2 import javax.servlet.http.*;
3 import java.io.*;
4 public class MyServlet extends HttpServlet
5 { String msg;
6 PrintWriter out;
7 public void init(ServletConfig config)throws ServletException
8 {
9 msg = config.getInitParameter("name");
10 } <param-value>
11 public void doGet(HttpServletRequest request , HttpServletResponse response) throws
12 ServletException,IOException
13 { response.setContentType("text/html");
14 out = response.getWriter();
15 out.println("<h1>"+ msg +"</h1>");
16 }
17 public void destroy()
18 { out.close();
19 }
20 }
ServletContext Interface
ServletContext is created by the web container at time of deploying the project.
It can be used to get configuration information from web.xml file.
There is only one ServletContext object per web application.
If any information is shared to many servlet, it is better to provide it from the web.xml file
using the <context-param> element.
<web-app>
...
<context-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</context-param>
...
<servlet> used to define
... initialization parameter in
</servlet>
the application scope.

</web-app>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>ServletContextDemo</servlet-name>
<servlet-class>ServletContextDemo</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ServletContextDemo</servlet-name>
<url-pattern>/ServletContextDemo</url-pattern>
</servlet-mapping>
<context-param>
<param-name>name</param-name>
<param-value>DIET</param-value>
</context-param>
</web-app>
ServletContextDemo.java
ServletContextDemo.java
1 import java.io.*;
2 import javax.servlet.*;
3 import javax.servlet.http.*;
4 public class ServletContextDemo extends HttpServlet
5 {
6 public void doGet(HttpServletRequest req,HttpServletResponse res) throws
7 ServletException,IOException
8 { res.setContentType("text/html");
9 PrintWriter out=res.getWriter();
10 //creating ServletContext object
11 ServletContext context=getServletContext();
12 //Getting the value of the initialization parameter and printing it
13 String college=context.getInitParameter("name");
14 out.println("College name is="+college);
15 out.close();
16 }
17 }
Servlet Config vs Servlet Context
Servlet Config Servlet Context
ServletConfig object is one per servlet class ServletContext object is global to entire web
application
Object of ServletConfig will be created during Object of ServletContext will be created at the time of
initialization process of the servlet web application deployment
Scope: As long as a servlet is executing, ServletConfig Scope: As long as web application is executing,
object will be available, it will be destroyed once the ServletContext object will be available, and it will be
servlet execution is completed. destroyed once the application is removed from the
server.
We should give request explicitly, in order to create ServletContext object will be available even before
ServletConfig object for the first time giving the first request
In web.xml – <init-param> tag will be appear under In web.xml – <context-param> tag will be appear under
<servlet-class> tag <web-app> tag
HttpServletRequest: Methods
String getContextPath() Returns the portion of the request URI that indicates the context of the request.

getContextPath
1 public void doGet(HttpServletRequest request, HttpServletResponse response)
2 {
3 out.println("<p>request.getContextPath():" +request.getContextPath()+"</p>");
4 }

Output
request.getContextPath():/ServletTemp
HttpServletRequest: Methods
Enumeration getHeaderNames() Returns an enumeration of all the header names this request contains.
getHeaderNames
1 public void doGet(HttpServletRequest request,HttpServletResponse response)
2 {
3 Enumeration h=request.getHeaderNames();
4 while(h.hasMoreElements())
5 {
6 String paramName = (String)h.nextElement();
7 out.print("<p>" + paramName + "\t");
8 String paramValue = request.getHeader(paramName);
9 out.println( paramValue + "</p>\n");
10 }
11 }

Output
host localhost:8080
user-agent Mozilla/5.0 (Windows NT 6.2; WOW64;rv:50.0) Gecko/20100101 Firefox/50.0
accept text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
accept-language en-US,en;q=0.5
accept-encoding gzip, deflate
connection keep-alive
upgrade-insecure-requests 1
HttpServletRequest: Methods
String getHeader(String name) Returns the value of the specified request header as a String.

getHeader
1 public void doGet(HttpServletRequest request,HttpServletResponse response)
2 {
3 out.println("<p>request.getHeader(): " +request.getHeader("host")+"</p>");
4 out.println("<p>request.getHeader(): " +request.getHeader("referer")+"</p>");
5 }

Output
request.getHeader():host=localhost:8080
request.getHeader():referer=http://localhost:8080/ServletTemp/servletmeth.html
HttpServletRequest: Methods
String getQueryString() Returns the query string that is contained in the request URL after the path.

getQueryString
1 public void doGet(HttpServletRequest request,HttpServletResponse response)
2 {
3 out.println("<p>request.getQueryString():" +request.getQueryString()+"</p>");
4
5 }

Output
requrest.getQueryString(): no1=1&no2=2
HttpServletRequest: Methods
String getServletPath() Returns the part of this request's URL that calls the servlet. This path starts with a "/"
character and includes either the servlet name or a path to the servlet

getServletPath
1 public void doGet(HttpServletRequest request, HttpServletResponse response)
2 {
3 out.println("<p>request.getServletPath():" +request.getServletPath()+"</p>");
4 }

Output
request.getServletPath(): /ServletMeth
HttpServletRequest: Methods
String getMethod() Returns the name of the HTTP method with which this request was made, for example GET
or POST

getServletPath
1 public void doGet(HttpServletRequest request, HttpServletResponse response)
2 {
3 out.println("<p>request.getMethod():"+request.getMethod()+"</p>");
4 }

Output
request.getMethod(): GET
javax.servlet.RequestDispatcher Interface
The RequestDispatcher interface provides the facility of dispatching the request to another
resource.
Resource can be HTML, Servlet or JSP.
This interface can also be used to include the content of another resource.
It is one of the way of servlet collaboration.
void forward(ServletRequest request, Forwards a request from a servlet to another resource
ServletResponse response) (servlet, JSP file, or HTML file) on the server.
throws ServletException, IOException
void include(ServletRequest request, Includes the content of a resource (Servlet, JSP page,
ServletResponse response) or HTML file) in the response.
throws ServletException, IOException
RequestDispatcher: forward()
Step2:
forward(req, res)
e s t Servlet 1 Servlet 2
e qu
p 1 :R
Ste

Step 3:
Response Response is
generated

Web Client
Step 4: R
esponse
is sent b
ack to br Response
owser
RequestDispatcher: include()
Step2: include(req, res)

u est Servlet 1 Servlet 2


R e q
te p1: Step3:
S
Response of Servlet 2
is included in the
Response of Servlet 1 Response

Web Client

Final
R
back esponse Response
t i
Serv o the clie s sent
let 1 nt fro
n
How to get the object of RequestDispatcher?
The getRequestDispatcher() method of ServletRequest interface returns the object of
RequestDispatcher.

Syntax
1 RequestDispatcher getRequestDispatcher(String resource)

Name of Servlet specified in <url-pattern>


Example
1 RequestDispatcher rd=request.getRequestDispatcher("servlet2");
RequestDispatcher: forward() and include()
Forward()
1 RequestDispatcher rd = request.getRequestDispatcher("servlet2");
2 rd.forward(request, response);

Forward()
1 RequestDispatcher rd = request.getRequestDispatcher("/1.html");
2 rd.forward(request, response);

Include()
1 RequestDispatcher rd = request.getRequestDispatcher("servlet2");
2 rd.include(request, response);
Include()
1 RequestDispatcher rd = request.getRequestDispatcher("/1.html");
2 rd.include(request, response);
RequestDispatcher: Servlet Program

Validate Servlet
[CallServlet.java]

Ye IsValid No
s ?
[include: 1.html]
[forward: FwdDemo.java]
RequestDispatcher: 1.html
1.html
1 <html>
2 <head>
3 <title>1.html</title>
4 </head>
5 <body>
6 <form action="/Dispatcher/CallServlet” method="POST">
7 <p>Login ID:<input type="text" name="login"></p>
8 <p>Password:<input type="text" name="pwd"></p>
9 <p><input type="submit" value="Sign In"></p>
10 </form>
11 </body>
12 </html>
RequestDispatcher: Validate Servlet
callServlet.java
1 public class CallServlet extends HttpServlet
2 {
3 public void doPost(HttpServletRequest request, HttpServletResponse response)
4 throws ServletException,IOException
5 { response.setContentType("text/html");
6 PrintWriter out=response.getWriter();
7 RequestDispatcher rd;
8 String login=request.getParameter("login");
9 String pwd=request.getParameter("pwd");
10 if(login.equals("java") && pwd.equals("servlet"))
11 { rd=request.getRequestDispatcher("FwdDemo");
12 rd.forward(request, response);}//if
13 else
14 { out.println("<p><h1>Incorrect Login Id/Password </h1></p>");
15 rd=request.getRequestDispatcher("/1.html");
16 rd.include(request, response);
17 }
18 }
19 //dopost
20 }
RequestDispatcher: fwdDemo.java
fwdDemo.java
1 import javax.servlet.*;
2 import javax.servlet.http.*;
3 import java.io.*;
4 public class FwdDemo extends HttpServlet{
5 public void doPost(HttpServletRequest request,HttpServletResponse response)
6 throws ServletException,IOException
7 { response.setContentType("text/html");
8 PrintWriter out=response.getWriter();
9 String username=request.getParameter("login");
10 out.println("<h1>"+"Welcome "+username+"</h1>");
11 }
12 }
13
RequestDispatcher: web.xml
web.xml
1 <web-app>
2 <servlet>
3 <servlet-name>FwdDemo</servlet-name>
4 <servlet-class>FwdDemo</servlet-class>
5 </servlet>
6 <servlet>
7 <servlet-name>CallServlet</servlet-name>
8 <servlet-class>CallServlet</servlet-class>
9 </servlet>
10
11 <servlet-mapping>
12 <servlet-name>FwdDemo</servlet-name>
13 <url-pattern>/FwdDemo</url-pattern>
14 </servlet-mapping>
15 <servlet-mapping>
16 <servlet-name>CallServlet</servlet-name>
17 <url-pattern>/CallServlet</url-pattern>
18 </servlet-mapping>
19 </web-app>
SendRedirect
The sendRedirect() method of HttpServletResponse interface can be used to redirect
response to another resource, it may be servlet, jsp or html file.
Syntax
1 void sendRedirect(String location) throws IOException

Example
1 response.sendRedirect("http://www.darshan.ac.in");
2 response.sendRedirect("/1.html");//relative path
3 response.sendRedirect("http://localhost:8080/1.html"); //absolute path
sendRedirect(): Example
Example
1 public class Redirect extends HttpServlet
2 {
3 public void doGet( HttpServletRequest request, HttpServletResponse response)
4 throws ServletException,IOException
5 { response.setContentType("text/html");
6 PrintWriter out=response.getWriter();
7 String login=request.getParameter("login");
8 String pwd=request.getParameter("pwd");
9 if(login.equals("java") && pwd.equals("servlet"))
10 {
11 response.sendRedirect("/Dispatcher/Welcome");
12 }
13 else
14 {
15 response.sendRedirect("/Dispatcher/redirect.html");
16 }
17 } //doGet
18 }
forward() vs sendRedirect()
forward() sendRedirect()
The forward() method works at server side. The sendRedirect() method works at client side.
It sends the same request and response objects to It always sends a new request.
another servlet.
It can work within the server only. It can be used within and outside the server.
original URL not change. Here browser knows that it's making a new request, so
original URL changes.
Example: request.getRequestD Example:
ispacher("servlet2").forward(request,response); response.sendRedirect("servlet2");
Session Management in Servlets
A session refers to the entire interaction between a client and a server from the time of the
client’s first request,which generally begins the session, to the time of last request/response.
Why we require Session?
HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a
separate connection to the Web server and the server automatically does not keep any record of previous
client request.
Session is required to keep track of users and their information.
1. Request (New)
2. Response
Client Server
3.Second Request (New)

When a User logs into your website, no matter on which web page he visits after logging in,
his credentials will be with the server, until user logs out.
So this is managed by creating a session.
Session Management
Session Management is a mechanism used by the Web container to store session
information for a particular user.
There are four different techniques for session management.

Session Management
Hidden form field

URL Rewriting

Cookies

HttpSession
Session Management: Hidden form field
Hidden Form Field, a hidden (invisible) textfield is used for maintaining the state of an user.
In such case, we store the information in the hidden field and get it from another servlet.

Example
1 <input type="hidden" name="session_id" value="054">
Session Management: Hidden form field
login.html Valid.java

request.getParameter(“name”);
Name:
request.getParameter(“password”);
Password:
request.getParameter(“session”);
`
Session_ID: 054
Submit Hidden Field

Welcome.java

request.getParameter(“session”);
Session Management: Hidden form field
login.html
1 <html>
2 <head>
3 <title>login</title>
4 </head>
5 <body>
6 <form action="/Session/Valid" method="POST">
7 <p>Login ID:<input type="text" name="login"></p>
8 <p>Password:<input type="text" name="pwd"></p>
9 <p><input type="hidden" name="session_id" value="054"></p>
10 <p><input type="submit" value="Sign In"></p>
11 </form>
12 </body>
13 </html>
Session Management: Hidden form field
Valid.java
1 public class Valid extends HttpServlet
2 { public void doPost(HttpServletRequest request, HttpServletResponse
3 response) throws ServletException,IOException
4 {
5 response.setContentType("text/html");
6 PrintWriter out=response.getWriter();
7 RequestDispatcher rd; Hidden Field
8 String login=request.getParameter("login");
9 String pwd=request.getParameter("pwd");
10 String session=request.getParameter("session_id");
11 if(login.equals("java") && pwd.equals("servlet"))
12 {
13 rd=request.getRequestDispatcher("Welcome");
14 rd.forward(request, response);
15 }//if
16 else
17 {
18 out.println("<p><h1>Incorrect LoginId/Password </h1></p>");
19 rd=request.getRequestDispatcher("/login.html");
20 rd.include(request, response);
21 }//else
22 }
23 }
Session Management: Hidden form field
Welcome.java
1 import javax.servlet.*;
2 import javax.servlet.http.*;
3 import java.io.*;
4 public class Welcome extends HttpServlet
5 { public void doPost(HttpServletRequest request, HttpServletResponse response)
6 throws ServletException,IOException
7 { response.setContentType("text/html");
8 PrintWriter out=response.getWriter();
9 String session=request.getParameter("session_id");
10 String username=request.getParameter("login");
11 out.println("<h1>"+"id:"+session+"</h1>");
12 out.println("<h3>"+"Welcome "+username+"</h3>");
13 }
14 }
15
Session Management: Hidden form field
Real application of hidden form field
It is widely used in comment form of a website.
In such case, we store page id or page name in the hidden field so that each page can be uniquely
identified.

Advantage of Hidden Form Field


Easy to implement
It will always work whether cookie is disabled or not.

Disadvantage of Hidden Form Field


It is maintained at server side.
Extra form submission is required on each pages.
Only textual information can be used.
It does not support hyperlink submission.
Security
▪ Hidden field will be visible with GET method
▪ User might view page source and can view hidden field
Session Management: URL Rewriting
In URL rewriting, a token or identifier is appended to the URL of the next Servlet or the next
resource.
We can send parameter name/value pairs using the following format:

URL ? Name1 = value1 & name2 = value2 &…

A name and a value is


name/value pair is separated from another
separated using an
parameter using the ampersand(&)
equal (=) sign

When the user clicks the hyperlink, the parameter name/value pairs will be passed to the
server.
From a Servlet, we can use getParameter() method to obtain a parameter value.
Session Management: URL Rewriting
Url1.java
1 import javax.servlet.*;
2 import javax.servlet.http.*;
3 import java.io.*;
4 public class Url1 extends HttpServlet
5 {
6 public void doGet(HttpServletRequest request, HttpServletResponse response)
7 throws ServletException,IOException
8 {
9 String url;
10 response.setContentType("text/html");
11 PrintWriter out=response.getWriter();
12 //for URL rewriting
13 url= "http://localhost:8080/Session/Url2?s_id1=054&s_id2=055";
14 out.println("<a href="+url+">next page</a>");
15 }
16 }
Session Management: URL Rewriting
Url2.java
1 import javax.servlet.*;
2 import javax.servlet.http.*;
3 import java.io.*;
4 public class Url2 extends HttpServlet
5 { public void doGet(HttpServletRequest request, HttpServletResponse response)
6 throws ServletException,IOException
7 { response.setContentType("text/html");
8 PrintWriter out=response.getWriter();
9 String session1=request.getParameter("s_id1");
10 String session2=request.getParameter("s_id2");
11 out.println("<h3>"+"id:"+session1+"</h3>");
12 out.println("<h3>"+"id:"+session2+"</h3>");
13 }
14 }
15
Session Management: URL Rewriting
Advantage of URL Rewriting
It will always work whether cookie is disabled or not (browser independent).
Extra form submission is not required on each pages.
Disadvantage of URL Rewriting

It will work only with links.


It can send only textual information.
URL header size constraint.
Security
▪ name/value field will be visible with URL followed by ‘?’.
Session Management: Cookies
A cookie is a small piece of information that is persisted between the multiple client
requests.
A cookie has a
Name
Single value
Optional attributes such as
▪ comment
▪ path
▪ domain qualifiers
▪ a maximum age
▪ version number
Session Management: Cookies
By default, each
request is considered
as a new request
1. Request

Server will add cookie with


response from the servlet

2. Response + Cookie

After that if request is sent by


Web Client the user, cookie is added with
request by default.
Thus, we recognize the user as Server
So cookie is the old user.
stored in the
cache of the
3. Request + Cookie
browser.
Session Management: Cookies
Types of Cookie

Non-persistent cookie Persistent cookie

• It is valid for single • It is valid for multiple session .


session only. • It is not removed each time when
• It is removed each time when user closes the browser.
user closes the browser. • It is removed only if user logout
or signout.
Session Management: Cookies
Cookie class
javax.servlet.http.Cookie
This class provides the functionality of using cookies.
It provides a lots of useful methods for cookies.
Constructor

Cookie(String name, String value) constructs a cookie with a specified name and value.

Example
1 Cookie c= new Cookie("session_id","054");
Session Management: Cookies : Methods
void setMaxAge(int expiry) Sets the maximum age in seconds for this Cookie
int getMaxAge() Gets the maximum age in seconds of this Cookie.
By default, -1 is returned, which indicates that the cookie will persist until browser
shutdown.
String getName() Returns the name of the cookie. The name cannot be changed after creation.
void setValue(String newValue) Assigns a new value to this Cookie.
String getValue() Gets the current value of this Cookie.
void addCookie(Cookie cookie) Method of HttpServletResponse interface is used to add cookie in response
object.

Cookie[] getCookies() Returns an array containing all of the Cookie objects the client sent with this
request. This method returns null if no cookies were sent.
Session Management: Cookies
How to create Cookie?
Example
1 //creating cookie object
2 Cookie c= new Cookie("session_id","054");
3 //adding cookie in the response
4 response.addCookie(c);

How to retrieve Cookies?


Example
1 Cookie c[]=request.getCookies();
2 for(int i=0;i<c.length;i++)
3 {
4 out.print(c[i].getName()+””+c[i].getValue());
5 //printing name&value of cookie
6 }
Session Management: Cookies
How to delete Cookie?
Read an already existing cookie and store it in Cookie object.
Set cookie age as zero using setMaxAge() method to delete an existing cookie
Add this cookie back into response header.

Example
1 //deleting value of cookie
2 Cookie c = new Cookie("user","");
3 //changing the maximum age to 0 seconds
4 c.setMaxAge(0);
5 //adding cookie in the response
6 response.addCookie(c);
Session Management: Cookies
Cookie.html

Cookie1.java

Add Cookie

Cookie2.java
Cookie3.java
Retrieve Cookie
Retrieve All Cookies Add Another Cookie
Session Management: Cookies
cookie.html
1 <html>
2 <head>
3 <title>cookie</title>
4 </head>
5 <body>
6 <form action="/Session/Cookie1" >
7 <p>Login ID:<input type="text" name="login"></p>
8 <p>Password:<input type="password" name="pwd"></p>
9 <p><input type="submit" value="Sign In"></p>
10 </form>
11 </body>
12 </html>
Session Management: Cookies
cookie1.java
1 public class Cookie1 extends HttpServlet
2 { public void doGet(HttpServletRequest request, HttpServletResponse response)
3 throws ServletException,IOException
4 { response.setContentType("text/html");
5 PrintWriter out=response.getWriter();
6 String login=request.getParameter("login");
7 String pwd=request.getParameter("pwd");
8 if(login.equals("java") && pwd.equals("servlet"))
9 {
10 Cookie c = new Cookie("c1",login);//create cookie
11 response.addCookie(c);//adds cookie with response
12 out.println("Cookie named:"+c.getName()+" added");
13 String path="/Session/Cookie2";
14 out.println("<p><a href="+path+">next page</a></p>");
15 }
16 else { //Redirect page to cookie.html}
17 } }
Session Management: Cookies
cookie2.java
1 public class Cookie2 extends HttpServlet
2 { public void doGet(HttpServletRequest request, HttpServletResponse response) throws
3 ServletException,IOException
4 { response.setContentType("text/html");
5 PrintWriter out=response.getWriter();
6 Cookie c[]=request.getCookies();
7 out.println("c.length="+c.length);
8 for(int i=0;i<c.length;i++)
9 { out.println("CookieName="+c[i].getName()+
10 "CookieValue="+c[i].getValue());
11 }
12 //to add another cookie
13 Cookie c1 = new Cookie("c2","054");
14 response.addCookie(c1);
15 String path="/Session/Cookie3";
16 out.println("<a href="+path+">next page</a>");
17 }
18 }
Session Management: Cookies
cookie3.java
1 public class Cookie3 extends HttpServlet
2 { public void doGet(HttpServletRequest request, HttpServletResponse response)
3 throws ServletException,IOException
4 { response.setContentType("text/html");
5 PrintWriter out=response.getWriter();
6 Cookie c[]=request.getCookies();
7 for(int i=0;i<c.length;i++)
8 { out.println("<p>");
9 out.println("CookieName="+c[i].getName()+
10 "CookieValue="+c[i].getValue());
11 out.println("</p>");
12 }
13 }
14 }
15
Session Management: Cookies
? Advantage of Cookies
Simplest technique of maintaining the state.
Cookies are maintained at client side.
? Disadvantage of Cookies
It will not work if cookie is disabled from the browser.
Only textual information can be set in Cookie object.
Session Management : HttpSession
Apart from the above mentioned three ways, servlet provides HttpSession Interface which
provides a way to identify a user across more than one page request
The container creates a session id for each user.
The container uses this id to identify the particular user.
An object of HttpSession can be used to perform two tasks:
Bind objects
View and manipulate information about a session, such as the session identifier, creation time, and last
accessed time.
Session Management : HttpSession
Server

Web Container

Request
Client1 id=054 Session1
id= 054
Servlet
Session2
Request id= 055
Client2
id=055

Working of HttpSession
Session Management :HttpSession
Package: javax.servlet.http.HttpSession
The servlet container uses this interface to create a session between an HTTP client and an
HTTP server.
In this technique create a session object at server side for each client.
Session is available until the session time out, until the client log out.
The default session time is 30 minutes and can configure explicit session time in web.xml file.
The HttpServletRequest interface provides two methods to get the object of HttpSession
HttpSession getSession() Returns the current session associated with this request, or if the request does
not have a session, creates one.

HttpSession Returns the current HttpSession associated with this request or, if there is no
getSession(boolean create) current session and create is true then it will returns a new session.
Session Management : HttpSession
String getId() Returns a string containing the unique identifier value.
long getCreationTime() Returns the time when this session was created, measured in milliseconds.
long getLastAccessedTime() Returns the last time the client sent a request associated with this session, as the
number of milliseconds.
void invalidate() Invalidates this session then unbinds any objects bound to it.
Session Management : HttpSession
How to create the session?
1 HttpSession hs=request.getSession();
2 hs.setAttribute("s_id", "diet054");

How to retrieve a session?


1 HttpSession hs=request.getSession(false);
2 String n=(String)hs.getAttribute("s_id");

How to invalidate a session?


1 hs.invalidate();
Session Management : HttpSession

Httpsession.html HSession1.java
[Login page] [Create Session]

HSession2.java
[Retrieve Session]

HSession4.java
[Logout]
Session Management : HttpSession
Httpsession.html
1 <html>
2 <head>
3 <title>HttpSession</title>
4 </head>
5 <body>
6 <form action="/Session/HSession1" method="Get">
7 <p>Login ID:<input type="text" name="login"></p>
8 <p><input type="submit" value="Sign In"></p>
9 </form>
10 </body>
11 </html>
12
Session Management : HttpSession
HSession1.java
1 response.setContentType("text/html");
2 PrintWriter out=response.getWriter();
3 RequestDispatcher rd;
4 String login=request.getParameter("login");
5 if(login.equals("java") )
6 { HttpSession hs=request.getSession();
7 hs.setAttribute("s_id",login);//set HttpSession
8 out.println("Session Created");
9 out.print("<a href='HSession2'>Homepage</a>");
10 }
11 else
12 { out.println("<p><h1>Incorrect Login Id/Password
13 </h1></p>");
14 rd=request.getRequestDispatcher("/httpsession.html");
15 rd.include(request, response);
16 }
Session Management : HttpSession
HSession2.java
1 public class HSession2 extends HttpServlet
2 { public void doGet(HttpServletRequest request, HttpServletResponse response)
3 throws ServletException,IOException
4 {
5 response.setContentType("text/html");
6 PrintWriter out=response.getWriter();
7 HttpSession hs=request.getSession(false);
8 String n=(String)hs.getAttribute("s_id");
9 out.print("Hello "+n);
10 out.print("<p><a hef='HSession3’>Logout</a></p>");
11 }
12 }
13
Session Management : HttpSession
HSession3.java
1 public class HSession3 extends HttpServlet
2 { public void doGet(HttpServletRequest request, HttpServletResponse response)
3 throws ServletException,IOException
4 {
5 response.setContentType("text/html");
6 PrintWriter out=response.getWriter();
7 HttpSession hs=request.getSession(false);
8 hs.invalidate();// Session Invalidated
9 try
10 {
11 String n=(String)hs.getAttribute("s_id");
12 }
13 catch(Exception ne)
14 {
15 out.println("Session Invalidated");
16 }
17 out.println("<form action='/Session/httpsession.html'>");
18 out.println("<p><input type='submit’ value=‘Login'></p></form>");
19 }
20 }
Session Timeout
The session timeout in a web application can be configured in two ways
Timeout in the deployment descriptor (web.xml)
Timeout with setMaxInactiveInterval()
Timeout in the deployment descriptor (web.xml)
1 <web-app>
2 <session-config>
3 <session-timeout> 10 </session-timeout>
4 </session-config>
5 </web-app> Here specified
time is in
minutes
Timeout with setMaxInactiveInterval()
1 HttpSession session = request.getSession();
2 session.setMaxInactiveInterval(10*60);

Here specified time


is in seconds
Filter API
Web Container

Filter

request Filter request

Servlet Program
Filter response response

WebClient
Filter
Filter is used for pre-processing of requests and post-processing of responses.
Filters are configured in the deployment descriptor of a web application.
Usage of Filter
Recording all incoming requests
Logs the IP addresses of the computers from which the requests originate
Conversion
Data compression
Encryption and Decryption
Input validation etc.
Filter API
The javax.servlet package contains the three interfaces of Filter API.
Filter
FilterChain
FilterConfig
Filter Interface
For creating any filter, you must implement the Filter interface.
Filter interface provides the life cycle methods for a filter.
Method
void init(FilterConfig config) init() method is invoked only once. It is used to initialize the filter.
void doFilter doFilter() method is invoked every time when user request to any resource,
(HttpServletRequest request, to which the filter is mapped.It is used to perform filtering tasks.
HttpServletResponse response, FilterChain
chain)
void destroy() This is invoked only once when filter is taken out of the service.
Filter Interface
Methods
1 public void init(FilterConfig config) throws ServletException {…}
2
3 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
4
5 throws IOException,ServletException
6 {
7 //filter logic…
8 }
9
10 public void destroy() {…}
FilterChain interface
The object of FilterChain is responsible to invoke the next filter or resource in the chain.
This object is passed in the doFilter method of Filter interface.
The FilterChain interface contains only one method:
void doFilter It passes the control to the next filter or resource.
(HttpServletRequest request,
HttpServletResponse response)

Example
1 FilterChain chain;
2 chain.doFilter(req, resp);//send request to next resource
Filter Example
Web Container

Filter1.java

FilteredServlet.java

request Filter request

Servlet Program
Filter response response

WebClient
Filter Example: index.html
index.html
1 <html>
2 <head>
3 <title>Filter</title>
4 </head>
5 <body>
6 <a href="FilteredServlet">click here</a>
7 </body>
8 </html>
9
Filter Example
Web.xml
1 <web-app>
2 <servlet>
3 <servlet-name>FilteredServlet</servlet-name>
4 <servlet-class>FilteredServlet</servlet-class>
5 </servlet>
6 <servlet-mapping>
7 <servlet-name>FilteredServlet</servlet-name>
8 <url-pattern>/FilteredServlet</url-pattern>
9 </servlet-mapping>
10
11 <filter>
12 <filter-name>f1</filter-name>
13 <filter-class>Filter1</filter-class>
14 </filter>
15 <filter-mapping>
16 <filter-name>f1</filter-name>
17 <url-pattern>/FilteredServlet</url-pattern>
18 </filter-mapping>
Filter Example: Filter1.java
Filter1.java
1 public class Filter1 implements Filter
2 {
3 public void init(FilterConfig arg0) throws ServletException {//overridden init() method}
4
5 public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain)
6 throws IOException, ServletException
7 {
8 PrintWriter out=resp.getWriter();
9 out.print("filter is invoked before");//exe. with request
10 chain.doFilter(req, resp);//send request to nextresource
11 out.print("filter is invoked after");//exe. with response
12 }
13 public void destroy() {//overridden destroy() method}
14 }
Filter Example: FilteredServlet.java
FilterServlet.java
1 import java.io.IOException;
2 import java.io.PrintWriter;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 public class FilteredServlet extends HttpServlet
6 {
7 public void doGet(HttpServletRequest request, HttpServletResponse response)
8 throws ServletException, IOException
9 {
10 response.setContentType("text/html");
11 PrintWriter out = response.getWriter();
12 out.println("<br>welcome to servlet<br>");
13 }
14 }

Filter1.java [executed with request]


FilteredServlet.java [Servlet code]
Filter1.java [executed with response]
Filter Example-2
Web Container

Filter1.java Filter2.java

FilteredServlet.java

Servlet Program

WebClient

Authenticate User Check config parameter


Filter Example-2
index.html
1 <html>
2 <head>
3 <title>filter</title>
4 </head>
5 <body>
6 <form action="/Filter/FilteredServlet" >
7 <p>Login ID:<input type="text" name="login"></p>
8 <p>Password:<input type="password" name="pwd"></p>
9 <p><input type="submit" value="Sign In"></p>
10 </form>
11 </body>
12 </html>
Filter Example-2
Web.xml Web.xml
1 <web-app> 19 <filter>
2 <servlet> 20 <filter-name>f2</filter-name>
3 <servlet-name>FilteredServlet</servlet-name> 21 <filter-class>Filter2</filter-class>
4 <servlet-class>FilteredServlet</servlet-class> 22 <init-param>
5 </servlet> 23 <param-name>permit</param-name>
6 <servlet-mapping> 24 <param-value>yes</param-value>
7 <servlet-name>FilteredServlet</servlet-name> 25 </init-param>
8 <url-pattern>/FilteredServlet</url-pattern> 26 </filter>
9 </servlet-mapping> 27 <filter-mapping>
10 28 <filter-name>f2</filter-name>
11 <filter> 29 <url-pattern>/FilteredServlet</url-pattern>
12 <filter-name>f1</filter-name> 30 </filter-mapping>
13 <filter-class>Filter1</filter-class> 31 </web-app>
14 </filter>
15 <filter-mapping>
16 <filter-name>f1</filter-name>
17 <url-pattern>/FilteredServlet</url-pattern>
18 </filter-mapping>
Filter Example-2
Filter1.java
1 public class Filter1 implements Filter{
2
3 public void init(FilterConfig config) {}
4
5 public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain)
6 throws IOException, ServletException
7 {
8 PrintWriter out=resp.getWriter();
9 out.print("<p>filter1 is invoked before</p>");
10 if(req.getParameter("login").equals("java") && req.getParameter("pwd").equals("servlet"))
11 {
12 chain.doFilter(req, resp);//send request to next resource
13 }//if
14 else
15 {
16 out.print("<p>invalid login/password</p>");
17 }//else
18 out.print("<p>filter1 is invoked after</p>");
19 }
20 public void destroy() {}
21 }
Filter Example-2
Filter1.java
1 public class Filter2 implements Filter{
2
3 String permission;
4 public void init(FilterConfig config) throws ServletException
5 { permission=config.getInitParameter("permit");
6 }
7
8 public void doFilter(ServletRequest req, ServletResponse resp,FilterChain chain) throws IOException,
9 ServletException
10 { PrintWriter out=resp.getWriter();
11 out.print("<p>filter2 is invoked before</p>");
12 if(permission.equals("yes"))
13 { chain.doFilter(req, resp);}//if
14 else
15 {
16 out.println("Permission Denied");
17 }//else
18 out.print("<p>filter2 is invoked after</p>");
19 }
20 public void destroy() {}}
Filter Example-2
FilteredServlet.java
1 public class FilteredServlet extends HttpServlet {
2 public void doGet(HttpServletRequest request, HttpServletResponse response)
3 throws ServletException, IOException
4 {
5 response.setContentType("text/html");
6 PrintWriter out = response.getWriter();
7 out.println("<p><h3>welcome to servlet</h3></p>");
8 }
9 }
10
Filter
Advantage of Filter
Filter is pluggable.
One filter don't have dependency onto another resource.
Less Maintenance Cost
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we remove the entry of filter
from the web.xml file, filter will be removed automatically and we don't need to change the servlet.
So maintenance cost will be less.
Servlet with JDBC
ServletWithJDBC.java
1 import java.io.*;
2 import java.sql.*;
3 import javax.servlet.*;
4 import javax.servlet.http.*;
5 public class JDBCServlet extends HttpServlet
6 {
7 public void doGet(HttpServletRequest request, HttpServletResponse response)
8 throws ServletException,IOException
9 { response.setContentType("text/html");
10 PrintWriter out=response.getWriter();
11 //Program continued in next slide ...
12 try{
13 Class.forName("com.mysql.jdbc.Driver");
14 Connection con=DriverManager.getConnection ("jdbc:mysql://localhost:3306/ajava","root","");
15 Statement st=con.createStatement();
16 ResultSet rs=st.executeQuery("select * from cxcy");
17 while(rs.next())
18 { out.println("<p>"+rs.getInt(1));
19 out.println(rs.getString(2));
20 out.println(rs.getString(3)+"</p>");
21 }
22 }catch(Exception e)
23 {out.println("<p>inside exception"+e.toString()+"</p>");}
24 }//doGet()
25 }//Class

You might also like