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

Servlet Config Context and Session Tracking

Knowing about networking and ip and servlet

Uploaded by

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

Servlet Config Context and Session Tracking

Knowing about networking and ip and servlet

Uploaded by

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

ServletRequest Interface

An object of ServletRequest is used to provide the client request information to a


servlet such as content type, content length, parameter names and values, header
informations, attributes etc.
Methods of ServletRequest interface
There are many methods defined in the ServletRequest interface. Some of them
are as follows:

Method Description

public String getParameter(String is used to obtain the value of a parameter


name) by name.

public String[] returns an array of String containing all


getParameterValues(String name) values of given parameter name. It is
mainly used to obtain values of a Multi
select list box.

java.util.Enumeration returns an enumeration of all of the


getParameterNames() request parameter names.

public int getContentLength() Returns the size of the request entity data,
or -1 if not known.

public String Returns the character set encoding for the


getCharacterEncoding() input of this request.

public String getContentType() Returns the Internet Media Type of the


request entity data, or null if not known.

public ServletInputStream Returns an input stream for reading binary


getInputStream() throws data in the request body.
IOException

public abstract String Returns the host name of the server that
getServerName() received the request.
public int getServerPort() Returns the port number on which this
request was received.
index.html
1. <form action="welcome" method="get">
2. Enter your name<input type="text" name="name"><br>
3. <input type="submit" value="login">
4. </form>
DemoServ.java
1. import javax.servlet.http.*;
2. import javax.servlet.*;
3. import java.io.*;
4. public class DemoServ extends HttpServlet{
5. public void doGet(HttpServletRequest req,HttpServletResponse res)
6. throws ServletException,IOException
7. {
8. res.setContentType("text/html");
9. PrintWriter pw=res.getWriter();
10. String name=req.getParameter("name");//will return value
11. pw.println("Welcome "+name);
12. pw.close();
13. }}
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.
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. public class Login extends HttpServlet {
6. public void doPost(HttpServletRequest request, HttpServletResponse response)
7. throws ServletException, IOException {
8. response.setContentType("text/html");
9. PrintWriter out = response.getWriter();
10. String n=request.getParameter("userName");
11. String p=request.getParameter("userPass");
12. if(p.equals("servlet"){
13. RequestDispatcher rd=request.getRequestDispatcher("servlet2");
14. rd.forward(request, response);
15. }
16. else{
17. out.print("Sorry UserName or Password Error!");
18. RequestDispatcher rd=request.getRequestDispatcher("/index.html");
19. rd.include(request, response);
20. }
21. }
22. }
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 response)

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. <servlet-mapping>
12. <servlet-name>Login</servlet-name>
13. <url-pattern>/servlet1</url-pattern>
14. </servlet-mapping>
15. <servlet-mapping>
16. <servlet-name>WelcomeServlet</servlet-name>
17. <url-pattern>/servlet2</url-pattern>
18. </servlet-mapping>
19.
20. <welcome-file-list>
21. <welcome-file>index.html</welcome-file>
22. </welcome-file-list>
23. </web-app>
SendRedirect in servlet
The sendRedirect() method of HttpServletResponse interface can be used to
redirect response to another resource, it may be servlet, jsp or html file.
It accepts relative as well as absolute URL.
It works at client side because it uses the url bar of the browser to make another
request. So, it can work inside and outside the server.

Difference between forward() and sendRedirect()


method
There are many differences between the forward() method of RequestDispatcher
and sendRedirect() method of HttpServletResponse interface. They are given
below:

forward() method sendRedirect() method

The forward() method works at server side. The sendRedirect() method


works at client side.

It sends the same request and response objects to It always sends a new request.
another servlet.

It can work within the server only. It can be used within and
outside the server.

Example: Example:
request.getRequestDispacher("servlet2").forward(re response.sendRedirect("servle
quest,response); t2");

example of sendRedirect method in 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 req,HttpServletResponse res)
7. throws ServletException,IOException
8. {
9. res.setContentType("text/html");
10. PrintWriter pw=res.getWriter();
11.
12. response.sendRedirect("http://www.google.com");
13.
14. pw.close();
15. }}
index.html
1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>sendRedirect example</title>
6. </head>
7. <body>
8.
9.
10. <form action="MySearcher">
11. <input type="text" name="name">
12. <input type="submit" value="Google Search">
13. </form>
14.
15. </body>
16. </html>

MySearcher.java
1. import java.io.IOException;
2. import javax.servlet.ServletException;
3. import javax.servlet.http.HttpServlet;
4. import javax.servlet.http.HttpServletRequest;
5. import javax.servlet.http.HttpServletResponse;
6.
7. public class MySearcher extends HttpServlet {
8. protected void doGet(HttpServletRequest request, HttpServletResponse respo
nse)
9. throws ServletException, IOException {
10.
11. String name=request.getParameter("name");
12. response.sendRedirect("https://www.google.co.in/#q="+name);
13. }
14. }

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
getServletConfig() method of Servlet interface returns the object of
ServletConfig.
Syntax of getServletConfig() method
public ServletConfig getServletConfig();
Example of getServletConfig() method
ServletConfig config=getServletConfig();
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 response)
7. throws ServletException, IOException {
8.
9. response.setContentType("text/html");
10. PrintWriter out = response.getWriter();
11. ServletConfig config=getServletConfig();
12. String driver=config.getInitParameter("driver");
13. out.print("Driver is: "+driver);
14. out.close();
15. }
16. }

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

