0% found this document useful (0 votes)
19 views

JavaServlet Material2

Uploaded by

Deep mathukiya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

JavaServlet Material2

Uploaded by

Deep mathukiya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 45

ServletConfig Interface

An object of ServletConfig is created by the web container for each servlet. This
object can be 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. So it is easier to manage the web application if any specific
content is modified from time to time.

Advantage of ServletConfig
The core advantage of ServletConfig is that you don't need to edit the servlet file if
information is modified from the web.xml file.

Methods of ServletConfig interface


1. public String getInitParameter(String name):Returns the parameter
value for the specified parameter name.

2. public Enumeration getInitParameterNames():Returns an enumeration


of all the initialization parameter names.

3. public String getServletName():Returns the name of the servlet.

4. public ServletContext getServletContext():Returns an object of


ServletContext.

How to get the object of ServletConfig


1. getServletConfig() method of Servlet interface returns the object of
ServletConfig.

Syntax of getServletConfig() method


1. public ServletConfig getServletConfig();
Example of getServletConfig() method
1. ServletConfig config=getServletConfig();
2. //Now we can call the methods of ServletConfig interface

Syntax to provide the initialization parameter for a servlet


The init-param sub-element of servlet is used to specify the initialization parameter
for a servlet.

1. <web-app>
2. <servlet>
3. ......
4.
5. <init-param>
6. <param-name>parametername</param-name>
7. <param-value>parametervalue</param-value>
8. </init-param>
9. ......
10. </servlet>
11. </web-app>

Example of ServletConfig to get initialization


parameter
In this example, we are getting the one initialization parameter from the web.xml
file and printing this information in the servlet.

DemoServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class DemoServlet extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse respons
e)
7. throws ServletException, IOException {
8.
9. response.setContentType("text/html");
10. PrintWriter out = response.getWriter();
11.
12. ServletConfig config=getServletConfig();
13. String driver=config.getInitParameter("driver");
14. out.print("Driver is: "+driver);
15.
16. out.close();
17. }
18.
19. }

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>DemoServlet</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6.
7. <init-param>
8. <param-name>driver</param-name>
9. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
10. </init-param>
11.
12. </servlet>
13.
14. <servlet-mapping>
15. <servlet-name>DemoServlet</servlet-name>
16. <url-pattern>/servlet1</url-pattern>
17. </servlet-mapping>
18.
19. </web-app>

download this example (developed in Myeclipse IDE)


download this example(developed in Eclipse IDE)
download this example(developed in Netbeans IDE)

Example of ServletConfig to get all the initialization


parameters
In this example, we are getting all the initialization parameter from the web.xml file
and printing this information in the servlet.

DemoServlet.java

1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import java.util.Enumeration;
4. import javax.servlet.ServletConfig;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.HttpServlet;
7. import javax.servlet.http.HttpServletRequest;
8. import javax.servlet.http.HttpServletResponse;
9.
10.
11. public class DemoServlet extends HttpServlet {
12. public void doGet(HttpServletRequest request, HttpServletResponse respons
e)
13. throws ServletException, IOException {
14.
15. response.setContentType("text/html");
16. PrintWriter out = response.getWriter();
17.
18. ServletConfig config=getServletConfig();
19. Enumeration<String> e=config.getInitParameterNames();
20.
21. String str="";
22. while(e.hasMoreElements()){
23. str=e.nextElement();
24. out.print("<br>Name: "+str);
25. out.print(" value: "+config.getInitParameter(str));
26. }
27.
28. out.close();
29. }
30.
31. }

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>DemoServlet</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6.
7. <init-param>
8. <param-name>username</param-name>
9. <param-value>system</param-value>
10. </init-param>
11.
12. <init-param>
13. <param-name>password</param-name>
14. <param-value>oracle</param-value>
15. </init-param>
16.
17. </servlet>
18.
19. <servlet-mapping>
20. <servlet-name>DemoServlet</servlet-name>
21. <url-pattern>/servlet1</url-pattern>
22. </servlet-mapping>
23.
24. </web-app>

ServletContext Interface
An object of ServletContext is created by the web container at time of deploying the
project. This object 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.

Advantage of ServletContext
Easy to maintain if any information is shared to all the servlet, it is better to make
it available for all the servlet. We provide this information from the web.xml file, so
if the information is changed, we don't need to modify the servlet. Thus it removes
maintenance problem.

Usage of ServletContext Interface


There can be a lot of usage of ServletContext object. Some of them are as follows:

1. The object of ServletContext provides an interface between the container and


servlet.
2. The ServletContext object can be used to get configuration information from
the web.xml file.

3. The ServletContext object can be used to set, get or remove attribute from
the web.xml file.

4. The ServletContext object can be used to provide inter-application


communication.

Commonly used methods of ServletContext interface


There is given some commonly used methods of ServletContext interface.

