User tracking in servlet in java

Satyapriyanayak
Posted by Satyapriyanayak under Others category on | Points: 40 | Views : 763
User tracking :- This is a process to keep information about users in multiple pages.Whenever user gives information to a servlet  then the destination servlet servlet can find values from the request by using getParameter() method.When the user provides a new request then the values avalable in previous request get lost,this is the nature of stateless protocol.Http is a stateless protocol.User tracking helps to keep information about users even if the request gets changed.This can be done is four different ways given below:
1.Url rewritting
2.Hidden field
3.Cookie
4.Session
First we will discuss about
Url rewritting:-This is a process to create an explict querystring with the help of a hyperlink.The href attribute of <a> tag can contain path of the destination with the querystring.Whenever user clicks on hyperlink then destination servlet can fetch values by using getParameter() method of the request.

Example:-In the first file 1 to 100 numbers will be displayed when user will click the number another page will appear showing that number the user has click the number previously.
First.java file
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class first extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
PrintWriter out=res.getWriter();
out.println("<h2>");
for(int i=1;i<101;i++)
out.println("<a href='./second?x="+i+"'>"+i+"</a>&nbsp;" );
}
}
Second.java file
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
public class second extends HttpServlet
{
public void doGet(HttpServletRequest req,HttpServletResponse res)throws ServletException,IOException
{
PrintWriter out=res.getWriter();
String s=req.getParameter("x");
out.println("<html><body>");
out.println("<h1>"+"You clicked:"+s+"</h1>");
out.println("</body></html>");
}
}
Web.xml settings
<?xml version="1.0" encoding="ISO-8859-1"?>

<servlet>
<servlet-name>first</servlet-name>
<servlet-class>first</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>first</servlet-name>
<url-pattern>/first</url-pattern>
</servlet-mapping>

<servlet>
<servlet-name>second</servlet-name>
<servlet-class>second</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>second</servlet-name>
<url-pattern>/second</url-pattern>
</servlet-mapping>

</web-app>

Compile both the files as below
javac -cp servlet-api.jar first.java (for tomcat 6.0)
javac -cp servlet-api.jar second.java (for tomcat 6.0)


Run the tomcat then write the below line in the Url
Here test is the Context path, which we mentioned in the server.xml file, which is present in (E:\Program Files\Apache Software Foundation\Tomcat 6.0\conf) directory.
http://localhost:8081/test/first

Comments or Responses

Login to post response