14. </web-app>

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


public ServletContext getServletContext()
Example of getServletContext() method
//We can get the ServletContext object from ServletConfig object
ServletContext application=getServletConfig().getServletContext();

//Another convenient way to get the ServletContext object


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.
<web-app>
......
<context-param>
<param-name>parametername</param-name>
<param-value>parametervalue</param-value>
</context-param>
......
</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>sonoojaiswal</servlet-name>
25. <url-pattern>/context</url-pattern>
26. </servlet-mapping>
27.
28. </web-app>

Session Tracking in Servlets


Session simply means a particular interval of time.

Session Tracking is a way to maintain state (data) of an user. It is also known as session
management in servlet.

Http protocol is a stateless so we need to maintain state using session tracking techniques.
Each time user requests to the server, server treats the request as the new request. So we
need to maintain the state of an user to recognize to particular user.

HTTP is stateless that means each request is considered as the new request. It is shown in
the figure given below:
Why use Session Tracking?

To recognize the user It is used to recognize the particular user.

Session Tracking Techniques


There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client
requests.

A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.

How Cookie works


By default, each request is considered as a new request. In cookies technique, we add cookie
with response from the servlet. So cookie is stored in the cache of the browser. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the
user as the old user.
Types of Cookie
There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie

It is valid for multiple session . It is not removed each time when user closes the browser. It
is removed only if user logout or signout.

Advantage of Cookies
1. Simplest technique of maintaining the state.
2. Cookies are maintained at client side.

Disadvantage of Cookies
1. It will not work if cookie is disabled from the browser.
2. Only textual information can be set in Cookie object.

Note: Gmail uses cookie technique for login. If you disable the cookie, gmail won't work.

Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a lot of
useful methods for cookies.

Constructor of Cookie class

Constructor Description

Cookie() constructs a cookie.


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

Useful Methods of Cookie class

There are given some commonly used methods of the Cookie class.

Method Description

public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)

public String getName() Returns the name of the cookie. The name cannot be changed
after creation.

public String getValue() Returns the value of the cookie.

public void setName(String changes the name of the cookie.


name)

public void setValue(String changes the value of the cookie.


value)

Other methods required for using Cookies

For adding cookie or getting the value from the cookie, we need some methods provided by
other interfaces. They are:
1. public void addCookie(Cookie ck):method of HttpServletResponse interface is used to
add cookie in response object.
2. public Cookie[] getCookies():method of HttpServletRequest interface is used to return all
the cookies from the browser.

How to create Cookie?


Let's see the simple code to create cookie.

Cookie ck=new Cookie("user","sonoo jaiswal");//creating cookie object


response.addCookie(ck);//adding cookie in the response

How to delete Cookie?


Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.

Cookie ck=new Cookie("user","");//deleting value of cookie


ck.setMaxAge(0);//changing the maximum age to 0 seconds
response.addCookie(ck);//adding cookie in the response

How to get Cookies?


Let's see the simple code to get all the cookies.

1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of cookie
4. }

Simple example of Servlet Cookies


In this example, we are storing the name of the user in the cookie object and accessing it in
another servlet. As we know well that session corresponds to the particular user. So if you
access it from too many browsers with different values, you will get the different value.
index.html

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


2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. Cookie ck=new Cookie("uname",n);//creating cookie object
18. response.addCookie(ck);//adding cookie in the response
19. //creating submit button
20. out.print("<form action='servlet2'>");
21. out.print("<input type='submit' value='go'>");
22. out.print("</form>");
23. out.close();
24. }catch(Exception e){System.out.println(e);}
25. }
26. }
SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse response){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. Cookie ck[]=request.getCookies();
14. out.print("Hello "+ck[0].getValue());
15.
16. out.close();
17.
18. }catch(Exception e){System.out.println(e);}
19. }
20.
21.
22. }

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</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>SecondServlet</servlet-class>
16. </servlet>
17. <servlet-mapping>
18. <servlet-name>s2</servlet-name>
19. <url-pattern>/servlet2</url-pattern>
20. </servlet-mapping>
21. </web-app>

2) Hidden Form Field


In case of Hidden Form Field a hidden (invisible) textfield is used for maintaining the state
of an user.

In such case, we store the information in the hidden field and get it from another servlet.
This approach is better if we have to submit form in all the pages and we don't want to
depend on the browser.

Let's see the code to store value in hidden field.