1. public String getInitParameter(String name):Returns the parameter value for the

specified parameter name.

2. public Enumeration getInitParameterNames():Returns the names of the context's

initialization parameters.

3. public void setAttribute(String name,Object object):sets the given object in the

application scope.

4. public Object getAttribute(String name):Returns the attribute for the specified

name.

5. public Enumeration getInitParameterNames():Returns the names of the context's

initialization parameters as an Enumeration of String objects.


6. public void removeAttribute(String name):Removes the attribute with the given

name from the servlet context.

How to get the object of ServletContext interface


1. getServletContext() method of ServletConfig interface returns the object
of ServletContext.

2. getServletContext() method of GenericServlet class returns the object of


ServletContext.

Syntax of getServletContext() method


1. public ServletContext getServletContext()
Example of getServletContext() method
1. //We can get the ServletContext object from ServletConfig object
2. ServletContext application=getServletConfig().getServletContext();
3.
4. //Another convenient way to get the ServletContext object
5. ServletContext application=getServletContext();

Syntax to provide the initialization parameter in Context


scope
The context-param element, subelement of web-app, is used to define the initialization

parameter in the application scope. The param-name and param-value are the sub-elements

of the context-param. The param-name element defines parameter name and and

param-value defines its value.

1. <web-app>
2. ......
3.
4. <context-param>
5. <param-name>parametername</param-name>
6. <param-value>parametervalue</param-value>
7. </context-param>
8. ......
9. </web-app>
Example of ServletContext to get the initialization
parameter
In this example, we are getting the initialization parameter from the web.xml file and

printing the value of the initialization parameter. Notice that the object of ServletContext

represents the application scope. So if we change the value of the parameter from the

web.xml file, all the servlet classes will get the changed value. So we don't need to modify

the servlet. So it is better to have the common information for most of the servlets in the

web.xml file by

context-param element. Let's see the simple example:

DemoServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class DemoServlet extends HttpServlet{
7. public void doGet(HttpServletRequest req,HttpServletResponse res)
8. throws ServletException,IOException
9. {
10. res.setContentType("text/html");
11. PrintWriter pw=res.getWriter();
12.
13. //creating ServletContext object
14. ServletContext context=getServletContext();
15.
16. //Getting the value of the initialization parameter and printing it
17. String driverName=context.getInitParameter("dname");
18. pw.println("driver name is="+driverName);
19.
20. pw.close();
21.
22. }}
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <context-param>
9. <param-name>dname</param-name>
10. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
11. </context-param>
12.
13. <servlet-mapping>
14. <servlet-name>sonoojaiswal</servlet-name>
15. <url-pattern>/context</url-pattern>
16. </servlet-mapping>
17.
18. </web-app>

Example of ServletContext to get all the initialization


parameters
In this example, we are getting all the initialization parameter from the web.xml file.

For getting all the parameters, we have used the getInitParameterNames() method

in the servlet class.

DemoServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class DemoServlet extends HttpServlet{
7. public void doGet(HttpServletRequest req,HttpServletResponse res)
8. throws ServletException,IOException
9. {
10. res.setContentType("text/html");
11. PrintWriter out=res.getWriter();
12.
13. ServletContext context=getServletContext();
14. Enumeration<String> e=context.getInitParameterNames();
15.
16. String str="";
17. while(e.hasMoreElements()){
18. str=e.nextElement();
19. out.print("<br> "+context.getInitParameter(str));
20. }
21. }}
web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <servlet-class>DemoServlet</servlet-class>
6. </servlet>
7.
8. <context-param>
9. <param-name>dname</param-name>
10. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
11. </context-param>
12.
13. <context-param>
14. <param-name>username</param-name>
15. <param-value>system</param-value>
16. </context-param>
17.
18. <context-param>
19. <param-name>password</param-name>
20. <param-value>oracle</param-value>
21. </context-param>
22.
23. <servlet-mapping>
24. <servlet-name>sonoo jaiswal</servlet-name>
25. <url-pattern>/context</url-pattern>
26. </servlet-mapping>
27.
28. </web-app>

Attribute in Servlet
An attribute in servlet is an object that can be set, get or removed from one of the
following scopes:

1. request scope

2. session scope

3. application scope

The servlet programmer can pass information from one servlet to another using
attributes. It is just like passing object from one class to another so that we can
reuse the same object again and again.

Attribute specific methods of ServletRequest, HttpSession


and ServletContext interface
There are following 4 attribute specific methods. They are as follows:

1. public void setAttribute(String name,Object object):sets the given object

in the application scope.

2. public Object getAttribute(String name):Returns the attribute for the

specified name.

3. public Enumeration getInitParameterNames():Returns the names of the

context's initialization parameters as an Enumeration of String objects.

4. public void removeAttribute(String name):Removes the attribute with

the given name from the servlet context.

Example of ServletContext to set and get attribute


