Servlet六(Session)

Servlet六—HttpSession


HttpSession是保存在服务器中的用户会话标识。当同一个用户访问多个URL时,其session相同,并且在做URL跳转时,可将相关信息带入到session中,代码如下:

public class HelloWorld extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        
        HttpSession session = request.getSession();
        session.setAttribute("userName", "HelloWorld");
        response.sendRedirect("getUserName");
    }
}

这段代码中,session保存了userName信息,并跳转到getUserName,下面在getUserName的Servlet中获取Session,代码如下:

public class getUserName extends HttpServlet{
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        
        HttpSession session = request.getSession();
        response.setContentType("text/html"); 
        PrintWriter out = response.getWriter();
        out.println(session.getAttribute("userName"));
    }
}

Session的值是保存在servlet容器的内存中,如果采用多个Web服务器的集群架构,那么,服务器之间的Session只能通过数据库共享实现。

猜你喜欢

转载自blog.csdn.net/xiaolicd/article/details/81636256