import java.io.*;
import java.util.Random;
import javax.servlet.http.*;
import javax.servlet.ServletException;
public class CookieServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Cookie[] coki = request.getCookies();
Cookie tokens = null;
if(coki !=null) {
for(int i=0; i<coki.length; i++) {
if (coki[i].getName().equals("token")) {
tokens = coki[i];
break;
}
}
}
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("<html><head><title>Tokens</title></head><body ");
pw.println("style=\"fonr-family:verdana;font-size:10pt\">");
String reset = request.getParameter("reset");
if(tokens==null || (reset != null && reset.equals("yes"))) {
Random rnd = new Random();
long id = rnd.nextLong();
pw.println("<p>Welcome. A new token " + id + " is now established</p>");
tokens = new Cookie("token", Long.toString(id));
tokens.setComment("Token to identity user");
tokens.setMaxAge(-1);
tokens.setPath("/cookie/track");
response.addCookie(tokens);
} else {
pw.println("Welcome back.. Your token is " + tokens.getValue() + ".</p>");
}
String requestURLSame = request.getRequestURL().toString();
String requestURLNew = request.getRequestURL() + "?reset = yes";
pw.println("<p>Click <a href=" + requestURLSame +" > here </a> again to continue browsing with the "+ " same identify.</p>");
pw.println("<p>Otherwise, click <a href = " + requestURLNew + "> here</a> again to start browsing with a new identify. </p>");
pw.println("</body></html>");
pw.close();
}
}
|