In this example, we are setting the attribute in the application scope

and getting that value from another servlet.


DemoServlet1.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class DemoServlet1 extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. {
7. try{
8.
9. res.setContentType("text/html");
10. PrintWriter out=res.getWriter();
11.
12. ServletContext context=getServletContext();
13. context.setAttribute("company","IBM");
14.
15. out.println("Welcome to first servlet");
16. out.println("<a href='servlet2'>visit</a>");
17. out.close();
18.
19. }catch(Exception e){out.println(e);}
20.
21. }}
DemoServlet2.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class DemoServlet2 extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. {
7. try{
8.
9. res.setContentType("text/html");
10. PrintWriter out=res.getWriter();
11.
12. ServletContext context=getServletContext();
13. String n=(String)context.getAttribute("company");
14.
15. out.println("Welcome to "+n);
16. out.close();
17.
18. }catch(Exception e){out.println(e);}
19. }}
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>DemoServlet1</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
14. <servlet-name>s2</servlet-name>
15. <servlet-class>DemoServlet2</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>

Difference between ServletConfig and ServletContext


The servletconfig object refers to the single servlet whereas servletcontext object

refers to the whole web application.

Servlet Filter
1.Filter

2.Usage of Filter

3.Advantage of Filter

4.Filter API

1.Filter interface

2.FilterChain interface

3.FilterConfig interface

5.Simple Example of Filter

A filter is an object that is invoked at the preprocessing and postprocessing of a


request.

It is mainly used to perform filtering tasks such as conversion, logging, compression,


encryption and decryption, input validation etc.

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.

Note: Unlike Servlet, One filter doesn't have dependency on another filter.
Usage of Filter
o recording all incoming requests

o logs the IP addresses of the computers from which the requests originate

o conversion

o data compression

o encryption and decryption

o input validation etc.


Advantage of Filter
1. Filter is pluggable.

2. One filter don't have dependency onto another resource.

3. Less Maintenance

Filter API
Like servlet filter have its own API. The javax.servlet package contains the three
interfaces of Filter API.

1. Filter

2. FilterChain

3. FilterConfig

1) Filter interface

For creating any filter, you must implement the Filter interface. Filter interface
provides the life cycle methods for a filter.

Method Description

public void init(FilterConfig config) init() method is invoked only once. It is used

to initialize the filter.

public void doFilter() method is invoked every time when


doFilter(HttpServletRequest
user request to any resource, to which the
request,HttpServletResponse
response, FilterChain chain) filter is mapped.It is used to perform

filtering tasks.

public void destroy() This is invoked only once when filter

is taken out of the service.

2) 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:
1. public void doFilter(HttpServletRequest request, HttpServletResponse
response): it passes the control to the next filter or resource.

How to define Filter


We can define filter same as servlet. Let's see the elements of filter and filter-
mapping.

1. <web-app>
2.
3. <filter>
4. <filter-name>...</filter-name>
5. <filter-class>...</filter-class>
6. </filter>
7.
8. <filter-mapping>
9. <filter-name>...</filter-name>
10. <url-pattern>...</url-pattern>
11. </filter-mapping>
12.
13. </web-app>

For mapping filter we can use, either url-pattern or servlet-name. The url-pattern
elements has an advantage over servlet-name element i.e. it can be applied on
servlet, JSP or HTML.

Simple Example of Filter


In this example, we are simply displaying information that filter is invoked
automatically after the post processing of the request.

index.html
1. <a href="servlet1">click here</a>
MyFilter.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3.
4. import javax.servlet.*;
5.
6. public class MyFilter implements Filter{
7.
8. public void init(FilterConfig arg0) throws ServletException {}
9.
10. public void doFilter(ServletRequest req, ServletResponse resp,
11. FilterChain chain) throws IOException, ServletException {
12.
13. PrintWriter out=resp.getWriter();
14. out.print("filter is invoked before");
15.
16. chain.doFilter(req, resp);//sends request to next resource
17.
18. out.print("filter is invoked after");
19. }
20. public void destroy() {}
21. }
HelloServlet.java
1. import java.io.IOException;
2. import java.io.PrintWriter;
3.
4. import javax.servlet.ServletException;
5. import javax.servlet.http.*;
6.
7. public class HelloServlet extends HttpServlet {
8. public void doGet(HttpServletRequest request, HttpServletResponse resp
onse)
9. throws ServletException, IOException {
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. out.print("<br>welcome to servlet<br>");
15.
16. }
17.
18. }
web.xml
For defining the filter, filter element of web-app must be defined just like servlet.

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>HelloServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <filter>
14. <filter-name>f1</filter-name>
15. <filter-class>MyFilter</filter-class>
16. </filter>
17.
18. <filter-mapping>
19. <filter-name>f1</filter-name>
20. <url-pattern>/servlet1</url-pattern>
21. </filter-mapping>
22.
23.
24. </web-app>

