Skip to content

Instantly share code, notes, and snippets.

@kencoba
Created June 3, 2023 11:40
Show Gist options
  • Save kencoba/d455600db24e882381e6bae0c0d010bb to your computer and use it in GitHub Desktop.
Save kencoba/d455600db24e882381e6bae0c0d010bb to your computer and use it in GitHub Desktop.
A sample servlet for understanding between a request and a sesson.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
@WebServlet("/counter")
public class CounterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
HttpSession session = request.getSession();
Integer reqCounter = (Integer) request.getAttribute("counter");
if (reqCounter == null) {
request.setAttribute("counter", 0);
} else {
request.setAttribute("counter", reqCounter + 1);
}
Integer sesCounter = (Integer) session.getAttribute("counter");
if (sesCounter == null) {
session.setAttribute("counter", 0);
} else {
session.setAttribute("counter", sesCounter + 1);
}
PrintWriter out = response.getWriter();
out.println("request counter: " + (Integer) request.getAttribute("counter"));
out.println("session counter: " + (Integer) session.getAttribute("counter"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment