import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(); String username = (String) session.getAttribute("username"); // use username to perform some action } }
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; public class MyServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) { HttpSession session = request.getSession(true); session.setAttribute("visited", true); } }In this example, we create a new session if one does not already exist (by passing "true" to getSession()), and then set a "visited" attribute on the session to indicate that the user has visited this page. The HttpServletRequest.getSession() method is part of the javax.servlet.http package/library, which is included in the Java Servlet API.