Authentication Filter
We can perform authentication in filter. Here, we are going to check to password
given by the user in filter class, if given password is admin, it will forward the
request to the WelcomeAdmin servlet otherwise it will display error message.

Example of authenticating user using filter


Let's see the simple example of authenticating user using filter.

Here, we have created 4 files:

o index.html
o MyFilter.java

o AdminServlet.java

o web.xml

index.html
1. <form action="servlet1">
2. Name:<input type="text" name="name"/><br/>
3. Password:<input type="password" name="password"/><br/>
4.
5. <input type="submit" value="login">
6.
7. </form>

MyFilter.java

1. import java.io.IOException;
2. import java.io.PrintWriter;
3. import javax.servlet.*;
4.
5. public class MyFilter implements Filter{
6.
7. public void init(FilterConfig arg0) throws ServletException {}
8.
9. public void doFilter(ServletRequest req, ServletResponse resp,
10. FilterChain chain) throws IOException, ServletException {
11.
12. PrintWriter out=resp.getWriter();
13.
14. String password=req.getParameter("password");
15. if(password.equals("admin")){
16. chain.doFilter(req, resp);//sends request to next resource
17. }
18. else{
19. out.print("username or password error!");
20. RequestDispatcher rd=req.getRequestDispatcher("index.html");
21. rd.include(req, resp);
22. }
23.
24. }
25. public void destroy() {}
26.
27. }

AdminServlet.java

1. import java.io.IOException;
2. import java.io.PrintWriter;
3.
4. import javax.servlet.ServletException;
5. import javax.servlet.http.*;
6.
7. public class AdminServlet extends HttpServlet {
8. public void doGet(HttpServletRequest request, HttpServletResponse respons
e)
9. throws ServletException, IOException {
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. out.print("welcome ADMIN");
15. out.close();
16. }
17. }

web.xml

1. <web-app>
2. <servlet>
3. <servlet-name>AdminServlet</servlet-name>
4. <servlet-class>AdminServlet</servlet-class>
5. </servlet>
6.
7. <servlet-mapping>
8. <servlet-name>AdminServlet</servlet-name>
9. <url-pattern>/servlet1</url-pattern>
10. </servlet-mapping>
11.
12. <filter>
13. <filter-name>f1</filter-name>
14. <filter-class>MyFilter</filter-class>
15. </filter>
16. <filter-mapping>
17. <filter-name>f1</filter-name>
18. <url-pattern>/servlet1</url-pattern>
19. </filter-mapping>
20.
21. </web-app>

FilterConfig
An object of FilterConfig is created by the web container. This object can be used to
get the configuration information from the web.xml file.

Methods of FilterConfig interface


There are following 4 methods in the FilterConfig interface.

1. public void init(FilterConfig config): init() method is invoked only once it


is used to initialize the filter.

2. public String getInitParameter(String parameterName): Returns the


parameter value for the specified parameter name.

3. public java.util.Enumeration getInitParameterNames(): Returns an


enumeration containing all the parameter names.

4. public ServletContext getServletContext(): Returns the ServletContext


object.

Example of FilterConfig
In this example, if you change the param-value to no, request will be forwarded to
the servlet otherwise filter will create the response with the message: this page is
underprocessing. Let's see the simple example of FilterConfig. Here, we have
created 4 files:

o index.html

o MyFilter.java
o HelloServlet.java

o web.xml

index.html
1. <a href="servlet1">click here</a>

MyFilter.java

1. import java.io.IOException;
2. import java.io.PrintWriter;
3.
4. import javax.servlet.*;
5.
6. public class MyFilter implements Filter{
7. FilterConfig config;
8.
9. public void init(FilterConfig config) throws ServletException {
10. this.config=config;
11. }
12.
13. public void doFilter(ServletRequest req, ServletResponse resp,
14. FilterChain chain) throws IOException, ServletException {
15.
16. PrintWriter out=resp.getWriter();
17.
18. String s=config.getInitParameter("construction");
19.
20. if(s.equals("yes")){
21. out.print("This page is under construction");
22. }
23. else{
24. chain.doFilter(req, resp);//sends request to next resource
25. }
26.
27. }
28. public void destroy() {}
29. }
HelloServlet.java

1. import java.io.IOException;
2. import java.io.PrintWriter;
3.
4. import javax.servlet.ServletException;
5. import javax.servlet.http.*;
6.
7. public class HelloServlet extends HttpServlet {
8. public void doGet(HttpServletRequest request, HttpServletResponse respons
e)
9. throws ServletException, IOException {
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. out.print("<br>welcome to servlet<br>");
15.
16. }
17.
18. }

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>HelloServlet</servlet-name>
5. <servlet-class>HelloServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>HelloServlet</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <filter>
14. <filter-name>f1</filter-name>
15. <filter-class>MyFilter</filter-class>
16. <init-param>
17. <param-name>construction</param-name>
18. <param-value>no</param-value>
19. </init-param>
20. </filter>
21. <filter-mapping>
22. <filter-name>f1</filter-name>
23. <url-pattern>/servlet1</url-pattern>
24. </filter-mapping>
25.
26.
27. </web-app>

