Site icon WebArtDeveloper

How to Perform Session Tracking using Cookie in Servlets

In this tutorial how to perform session tracking using Cookie in servlets is shown.

Code:

index.html

<html>
<head>
<title>Cookie Program</title>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
</head>
<body>
<form action=”page1″ method=”POST”>
Name:<input type=”text” name=”userName”><br>
<input type=”submit” value=”Go”>
</form>
</body>
</html>

page1.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.*;
public class page1 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);
try (PrintWriter out = response.getWriter()) {
String s=request.getParameter(“userName”);
Cookie ck=new Cookie(“uname”,s);
response.addCookie(ck);
/* TODO output your page here. You may use following sample code. */
out.println(“<!DOCTYPE html>”);
out.println(“<html>”);
out.println(“<head>”);
out.println(“<title>Servlet page1</title>”);
out.println(“</head>”);
out.println(“<body>”);
out.println(“Welcome “+s);
out.println(“<form action=’page2′ method=’POST’>”);
out.println(“<input type=’submit’ value=’Go’>”);
out.println(“</form>”);
out.println(“</body>”);
out.println(“</html>”);

}
}

}

page2.java

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.*;

public class page2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);
try (PrintWriter out = response.getWriter()) {
Cookie ck[]=request.getCookies();
/* TODO output your page here. You may use following sample code. */
out.println(“<!DOCTYPE html>”);
out.println(“<html>”);
out.println(“<head>”);
out.println(“<title>Servlet page2</title>”);
out.println(“</head>”);
out.println(“<body>”);
out.println(“Hello “+ck[0].getValue());
out.println(“</body>”);
out.println(“</html>”);
}
}

}

https://youtu.be/VOHrPE1ftiU

Exit mobile version