Servlet API Overview and Lifecycle
Servlet API Overview and Lifecycle
GTU #3160707
Unit-3
Servlet API and
Overview
Reference Book:
Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric
Buest Wiley Publication
Hi, I am Servlet.
But I have
Let me helpanyou
application named
to display given
SERVLET,
name in your web
which
page. can process
your request
Clien Server
Dynamic Response
t
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 5
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.
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.
Image Reference:http://www.c4learn.com/java/servlet/servlet-vs-cgi/
Implemented by
It provides implementation of methods
GenericServlet of Servlet interfaces.
extended by
Contains interface and abstract class for
Class
init() destroy()
Servlet
In Service
Servlet Container
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 …
}
It is used to
Configuration
map Servlet toof servlet
using <servlet>
specific URL Map the servlet to a URL. This can be done
using <servlet-mapping> element.
1
2
5
3
Ref: https://www.ntu.edu.sg/home/ehchua/programming/java/JavaServlets.html
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 31
javax.servlet Interface
Http Servlet
javax.servlet.http (package)
extends javax.servlet.HttpServlet
doGet(), doPost()
doGet(HttpServletRequest req,HttpServletResponse res)
doPost(HttpServletRequest req,HttpServletResponse res)
</servlet>
Used to pass parameters to a servlet from the web.xml file.
<servlet-mapping>
map the servlet to a
<servlet-name>MyServlet</servlet-name> URL or URL pattern
<url-pattern>/MyServlet</url-pattern>
Using
doPost()
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 42
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
web.xml
<init-param>
<param-name>name</param-name>
</web-app>
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 46
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>
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 47
ServletContextDemo.java
ServletContextDemo.jav
a
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 }
getContextPath
1 public void doGet(HttpServletRequest request, HttpServletResponse response)
2 {
3 out.println("<p>request.getContextPath():" +request.getContextPath()+"</p>");
4 }
Output
request.getContextPath():/ServletTemp
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
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
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
getServletPath
1 public void doGet(HttpServletRequest request, HttpServletResponse response)
2 {
3 out.println("<p>request.getServletPath():" +request.getServletPath()+"</p>");
4 }
Output
request.getServletPath(): /ServletMeth
getServletPath
1 public void doGet(HttpServletRequest request, HttpServletResponse response)
2 {
3 out.println("<p>request.getMethod():"+request.getMethod()+"</p>");
4 }
Output
request.getMethod(): GET
void include(ServletRequest request, Includes the content of a resource (Servlet, JSP page,
ServletResponse response) or HTML file) in the response.
throws ServletException, IOException
Step 3:
Response Response is
generated
Web Client
Step 4: R
e sponse i
s sent ba
ck to brows Response
er
Web Client
Fina
l
sent Response Response
b
fro n a c k t o t h e i s
Serv
l e t 1 c l i e nt
Syntax
1 RequestDispatcher getRequestDispatcher(String resource)
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);
Validate Servlet
[CallServlet.java]
Yes IsVali No
d?
[include: 1.html]
[forward: FwdDemo.java]
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
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
Hidden form field
URL Rewriting
Cookies
HttpSession
Example
1 <input type="hidden" name="session_id" value="054">
Welcome.java
request.getParameter(“session”);
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.
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 Server
So cookie is as the old user.
stored in the
cache of the
3. Request +
browser.
Cookie
Cookie(String name, String value) constructs a cookie with a specified name and value.
Example
1 Cookie c= new Cookie("session_id","054");
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.
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);
Cookie1.java
Add Cookie
Cookie2.java
Cookie3.java
Retrieve Cookie
Retrieve All Cookies Add Another Cookie
Server
Web Container
Request
Client1 id=054 Session1
id= 054
Servle
t
Session2
Request id= 055
Client2
id=055
Working of HttpSession
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.
Httpsession.html HSession1.java
[Login page] [Create Session]
HSession2.java
[Retrieve Session]
HSession4.java
[Logout]
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 100
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
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 101
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 }
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 102
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
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 103
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 }
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 104
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()
Here specified
time is in seconds
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 105
Filter API
Web Container
Filter
WebClient
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 106
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.
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 107
Filter API
The javax.servlet package contains the three interfaces of Filter API.
Filter
FilterChain
FilterConfig
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 108
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
(HttpServletRequest request, resource, to which the filter is mapped.It is used to perform filtering
HttpServletResponse response, FilterChain tasks.
chain)
void destroy() This is invoked only once when filter is taken out of the service.
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 109
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() {…}
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 110
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
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 111
Filter Example
Web Container
Filter1.java
FilteredServlet.java
WebClient
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 112
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
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 113
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>
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 114
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,
7 ServletException
8 {
9 PrintWriter out=resp.getWriter();
10 out.print("filter is invoked before");//exe. with request
11 chain.doFilter(req, resp);//send request to nextresource
12 out.print("filter is invoked after");//exe. with response
13 }
14 public void destroy() {//overridden destroy() method}
}
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 115
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 }
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 116
Filter Example-2
Web Container
Filter1.java Filter2.java
FilteredServlet.java
Servlet Program
WebClient
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 117
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>
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 118
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>
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 119
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 }
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 120
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() {}}
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 121
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
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 122
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.
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 123
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
Prof. Jayesh D. Vagadiya # 3160707 Unit 3 – Servlet API and Overview 124