Site icon WebArtDeveloper

How to Perform Session Tracking using HTTP Session in Servlets

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

Code:

index.html

<html>
<head>
<title>Http Session 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”>
<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 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+”<br>”);
HttpSession session=request.getSession();
session.setAttribute(“uname”,n);
out.println(“<a href=’page2′>Visit</a>”);
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 doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType(“text/html;charset=UTF-8”);
try (PrintWriter out = response.getWriter()) {
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute(“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>”);
}
}

}

https://youtu.be/QENnHiJkAN4

Exit mobile version