In this tutorial how to perform session tracking using Hidden Field in servlets is shown.
Code:
index.html
<html>
<head>
<title>Hidden Field 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;
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 n=request.getParameter(“username”);
/* 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 “+n);
out.println(“<form action=’page2′ method=’POST’>”);
out.println(“<input type=’hidden’ name=’uname’ value='”+n+”‘>”);
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;
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()) {
String n=request.getParameter(“uname”);
/* 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 “+n);
out.println(“</body>”);
out.println(“</html>”);
}
}
}