RequestDispatcher in Servlet
The RequestDispatcher interface provides the facility of dispatching the request to
another resource it may be html, servlet or jsp. This interface can also be used to
include the content of another resource also. It is one of the way of servlet
collaboration.

There are two methods defined in the RequestDispatcher interface.

Methods of RequestDispatcher interface


The RequestDispatcher interface provides two methods. They are:

1. public void forward(ServletRequest request,ServletResponse


response)throws ServletException,java.io.IOException:Forwards a
request from a servlet to another resource (servlet, JSP file, or HTML file) on
the server.

2. public void include(ServletRequest request,ServletResponse


response)throws ServletException,java.io.IOException:Includes the
content of a resource (servlet, JSP page, or HTML file) in the response.
As you see in the above figure, response of second servlet is sent to the client.
Response of the first servlet is not displayed to the user.

As you can see in the above figure, response of second servlet is included in the

response of the first servlet that is being sent to the client.


How to get the object of RequestDispatcher
The getRequestDispatcher() method of ServletRequest interface returns the object
of RequestDispatcher. Syntax:

Syntax of getRequestDispatcher method


1. public RequestDispatcher getRequestDispatcher(String resource);
Example of using getRequestDispatcher method
1. RequestDispatcher rd=request.getRequestDispatcher("servlet2");
2. //servlet2 is the url-pattern of the second servlet
3.
4. rd.forward(request, response);//method may be include or forward

Example of RequestDispatcher interface


In this example, we are validating the password entered by the user. If password is
servlet, it will forward the request to the WelcomeServlet, otherwise will show an
error message: sorry username or password error!. In this program, we are cheking
for hardcoded information. But you can check it to the database also that we will see
in the development chapter. In this example, we have created following files:

o index.html file: for getting input from the user.

o Login.java file: a servlet class for processing the response. If password is


servet, it will forward the request to the welcome servlet.

o WelcomeServlet.java file: a servlet class for displaying the welcome


message.

o web.xml file: a deployment descriptor file that contains the information


about the servlet.
index.html

1. <form action="servlet1" method="post">


2. Name:<input type="text" name="userName"/><br/>
3. Password:<input type="password" name="userPass"/><br/>
4. <input type="submit" value="login"/>
5. </form>

Login.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class Login extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse respon
se)
9. throws ServletException, IOException {
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. String p=request.getParameter("userPass");
16.
17. if(p.equals("servlet"){
18. RequestDispatcher rd=request.getRequestDispatcher("servlet2");
19. rd.forward(request, response);
20. }
21. else{
22. out.print("Sorry UserName or Password Error!");
23. RequestDispatcher rd=request.getRequestDispatcher("/index.html");
24. rd.include(request, response);
25.
26. }
27. }
28.
29. }

WelcomeServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class WelcomeServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse resp
onse)
8. throws ServletException, IOException {
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. String n=request.getParameter("userName");
14. out.print("Welcome "+n);
15. }
16.
17. }

web.xml

1. <web-app>
2. <servlet>
3. <servlet-name>Login</servlet-name>
4. <servlet-class>Login</servlet-class>
5. </servlet>
6. <servlet>
7. <servlet-name>WelcomeServlet</servlet-name>
8. <servlet-class>WelcomeServlet</servlet-class>
9. </servlet>
10.
11.
12. <servlet-mapping>
13. <servlet-name>Login</servlet-name>
14. <url-pattern>/servlet1</url-pattern>
15. </servlet-mapping>
16. <servlet-mapping>
17. <servlet-name>WelcomeServlet</servlet-name>
18. <url-pattern>/servlet2</url-pattern>
19. </servlet-mapping>
20.
21. <welcome-file-list>
22. <welcome-file>index.html</welcome-file>
23. </welcome-file-list>
24. </web-app>
download this example
download this example (developed in Myeclipse IDE)
download this example (developed in eclipse IDE)
download this example (developed in netbeans IDE)
Servlets - Cookies Handling
Cookies are text files stored on the client computer and they are kept for various
information tracking purpose. Java Servlets transparently supports HTTP cookies.
There are three steps involved in identifying returning users −
• Server script sends a set of cookies to the browser. For example name, age,
or identification number etc.
• Browser stores this information on local machine for future use.
• When next time browser sends any request to web server then it sends those
cookies information to the server and server uses that information to identify
the user.
This chapter will teach you how to set or reset cookies, how to access them and how
to delete them.

The Anatomy of a Cookie