<input type="hidden" name="uname" value="Vimal Jaiswal">

Here, uname is the hidden field name and Vimal Jaiswal is the hidden field value.

Real application of hidden form field

It is widely used in comment form of a website. In such case, we store page id or page name
in the hidden field so that each page can be uniquely identified.

Advantage of Hidden Form Field

1. It will always work whether cookie is disabled or not.


Disadvantage of Hidden Form Field:

1. It is maintained at server side.


2. Extra form submission is required on each pages.
3. Only textual information can be used.

Example of using Hidden Form Field


In this example, we are storing the name of the user in a hidden textfield and getting that
value from another servlet.

index.html

1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class FirstServlet extends HttpServlet {
6. public void doGet(HttpServletRequest request, HttpServletResponse response){
7. try{
8.
9. response.setContentType("text/html");
10. PrintWriter out = response.getWriter();
11.
12. String n=request.getParameter("userName");
13. out.print("Welcome "+n);
14.
15. //creating form that have invisible textfield
16. out.print("<form action='servlet2'>");
17. out.print("<input type='hidden' name='uname' value='"+n+"'>");
18. out.print("<input type='submit' value='go'>");
19. out.print("</form>");
20. out.close();
21.
22. }catch(Exception e){System.out.println(e);}
23. }
24.
25. }

SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4. public class SecondServlet extends HttpServlet {
5. public void doGet(HttpServletRequest request, HttpServletResponse response)
6. try{
7. response.setContentType("text/html");
8. PrintWriter out = response.getWriter();
9.
10. //Getting the value from the hidden field
11. String n=request.getParameter("uname");
12. out.print("Hello "+n);
13.
14. out.close();
15. }catch(Exception e){System.out.println(e);}
16. }
17. }

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</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>SecondServlet</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>
3)URL Rewriting
In URL rewriting, we append a token or identifier to the URL of the next Servlet or the next
resource. We can send parameter name/value pairs using the following format:

url?name1=value1&name2=value2&??

A name and a value is separated using an equal = sign, a parameter name/value pair is
separated from another parameter using the ampersand(&). 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.

Advantage of URL Rewriting

1. It will always work whether cookie is disabled or not (browser independent).


2. Extra form submission is not required on each pages.

Disadvantage of URL Rewriting

1. It will work only with links.


2. It can send Only textual information.
Example of using URL Rewriting
In this example, we are maintaning the state of the user using link. For this purpose, we are
appending the name of the user in the query string and getting the value from the query
string in another page.

index.html

1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class FirstServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse response){
8. try{
9. response.setContentType("text/html");
10. PrintWriter out = response.getWriter();
11.
12. String n=request.getParameter("userName");
13. out.print("Welcome "+n);
14. //appending the username in the query string
15. out.print("<a href='servlet2?uname="+n+"'>visit</a>");
16. out.close();
17.
18. }catch(Exception e){System.out.println(e);}
19. }
20. }
SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse response)
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. //getting value from the query string
14. String n=request.getParameter("uname");
15. out.print("Hello "+n);
16.
17. out.close();
18.
19. }catch(Exception e){System.out.println(e);}
20. }
21.
22.
23. }

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</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>SecondServlet</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>

4) HttpSession interface
In such case, container creates a session id for each user.The container uses this id to identify
the particular user.An object of HttpSession can be used to perform two tasks:

1. bind objects
2. view and manipulate information about a session, such as the session identifier, creation time,
and last accessed time.
How to get the HttpSession object ?

The HttpServletRequest interface provides two methods to get the object of HttpSession:

1. public HttpSession getSession():Returns the current session associated with this request, or
if the request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current HttpSession associated
with this request or, if there is no current session and create is true, returns a new session.

Commonly used methods of HttpSession interface

1. public String getId():Returns a string containing the unique identifier value.


2. public long getCreationTime():Returns the time when this session was created, measured in
milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1, 1970
GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.

Example of using HttpSession


In this example, we are setting the attribute in the session scope in one servlet and getting
that value from the session scope in another servlet. To set the attribute in the session
scope, we have used the setAttribute() method of HttpSession interface and to get the
attribute, we have used the getAttribute method.

index.html

1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doGet(HttpServletRequest request, HttpServletResponse response){
9. try{
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12. String n=request.getParameter("userName");
13. out.print("Welcome "+n);
14.
15. HttpSession session=request.getSession();
16. session.setAttribute("uname",n);
17.
18. out.print("<a href='servlet2'>visit</a>");
19. out.close();
20.
21. }catch(Exception e){System.out.println(e);}
22. }
23. }
SecondServlet.java

1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doGet(HttpServletRequest request, HttpServletResponse response)
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. HttpSession session=request.getSession(false);
14. String n=(String)session.getAttribute("uname");
15. out.print("Hello "+n);
16.
17. out.close();
18. }catch(Exception e){System.out.println(e);}
19. }
20. }

web.xml

1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</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>SecondServlet</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>

You might also like