大家都知道用户和web应用交互,通过Session的方式。
那么客户端是如何在服务器上一下子找到属于自己的那个Session呢?
一般情况下,客户端是通过cookie 的方式找到服务器上的Session的。
可以打开自己的浏览器找到SESSIONID 这个cookie。里面存放的就是用户使用的Session。
那么当用户手动的禁用掉了Cookie呢?
那么此时,会出现当用户访问一个web应用多个页面的时候,会出现遗失了Session的"假象".
其实用户的Session还存在服务器上,只不过遗失了。
对于这种现象,JavaEE提供了解决方法。
就是采用URL重写的方法,在请求地址之后加上;jsessionid=HttpSession对象的Id号
HttpSession session = req.getSession();
//调用这行代码之前先调用以下上面一条代码.
String path = resp.encodeRedirectURL("/world");
这两行代码可以弥补因为禁用Cookie而产生的用户session丢失的"假象".
那么客户端是如何在服务器上一下子找到属于自己的那个Session呢?
一般情况下,客户端是通过cookie 的方式找到服务器上的Session的。
可以打开自己的浏览器找到SESSIONID 这个cookie。里面存放的就是用户使用的Session。
那么当用户手动的禁用掉了Cookie呢?
那么此时,会出现当用户访问一个web应用多个页面的时候,会出现遗失了Session的"假象".
其实用户的Session还存在服务器上,只不过遗失了。
对于这种现象,JavaEE提供了解决方法。
就是采用URL重写的方法,在请求地址之后加上;jsessionid=HttpSession对象的Id号
HttpSession session = req.getSession();
//调用这行代码之前先调用以下上面一条代码.
String path = resp.encodeRedirectURL("/world");
这两行代码可以弥补因为禁用Cookie而产生的用户session丢失的"假象".
在粘贴上两个Servlet的演示效果。
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.io.IOException;
@WebServlet(urlPatterns = "/hello")
public class MyServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
HttpSession session = req.getSession();
String path = resp.encodeRedirectURL( "/world" );
System.out.println( "jsessionId是:" + req.getSession().getId() );
String sessionId = req.getSession().getId();
req.setAttribute( "sessionId",sessionId );
resp.sendRedirect( path );
// req.getRequestDispatcher( "path" ).forward( req, resp );
}
}
==============================================================================================
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 java.io.IOException;
@WebServlet(urlPatterns = "/world")
public class AnotherServlet extends HttpServlet
{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException
{
System.out.println("跳跃到另一个Servlet的jsessionId是:" + req.getSession().getId());
// System.out.println("两个Session相等么" + req.getAttribute( "sessionId" ).equals( req.getSession().getId() ));
}
}