ServletsDU II
ServletsDU II
Advanced Java
Unit-3 (Part-II)
Servlet API and
Overview
Reference Book:
Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric
Buest Wiley Publication
Chapter 6,7,8
Unit-3 Servlet
ADVANCED JAVA
API- and
2160707
Overview Darshan
Darshan
Institute
Institute
of of
Engineering
Engineering
& Technology
& Technology
Cookies and Session Management
Unit-3 Servelt API and Overview 3 Darshan Institute of Engineering & Technology
Session Management in Servlets
What is Session?
Unit-3 Servlet API and Overview 4 Darshan Institute of Engineering & Technology
Session Management in Servlets
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.
1. Request (New)
2. Response
Client Server
3.Second Request (New)
Unit-3 Servlet API and Overview 5 Darshan Institute of Engineering & Technology
Session Management
Example: Application of Session
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.
Unit-3 Servlet API and Overview 6 Darshan Institute of Engineering & Technology
Session Management
▪ Session Management is a mechanism used by the Web
container to store session information for a particular user.
▪ There are three different techniques for session management.
Session Management
URL Rewriting
Cookies
HttpSession
Unit-3 Servlet API and Overview 7 Darshan Institute of Engineering & Technology
URL Rewriting
8
Unit-3 Servelt API and Overview 8 Darshan Institute of Engineering & Technology
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 &…
Unit-3 Servlet API and Overview 9 Darshan Institute of Engineering & Technology
Session Management: URL Rewriting
1. import javax.servlet.*; Url1.java
2. import javax.servlet.http.*;
3. import java.io.*;
4. public class Url1 extends HttpServlet
5. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
6. throws ServletException,IOException
7. { String url;
8. response.setContentType("text/html");
9. PrintWriter out=response.getWriter(); URL
10. //for URL rewriting Rewriting
11. url= "http://localhost:8080/Session
/Url2?s_id1=054&s_id2=055";
12. out.println("<a href="+url+">next page</a>");
13. } }
Unit-3 Servlet API and Overview 10 Darshan Institute of Engineering & Technology
Session Management: URL Rewriting
1. import javax.servlet.*; Url2.java
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. }
Unit-3 Servlet API and Overview 11 Darshan Institute of Engineering & Technology
Session Management: URL Rewriting
Url1.java
Url2.java
Unit-3 Servlet API and Overview 12 Darshan Institute of Engineering & Technology
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
Unit-3 Servlet API and Overview 13 Darshan Institute of Engineering & Technology
Cookies
javax.servlet.http.Cookie
14
Unit-3 Servelt API and Overview 14 Darshan Institute of Engineering & Technology
Session Management: Cookies
▪ A cookie is a small piece of information that is persisted between
the multiple client requests and stored on the client machine.
▪ A cookie has a
1. Name
2. Single value
3. Optional attributes such as
i. comment
ii. path
iii. domain qualifiers
iv. a maximum age
v. version number
Unit-3 Servlet API and Overview 15 Darshan Institute of Engineering & Technology
Session Management: Cookies
How Cookie works? By default, each
request is considered
as a new request
1. Request
2. Response + Cookie
Unit-3 Servlet API and Overview 16 Darshan Institute of Engineering & Technology
Session Management: Cookies
Types of Cookie
Unit-3 Servlet API and Overview 17 Darshan Institute of Engineering & Technology
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
Cookie c= new Cookie("session_id","054");
//creating cookie object
Unit-3 Servlet API and Overview 18 Darshan Institute of Engineering & Technology
Session Management: Cookies
Methods of Cookie class
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 Assigns a new value to this Cookie.
(String newValue)
String getValue() Gets the current value of this Cookie.
Unit-3 Servlet API and Overview 19 Darshan Institute of Engineering & Technology
Session Management: Cookies
Other Methods of HttpServletRequest & HttpServletResponse
void addCookie(Cookie cookie) • Method of HttpServletResponse interface is used to
add cookie in response object.
Unit-3 Servlet API and Overview 20 Darshan Institute of Engineering & Technology
Session Management: Cookies
How to create Cookie?
Example
//creating cookie object
Cookie c= new Cookie("session_id","054");
//adding cookie in the response
response.addCookie(c);
Unit-3 Servlet API and Overview 21 Darshan Institute of Engineering & Technology
Session Management: Cookies
How to retrieve Cookies?
Cookie c[]=request.getCookies();
for(int i=0;i<c.length;i++)
{
out.print(c[i].getName()+””+
c[i].getValue());
//printing name&value of cookie
}
Unit-3 Servlet API and Overview 22 Darshan Institute of Engineering & Technology
Session Management: Cookies
How to delete Cookie?
1. Read an already existing cookie and store it in Cookie
object.
2. Set cookie age as zero using setMaxAge() method to
delete an existing cookie
3. Add this cookie back into response header.
Unit-3 Servlet API and Overview 23 Darshan Institute of Engineering & Technology
Session Management: Cookies
How to delete Cookie?
//deleting value of cookie
Cookie c = new Cookie("user","");
//changing the maximum age to 0 seconds
c.setMaxAge(0);
//adding cookie in the response
response.addCookie(c);
Unit-3 Servlet API and Overview 24 Darshan Institute of Engineering & Technology
Session Management: Cookies
Cookie.html
Cookie1.java
Add Cookie
Cookie2.java
Cookie3.java
Retrieve Cookie
Retrieve All Cookies Add Another Cookie
Unit-3 Servlet API and Overview 25 Darshan Institute of Engineering & Technology
Session Management: Cookies
<html> cookie.html
<head>
<title>cookie</title>
</head>
<body>
<form action="/Session/Cookie1" >
<p>Login ID:<input type="text" name="login"></p>
<p>Password:<input type="password" name="pwd"></p>
<p><input type="submit" value="Sign In"></p>
</form>
</body>
</html>
Unit-3 Servlet API and Overview 26 Darshan Institute of Engineering & Technology
Session Management: Cookies
1. public class Cookie1 extends HttpServlet Cookie1.java
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. { Cookie c = new Cookie("c1",login);//create cookie
10. response.addCookie(c);//adds cookie with response
11. out.println("Cookie named:"+c.getName()+" added");
12. String path="/Session/Cookie2";
13. out.println("<p><a href="+path+">next page</a></p>");
14. }
15. else { //Redirect page to cookie.html}
16. } }
Unit-3 Servlet API and Overview 27 Darshan Institute of Engineering & Technology
Session Management: Cookies
Output: Cookie1.java [add Cookie]
Unit-3 Servlet API and Overview 28 Darshan Institute of Engineering & Technology
Session Management: Cookies
1. public class Cookie2 extends HttpServlet Cookie2.java
2. { public void doGet(HttpServletRequest request,
HttpServletResponse response) throws
ServletException,IOException
3. { response.setContentType("text/html");
4. PrintWriter out=response.getWriter();
5. Cookie c[]=request.getCookies();
6. out.println("c.length="+c.length);
7. for(int i=0;i<c.length;i++)
8. { out.println("CookieName="+c[i].getName()+
9. "CookieValue="+c[i].getValue());}
10. //to add another cookie
11. Cookie c1 = new Cookie("c2","054");
12. response.addCookie(c1);
13. String path="/Session/Cookie3";
14. out.println("<a href="+path+">next page</a>");}}
Unit-3 Servlet API and Overview 29 Darshan Institute of Engineering & Technology
Session Management: Cookies
Output: Cookie1.java [Retrive Cookie and add one more cookie]
Unit-3 Servlet API and Overview 30 Darshan Institute of Engineering & Technology
Session Management: Cookies
1. public class Cookie3 extends HttpServlet Cookie3.java
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. }
Unit-3 Servlet API and Overview 31 Darshan Institute of Engineering & Technology
Session Management: Cookies
Output: Cookie1.java [Retrive all the Cookies]
Unit-3 Servlet API and Overview 32 Darshan Institute of Engineering & Technology
Session Management: Cookies
Advantage of Cookies
▪ Simplest technique of maintaining the state.
Disadvantage of Cookies
▪ It will not work if cookie is disabled from the browser.
▪ Only textual information can be set in Cookie object.
Unit-3 Servlet API and Overview 33 Darshan Institute of Engineering & Technology
Interview Questions: Cookies
1. What Are Cookies?
2. Can I see/view the cookies I have on my computer?
3. What's in a Cookie? OR What does a Cookie contains?
4. Why are Cookies Used?
5. How Long Does a Cookie Last?
6. How Secure are Cookies?
7. What are Tracking Cookies?
8. What do the Cookies Do?
Unit-3 Servlet API and Overview 34 Darshan Institute of Engineering & Technology
HttpSession
javax.servlet.http.HttpSession
35
Unit-3 Servelt API and Overview 35 Darshan Institute of Engineering & Technology
Session Management: HttpSession
▪ javax.servlet.http.HttpSession
▪ The HttpSession interface enables a servlet to read and write the
state information that is associated with an HTTP session.
▪ The default session time is 30 minutes and can configure explicit
session time in web.xml file.
Unit-3 Servlet API and Overview 36 Darshan Institute of Engineering & Technology
Session Management : HttpSession
Server
Web Container
Request
Client1 id=054 Session1
id= 054
Servlet
Session2
Request id= 055
Client2
id=055
Working of HttpSession
Unit-3 Servlet API and Overview 37 Darshan Institute of Engineering & Technology
Session Management :HttpSession
▪ Package: javax.servlet.http.HttpSession
Interface
▪ 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.
Unit-3 Servlet API and Overview 38 Darshan Institute of Engineering & Technology
Session Management : HttpSession
The HttpServletRequest interface provides two methods to get the
object of HttpSession
Unit-3 Servlet API and Overview 39 Darshan Institute of Engineering & Technology
Session Management : HttpSession
Methods of HttpSession interface
Unit-3 Servlet API and Overview 40 Darshan Institute of Engineering & Technology
Session Management : HttpSession
How to create the session?
HttpSession hs=request.getSession();
hs.setAttribute("s_id", "diet054");
How to retrieve a session?
HttpSession hs=request.getSession(false);
String n=(String)hs.getAttribute("s_id");
How to invalidate a session?
hs.invalidate();
Unit-3 Servlet API and Overview 41 Darshan Institute of Engineering & Technology
Session Management : HttpSession
Httpsession.html HSession1.java
[Login page] [Create Session]
HSession2.java
[Retrieve Session]
HSession3.java
HSession4.java
[Retrieve Session]
[Logout]
[Invalidate Session]
Unit-3 Servlet API and Overview 42 Darshan Institute of Engineering & Technology
Session Management : HttpSession
<html> Httpsession.html
<head>
<title>HttpSession</title>
</head>
<body>
<form action="/Session/HSession1" method="Get">
<p>Login ID:<input type="text" name="login"></p>
<p><input type="submit" value="Sign In"></p>
</form>
</body>
</html>
Unit-3 Servlet API and Overview 43 Darshan Institute of Engineering & Technology
Session Management : HttpSession
1. response.setContentType("text/html"); HSession1.java
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
</h1></p>");
13. rd=request.getRequestDispatcher("/httpsession.html");
14. rd.include(request, response);}
Unit-3 Servlet API and Overview 44 Darshan Institute of Engineering & Technology
Session Management : HttpSession
Output: HttpSession1.java
Unit-3 Servlet API and Overview 45 Darshan Institute of Engineering & Technology
Session Management : HttpSession
1. public class HSession2 extends HttpServlet HSession2.java
2. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
3. throws ServletException,IOException
4. {response.setContentType("text/html");
5. PrintWriter out=response.getWriter();
6. HttpSession hs=request.getSession(false);
7. String n=(String)hs.getAttribute("s_id");
8. out.print("Hello "+n);
9. out.print("<p><a hef='HSession3'>visit</a></p>");
10. } }
Unit-3 Servlet API and Overview 46 Darshan Institute of Engineering & Technology
Session Management : HttpSession
Output: HttpSession2.java
Unit-3 Servlet API and Overview 47 Darshan Institute of Engineering & Technology
Session Management : HttpSession
1. public class HSession3 extends HttpServlet HSession3.java
2. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
3. throws
ServletException,IOException
4. {response.setContentType("text/html");
5. PrintWriter out=response.getWriter();
6. HttpSession hs=request.getSession(false);
7. String n=(String)hs.getAttribute("s_id");
8. out.print("Hello again "+n);
9. out.println("<form
action='/Session/HSession4'>");
10. out.println("<p><input type='submit'
11. value='End
Session'></p></form>");
12. hs.invalidate();//Session Invalidated
13. }
Unit-3 Servlet API and Overview 48 Darshan Institute of Engineering & Technology
Session Management : HttpSession
Output: HttpSession3.java
Unit-3 Servlet API and Overview 49 Darshan Institute of Engineering & Technology
Session Management : HttpSession
1. public void doGet(HttpServletRequest request, HSession4.java
HttpServletResponse response)
2. throws ServletException,IOExceptio
{ response.setContentType("text/html");
3. PrintWriter out=response.getWriter();
4. HttpSession hs=request.getSession(false);
5. try
6. { String n=(String)hs.getAttribute("s_id");
7. } catch(NullPointerException ne)
8. {out.println("Session Invalidated");}
9. out.println("<form action='/Session/httpsession.html'>");
10. out.println("<p><input type='submit'
value='logout'></p></form>");
11. }//doGet
Unit-3 Servlet API and Overview 50 Darshan Institute of Engineering & Technology
Session Management : HttpSession
Output: HttpSession4.java
Unit-3 Servlet API and Overview 51 Darshan Institute of Engineering & Technology
Session Timeout
52
Unit-3 Servelt API and Overview 52 Darshan Institute of Engineering & Technology
Session Timeout
The session timeout in a web application can be configured in two
ways
1. Timeout in the deployment descriptor (web.xml)
2. Timeout with setMaxInactiveInterval()
Unit-3 Servlet API and Overview 53 Darshan Institute of Engineering & Technology
Session Timeout
1. Timeout in the deployment descriptor (web.xml)
<web-app>
<session-config>
<session-timeout> 10 </session-timeout>
</session-config>
Here specified
</web-app> time is in
minutes
Unit-3 Servlet API and Overview 54 Darshan Institute of Engineering & Technology
Session Timeout
2. Timeout with setMaxInactiveInterval()
The timeout of the current session only can be specified
programmatically via the API of the javax.servlet.http.HttpSession
Here specified
time is in
seconds
Unit-3 Servlet API and Overview 55 Darshan Institute of Engineering & Technology
GTU Questions
1. Write Servlet program to create cookie. Also write code to display
contents of cookie on page. [7]
2. What is session? Explain session management using HTTPSession.
[7]
3. List the different ways to manage the session. [4]
Unit-3 Servlet API and Overview 56 Darshan Institute of Engineering & Technology
Filter API
57
Unit-3 Servelt API and Overview 57 Darshan Institute of Engineering & Technology
Filter API
Web Container
Filter
Servlet Program
Filter response response
WebClient
Unit-3 Servlet API and Overview 58 Darshan Institute of Engineering & Technology
Filter
1. Filter is used for pre-processing of requests and
post-processing of responses.
2. Filters are configured in the deployment descriptor of a web
application.
3. If multiple filters are chained together then the filters will
be called in the order in which they appear in the web.xml
file.
4. 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.
5. So maintenance cost will be less.
Unit-3 Servlet API and Overview 59 Darshan Institute of Engineering & Technology
Filter
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.
Unit-3 Servlet API and Overview 60 Darshan Institute of Engineering & Technology
Filter API
The javax.servlet package contains the three interfaces of Filter API.
1. Filter
2. FilterChain
3. FilterConfig
Unit-3 Servlet API and Overview 61 Darshan Institute of Engineering & Technology
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
(HttpServletRequest request, request to any resource, to which the filter is mapped.It
HttpServletResponse response, is used to perform filtering tasks.
FilterChain fc)
void destroy() This is invoked only once when filter is taken out of the
service.
Unit-3 Servlet API and Overview 62 Darshan Institute of Engineering & Technology
Filter Interface
Example
public void init(FilterConfig config)
throws ServletException {…}
Unit-3 Servlet API and Overview 63 Darshan Institute of Engineering & Technology
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:
Unit-3 Servlet API and Overview 64 Darshan Institute of Engineering & Technology
Filter Config
▪ FilterConfig is created by the web container.
▪ This object can be used to get the configuration information from
the web.xml file.
Method
void init(FilterConfig config) init() method is invoked only once it is used to initialize
the filter.
String getInitParameter Returns the parameter value for the specified parameter
(String parameterName) name.
Unit-3 Servlet API and Overview 65 Darshan Institute of Engineering & Technology
Filter Example
Web Container
Filter1.java
FilteredServlet.java
Servlet Program
Filter response response
WebClient
Unit-3 Servlet API and Overview 66 Darshan Institute of Engineering & Technology
Filter Example: 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>
Unit-3 Servlet API and Overview 67 Darshan Institute of Engineering & Technology
Filter Example1
1. <web-app> web.xml
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>
Unit-3 Servlet API and Overview 68 Darshan Institute of Engineering & Technology
Filter Example1
10. <filter> web.xml
11. <filter-name>f1</filter-name>
12. <filter-class>Filter1</filter-class>
13. </filter>
14. <filter-mapping>
15. <filter-name>f1</filter-name>
16. <url-pattern>/FilteredServlet</url-pattern>
17. </filter-mapping>
Unit-3 Servlet API and Overview 69 Darshan Institute of Engineering & Technology
Filter Example1: Filter1.java
1. public class Filter1 implements Filter
2. {public void init(FilterConfig arg0) throws
ServletException {//overridden init() method}
3. public void doFilter(ServletRequest req,
4. ServletResponse resp,FilterChain chain)
throws IOException, ServletException
5. { PrintWriter out=resp.getWriter();
6. out.print("filter is invoked before");//exe. with request
7. chain.doFilter(req, resp);//send request to nextresource
8. out.print("filter is invoked after");//exe. with response
9. }
10. public void destroy() {//overridden destroy() method}
11. }
Unit-3 Servlet API and Overview 70 Darshan Institute of Engineering & Technology
Filter Example1: FilteredServlet.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. { public void doGet(HttpServletRequest request,
HttpServletResponse response)
7. throws ServletException, IOException
8. {
9. response.setContentType("text/html");
10. PrintWriter out = response.getWriter();
11. out.println("<br>welcome to servlet<br>");
12. }
13. }
Unit-3 Servlet API and Overview 71 Darshan Institute of Engineering & Technology
Filter Example1: Output
Unit-3 Servlet API and Overview 72 Darshan Institute of Engineering & Technology
Filter Example2
Web Container
Filter1.java Filter2.java
FilteredServlet.java
Servlet Program
WebClient
Unit-3 Servlet API and Overview 73 Darshan Institute of Engineering & Technology
Filter Example2
1. <html> index.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>
Unit-3 Servlet API and Overview 74 Darshan Institute of Engineering & Technology
Filter Example2
1. <web-app> web.xml
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>
Unit-3 Servlet API and Overview 75 Darshan Institute of Engineering & Technology
Filter Example2
10. <filter> web.xml
11. <filter-name>f1</filter-name>
12. <filter-class>Filter1</filter-class>
13. </filter>
14. <filter-mapping>
15. <filter-name>f1</filter-name>
16. <url-pattern>/FilteredServlet</url-pattern>
17. </filter-mapping>
Unit-3 Servlet API and Overview 76 Darshan Institute of Engineering & Technology
Filter Example2 web.xml
18. <filter>
19. <filter-name>f2</filter-name>
20. <filter-class>Filter2</filter-class>
21. <init-param>
22. <param-name>permit</param-name>
23. <param-value>yes</param-value>
24. </init-param>
25. </filter>
26. <filter-mapping>
27. <filter-name>f2</filter-name>
28. <url-pattern>/FilteredServlet</url-pattern>
29. </filter-mapping>
30. </web-app>
Unit-3 Servlet API and Overview 77 Darshan Institute of Engineering & Technology
Filter Example2
1. public class Filter1 implements Filter{ Filter1.java
2. public void init(FilterConfig config) {}
3. public void doFilter(ServletRequest req,
4. ServletResponse resp, FilterChain chain)
5. throws IOException, ServletException
6. { PrintWriter out=resp.getWriter();
7. out.print("<p>filter1 is invoked before</p>");
8. if(req.getParameter("login").equals("java") &&
9. req.getParameter("pwd").equals("servlet"))
10. { chain.doFilter(req, resp);//send request to next resource
11. }//if
12. else
13. {out.print("<p>invalid login/password</p>");}//else
14.
15. out.print("<p>filter1 is invoked after</p>");
16. }
17. public void destroy() {}}
Unit-3 Servlet API and Overview 78 Darshan Institute of Engineering & Technology
Filter Example2
1. public class Filter2 implements Filter{ Filter2.java
2. String permission;
3. public void init(FilterConfig config) throws ServletException
4. { permission=config.getInitParameter("permit");
}
5. public void doFilter(ServletRequest req, ServletResponse resp,
6. FilterChain chain) throws IOException, ServletException
7. { PrintWriter out=resp.getWriter();
8. out.print("<p>filter2 is invoked before</p>");
9. if(permission.equals("yes"))
10. { chain.doFilter(req, resp);}//if
11. else
12. { out.println("Permission Denied"); }//else
Unit-3 Servlet API and Overview 79 Darshan Institute of Engineering & Technology
Filter Example2
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. }
Unit-3 Servlet API and Overview 80 Darshan Institute of Engineering & Technology
Filter Example2:output
Unit-3 Servlet API and Overview 81 Darshan Institute of Engineering & Technology
Filter
Advantage of Filter
▪ Filter is pluggable.
▪ One filter don't have dependency onto another resource.
▪ Less Maintenance Cost
Unit-3 Servlet API and Overview 82 Darshan Institute of Engineering & Technology
GTU Questions:Filter
1. What is Filter? List the applications of filter. [3] Win’17
Win’18
2. Explain the configuration of filter using deployment Sum’18
descriptor.[4]
Unit-3 Servlet API and Overview 83 Darshan Institute of Engineering & Technology
Attributes in Servlet
84
Unit-3 Servelt API and Overview 84 Darshan Institute of Engineering & Technology
Attributes in Servlet
SetAttributeDemo.java
ServletContext context=getServletContext();
context.setAttribute("college", "diet");
out.println("<a href='/New/GetAttributeDemo'>next</a>");
GetAttributeDemo.java
ServletContext context=getServletContext();
String value=(String)context.getAttribute("college");
out.println("Welcome "+value);
Unit-3 Servlet API and Overview 85 Darshan Institute of Engineering & Technology
Servlet with JDBC
86
Unit-3 Servelt API and Overview 86 Darshan Institute of Engineering & Technology
Servlet with JDBC
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();
//Program continued in next slide…
...
Unit-3 Servlet API and Overview 87 Darshan Institute of Engineering & Technology
Servlet with JDBC
11. try{
12. Class.forName("com.mysql.jdbc.Driver");
13. Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306/ajava","root","");
14. Statement st=con.createStatement();
15. ResultSet rs=st.executeQuery("select * from cxcy");
16. while(rs.next())
17. { out.println("<p>"+rs.getInt(1));
18. out.println(rs.getString(2));
19. out.println(rs.getString(3)+"</p>");
20. }
21. }catch(Exception e)
22. {out.println("<p>inside exception"+e.toString()+"</p>");}
23. }//doGet()
24. }//Class
Unit-3 Servlet API and Overview 88 Darshan Institute of Engineering & Technology
Types of Servlet Events
▪ Events are basically occurrence of something.
▪ Changing the state of an object is known as an event.
▪ There are many Event classes and Listener interfaces in the
javax.servlet and javax.servlet.http packages.
▪ In web application world an event can be
• Initialization of application
• Destroying an application
• Request from client
• Creating/destroying a session
• Attribute modification in session etc.
Unit-3 Servlet API and Overview 89 Darshan Institute of Engineering & Technology
Types of Servlet Events
▪ Event classes
ServletRequestEvent Events of this kind indicate lifecycle events for a
ServletRequest. The source of the event is the
ServletContext of this web application.
ServletContextEvent This is the event class for notifications about changes to the
servlet context of a web application.
ServletRequestAttributeEvent This is the event class for notifications of changes to the
attributes of the servlet request in an application.
ServletContextAttributeEvent Event class for notifications about changes to the attributes
of the ServletContext of a web application.
HttpSessionEvent This is the class representing event notifications for changes
to sessions within a web application.
HttpSessionBindingEvent Send to an Object that implements
HttpSessionBindingListener when bound into a session or
unbound from a session.
Unit-3 Servlet API and Overview 90 Darshan Institute of Engineering & Technology
GTU Servlet Programs
1. Write a Java Servlet to demonstrate the use of Session Management. [Win’18]
[Sum’18]
[Win’16]
[Win’15]
2. Write small web application which takes marks of three subject and pass [Sum’16]
to servlet. Servlet forward to model class having method getClass() and
getPercentage(). Display class and percentage
3. Write servlet which displayed following information of client. [Sum’16]
I. Client Browser II. Client IP address III. Client Port No IV. Server Port No.
V. Local Port No VI. Method used by client for form submission
VII. Query String name and values
4. Write a Java Servlet to print BE Semester 7 Marksheet of entered [Sum’18]
enrollment number by user using JDBC. [Sum’15]
[Sum’19]
5. Write a servlet which accept two numbers using POST methods and [Win’14]
display the maximum of them.
Unit-3 Servlet API and Overview 91 Darshan Institute of Engineering & Technology
GTU Servlet Programs
7.
6. Write a web application using servlet to compute an area of a circle. Get [Win’13]
the radius from the client. Write necessary web.xml file.
Unit-3 Servlet API and Overview 92 Darshan Institute of Engineering & Technology
GTU Servlet Theory Questions
1. Explain Servlet Life Cycle with example to demonstrate every state. [Sum’17]
Explain role of web container. Explain importance of context object. [Win’18]
[Win’19]
[Sum’19]
2. What is filter? What is its use? List different filter interfaces with their [Win’18]
important methods. Explain the configuration of filter using deployment [Sum’18]
descriptor. [Win’16]
[Sum’15]
3. What is Request Dispatcher? What is the difference between Request [Win’16]
dispatcher’s forward() and include() method?
4. Explain difference between ServletConfig and ServletContext object. [Sum’18]
[Sum’17]
[Win ’19]
5. Write Servlet program to create cookie. Also write code to display [Sum’18]
contents of cookie on page. Explain functionality of Cookie.[7] [Sum’19]
6. Write difference between (1) Generic Servlet and Http Servlet [Sum’19]
(2) doGet and doPost
Unit-3 Servlet API and Overview 93 Darshan Institute of Engineering & Technology
GTU Servlet Theory Questions
7. What is session? Explain session management using HTTPSession. [Win’17]
[Sum’18]
[Win’19]
[Sum’19]
Unit-3 Servlet API and Overview 94 Darshan Institute of Engineering & Technology
Servlet Interview Questions
1. Who is responsible to create the object of servlet?
2. What is difference between Get and Post method?
3. When servlet object is created?
4. What is difference between PrintWriter and ServletOutputStream?
5. What is difference between GenericServlet and HttpServlet?
6. Can you call a jsp from the servlet?
7. Difference between forward() method and sendRedirect() method ?
8. What is difference between ServletConfig and ServletContext?
9. What happens if you add a main method to servlet?
10. What is MIME Type?
11. Why main() is not written in servlets programs?
12. How does the JVM execute a servlet compared with a regular Java class?
13. Consider a scenario in which 4 users are accessing a servlet instance. Among which
one user called destroy() method. What happens to the rest 3 users?
14. What is Connection Pooling?
Unit-3 Servlet API and Overview 95 Darshan Institute of Engineering & Technology
Servlet Interview Questions
15. Servlet is Java class. Then why there is no constructor in Servlet? Can we write the
constructor in Servlet? Justify your answer.
Unit-3 Servlet API and Overview 96 Darshan Institute of Engineering & Technology