Cookies are usually set in an HTTP header (although JavaScript can also set a cookie
directly on a browser). A servlet that sets a cookie might send headers that look
something like this −
HTTP/1.1 200 OK
Date: Fri, 04 Feb 2000 21:03:38 GMT
Server: Apache/1.3.9 (UNIX) PHP/4.0b3
Set-Cookie: name = xyz; expires = Friday, 04-Feb-07 22:03:38 GMT;
path = /; domain = tutorialspoint.com
Connection: close
Content-Type: text/html
As you can see, the Set-Cookie header contains a name value pair, a GMT date, a
path and a domain. The name and value will be URL encoded. The expires field is an
instruction to the browser to "forget" the cookie after the given time and date.
If the browser is configured to store cookies, it will then keep this information until the
expiry date. If the user points the browser at any page that matches the path and
domain of the cookie, it will resend the cookie to the server. The browser's headers
might look something like this −
GET / HTTP/1.0
Connection: Keep-Alive
User-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)
Host: zink.demon.co.uk:1126
Accept: image/gif, */*
Accept-Encoding: gzip
Accept-Language: en
Accept-Charset: iso-8859-1,*,utf-8
Cookie: name = xyz
A servlet will then have access to the cookie through the request
method request.getCookies() which returns an array of Cookie objects.

Servlet Cookies Methods


Following is the list of useful methods which you can use while manipulating cookies
in servlet.

Sr.No. Method & Description

public void setDomain(String pattern)


1
This method sets the domain to which cookie applies, for example
tutorialspoint.com.

public String getDomain()


2
This method gets the domain to which cookie applies, for example
tutorialspoint.com.

public void setMaxAge(int expiry)


3
This method sets how much time (in seconds) should elapse before the cookie
expires. If you don't set this, the cookie will last only for the current session.
public int getMaxAge()
4
This method returns the maximum age of the cookie, specified in seconds, By
default, -1 indicating the cookie will persist until browser shutdown.

public String getName()


5
This method returns the name of the cookie. The name cannot be changed after
creation.

public void setValue(String newValue)


6
This method sets the value associated with the cookie

public String getValue()


7
This method gets the value associated with the cookie.

public void setPath(String uri)


8 This method sets the path to which this cookie applies. If you don't specify a path,
the cookie is returned for all URLs in the same directory as the current page as well
as all subdirectories.

public String getPath()


9
This method gets the path to which this cookie applies.

public void setSecure(boolean flag)


10
This method sets the boolean value indicating whether the cookie should only be
sent over encrypted (i.e. SSL) connections.

public void setComment(String purpose)


11
This method specifies a comment that describes a cookie's purpose. The comment
is useful if the browser presents the cookie to the user.

public String getComment()


12
This method returns the comment describing the purpose of this cookie, or null if
the cookie has no comment.

Setting Cookies with Servlet


Setting cookies with servlet involves three steps −
(1) Creating a Cookie object − You call the Cookie constructor with a cookie name
and a cookie value, both of which are strings.
Cookie cookie = new Cookie("key","value");
Keep in mind, neither the name nor the value should contain white space or any of
the following characters −
[ ] ( ) = , " / ? @ : ;
(2) Setting the maximum age − You use setMaxAge to specify how long (in
seconds) the cookie should be valid. Following would set up a cookie for 24 hours.
cookie.setMaxAge(60 * 60 * 24);
(3) Sending the Cookie into the HTTP response headers − You use
response.addCookie to add cookies in the HTTP response header as follows −
response.addCookie(cookie);
Example
Let us modify our Form Example to set the cookies for first and last name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloForm extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

// Create cookies for first and last names.


Cookie firstName = new Cookie("first_name",
request.getParameter("first_name"));
Cookie lastName = new Cookie("last_name",
request.getParameter("last_name"));

// Set expiry date after 24 Hrs for both the cookies.


firstName.setMaxAge(60*60*24);
lastName.setMaxAge(60*60*24);

// Add both the cookies in the response header.


response.addCookie( firstName );
response.addCookie( lastName );

// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Setting Cookies Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head>
<title>" + title + "</title>
</head>\n" +

"<body bgcolor = \"#f0f0f0\">\n" +


"<h1 align = \"center\">" + title + "</h1>\n" +
"<ul>\n" +
" <li><b>First Name</b>: "
+ request.getParameter("first_name") + "\n" +
" <li><b>Last Name</b>: "
+ request.getParameter("last_name") + "\n" +
"</ul>\n" +
"</body>
</html>"
);
}
}

Compile the above servlet HelloForm and create appropriate entry in web.xml file
and finally try following HTML page to call servlet.

<html>
<body>
<form action = "HelloForm" method = "GET">
First Name: <input type = "text" name = "first_name">
<br />
Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>
</body>
</html>

Keep above HTML content in a file Hello.htm and put it in <Tomcat-


installationdirectory>/webapps/ROOT directory. When you would
access http://localhost:8080/Hello.htm, here is the actual output of the above form.

First Name:
Last Name:

Try to enter First Name and Last Name and then click submit button. This would
display first name and last name on your screen and same time it would set two
cookies firstName and lastName which would be passed back to the server when
next time you would press Submit button.
Next section would explain you how you would access these cookies back in your
web application.
Reading Cookies with Servlet
To read cookies, you need to create an array of javax.servlet.http.Cookie objects by
calling the getCookies() method of HttpServletRequest. Then cycle through the
array, and use getName() and getValue() methods to access each cookie and
associated value.
Example
Let us read cookies which we have set in previous example −
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class ReadCookies extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

Cookie cookie = null;


Cookie[] cookies = null;

// Get an array of Cookies associated with this domain


cookies = request.getCookies();

// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Reading Cookies Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" );

if( cookies != null ) {


out.println("<h2> Found Cookies Name and Value</h2>");

for (int i = 0; i < cookies.length; i++) {


cookie = cookies[i];
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( ) + " <br/>");
}
} else {
out.println("<h2>No cookies founds</h2>");
}
out.println("</body>");
out.println("</html>");
}
}

Compile above servlet ReadCookies and create appropriate entry in web.xml file. If
you would have set first_name cookie as "John" and last_name cookie as "Player"
then running http://localhost:8080/ReadCookies would display the following result −

Found Cookies Name and Value


Name : first_name, Value: John

Name : last_name, Value: Player


Delete Cookies with Servlet
To delete cookies is very simple. If you want to delete a cookie then you simply need
to follow up following three steps −
• 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
The following example would delete and existing cookie named "first_name" and
when you would run ReadCookies servlet next time it would return null value for
first_name.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class DeleteCookies extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

Cookie cookie = null;


Cookie[] cookies = null;

// Get an array of Cookies associated with this domain


cookies = request.getCookies();

// Set response content type


response.setContentType("text/html");

PrintWriter out = response.getWriter();


String title = "Delete Cookies Example";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor = \"#f0f0f0\">\n" );

if( cookies != null ) {


out.println("<h2> Cookies Name and Value</h2>");

for (int i = 0; i < cookies.length; i++) {


cookie = cookies[i];

if((cookie.getName( )).compareTo("first_name") == 0 )
{
cookie.setMaxAge(0);
response.addCookie(cookie);
out.print("Deleted cookie : " + cookie.getName( )
+ "<br/>");
}
out.print("Name : " + cookie.getName( ) + ", ");
out.print("Value: " + cookie.getValue( )+" <br/>");
}
} else {
out.println("<h2>No cookies founds</h2>");
}
out.println("</body>");
out.println("</html>");
}
}

Compile above servlet DeleteCookies and create appropriate entry in web.xml file.
Now running http://localhost:8080/DeleteCookies would display the following result −

Cookies Name and Value

Deleted cookie : first_name

Name : first_name, Value: John

Name : last_name, Value: Player

Now try to run http://localhost:8080/ReadCookies and it would display only one


cookie as follows −

Found Cookies Name and Value


Name : last_name, Value: Player
You can delete your cookies in Internet Explorer manually. Start at the Tools menu
and select Internet Options. To delete all cookies, press Delete Cookies.

Servlets - Session Tracking


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.
Still there are following three ways to maintain session between web client and web
server −

Cookies
A webserver can assign a unique session ID as a cookie to each web client and for
subsequent requests from the client they can be recognized using the recieved
cookie.
This may not be an effective way because many time browser does not support a
cookie, so I would not recommend to use this procedure to maintain the sessions.

Hidden Form Fields


A web server can send a hidden HTML form field along with a unique session ID as
follows −
<input type = "hidden" name = "sessionid" value = "12345">
This entry means that, when the form is submitted, the specified name and value are
automatically included in the GET or POST data. Each time when web browser sends
request back, then session_id value can be used to keep the track of different web
browsers.
This could be an effective way of keeping track of the session but clicking on a regular
(<A HREF...>) hypertext link does not result in a form submission, so hidden form
fields also cannot support general session tracking.

URL Rewriting
You can append some extra data on the end of each URL that identifies the session,
and the server can associate that session identifier with data it has stored about that
session.
For example, with http://tutorialspoint.com/file.htm;sessionid = 12345, the session
identifier is attached as sessionid = 12345 which can be accessed at the web server
to identify the client.
URL rewriting is a better way to maintain sessions and it works even when browsers
don't support cookies. The drawback of URL re-writing is that you would have to
generate every URL dynamically to assign a session ID, even in case of a simple
static HTML page.
The HttpSession Object
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 or visit to
a Web site and to store information about that user.
The servlet container uses this interface to create a session between an HTTP client
and an HTTP server. The session persists for a specified time period, across more
than one connection or page request from the user.
You would get HttpSession object by calling the public method getSession() of
HttpServletRequest, as below −
HttpSession session = request.getSession();

You need to call request.getSession() before you send any document content to the
client. Here is a summary of the important methods available through HttpSession
object −

Sr.No. Method & Description

public Object getAttribute(String name)


1
This method returns the object bound with the specified name in this session, or
null if no object is bound under the name.

public Enumeration getAttributeNames()


2
This method returns an Enumeration of String objects containing the names of all
the objects bound to this session.

public long getCreationTime()


3
This method returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.

public String getId()


4
This method returns a string containing the unique identifier assigned to this
session.

public long getLastAccessedTime()


5
This method returns the last accessed time of the session, in the format of
milliseconds since midnight January 1, 1970 GMT

6 public int getMaxInactiveInterval()


This method returns the maximum time interval (seconds), that the servlet container
will keep the session open between client accesses.

public void invalidate()


7
This method invalidates this session and unbinds any objects bound to it.

public boolean isNew(


8
This method returns true if the client does not yet know about the session or if the
client chooses not to join the session.

public void removeAttribute(String name)


9
This method removes the object bound with the specified name from this session.

public void setAttribute(String name, Object value)


10
This method binds an object to this session, using the name specified.

public void setMaxInactiveInterval(int interval)


11
This method specifies the time, in seconds, between client requests before the
servlet container will invalidate this session.

Session Tracking Example


This example describes how to use the HttpSession object to find out the creation
time and the last-accessed time for a session. We would associate a new session
with the request if one does not already exist.
// Import required java libraries
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;

// Extend HttpServlet class


public class SessionTrack extends HttpServlet {

public void doGet(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException {

// Create a session object if it is already not created.


HttpSession session = request.getSession(true);

// Get session creation time.


Date createTime = new Date(session.getCreationTime());
// Get last access time of this web page.
Date lastAccessTime = new
Date(session.getLastAccessedTime());

String title = "Welcome Back to my website";


Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");

// Check if this is new comer on your web page.


if (session.isNew()) {
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
} else {
visitCount =
(Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
}
session.setAttribute(visitCountKey, visitCount);

// Set response content type


response.setContentType("text/html");
PrintWriter out = response.getWriter();

String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";

out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +

"<body bgcolor = \"#f0f0f0\">\n" +


"<h1 align = \"center\">" + title + "</h1>\n" +
"<h2 align = \"center\">Session Infomation</h2>\n"
+
"<table border = \"1\" align = \"center\">\n" +

"<tr bgcolor = \"#949494\">\n" +


" <th>Session info</th><th>value</th>
</tr>\n" +

"<tr>\n" +
" <td>id</td>\n" +
" <td>" + session.getId() + "</td>
</tr>\n" +

"<tr>\n" +
" <td>Creation Time</td>\n" +
" <td>" + createTime + " </td>
</tr>\n" +

"<tr>\n" +
" <td>Time of Last Access</td>\n" +
" <td>" + lastAccessTime + " </td>
</tr>\n" +

"<tr>\n" +
" <td>User ID</td>\n" +
" <td>" + userID + " </td>
</tr>\n" +

"<tr>\n" +
" <td>Number of visits</td>\n" +
" <td>" + visitCount + "</td>
</tr>\n" +
"</table>\n" +
"</body>
</html>"
);
}
}

Compile the above servlet SessionTrack and create appropriate entry in web.xml
file. Now running http://localhost:8080/SessionTrack would display the following
result when you would run for the first time −

Welcome to my website
Session Infomation

Session info value

id 0AE3EC93FF44E3C525B4351B77ABB2D5

Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010

Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010

User ID ABCD

Number of visits 0
Now try to run the same servlet for second time, it would display following result.

Welcome Back to my website


Session Infomation

info type value

id 0AE3EC93FF44E3C525B4351B77ABB2D5

Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010

Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010

User ID ABCD

Number of visits 1

Deleting Session Data


When you are done with a user's session data, you have several options −
• Remove a particular attribute − You can call public void
removeAttribute(String name) method to delete the value associated with a
particular key.
• Delete the whole session − You can call public void invalidate() method to
discard an entire session.
• Setting Session timeout − You can call public void setMaxInactiveInterval(int
interval) method to set the timeout for a session individually.
• Log the user out − The servers that support servlets 2.4, you can
call logout to log the client out of the Web server and invalidate all sessions
belonging to all the users.
• web.xml Configuration − If you are using Tomcat, apart from the above
mentioned methods, you can configure session time out in web.xml file as
follows.
<session-config>
<session-timeout>15</session-timeout>
</session-config>
The timeout is expressed as minutes, and overrides the default timeout which is 30
minutes in Tomcat.
The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that
session in seconds. So if your session is configured in web.xml for 15 minutes,
getMaxInactiveInterval( ) returns 900.

You might also like