Session会话跟踪的三种方式

若客户端未禁用cookie,sessionId会自动的写入Cookie中,不需要编程,web容器自动完成

1 当客户端禁用cookie时,通过URL重写来实现会话跟踪

  1. servlet

    HttpSession session = req.getSession();
    String url = resp.encodeRedirectURL("index.jsp");
    resp.sendRedirect(url);
    
  2. 浏览器地址栏中的地址
    http://localhost:8080/Test/index.jsp;jsessionid=83F3CD5C7FCC72436DAC98EB9E136D20

2 当客户端禁用cookie时,通过超链接重定向来实现会话跟踪

1. servlet

	String url2 = resp.encodeURL("index.jsp");
	System.out.println("Url2 = " + url2);

2. 打印结果:
Url2 = index.jsp;jsessionid=83F3CD5C7FCC72436DAC98EB9E136D20

3 两者综合使用(浏览器禁用Cookie)

  1. servlet文件

    public class SessionIdTest extends HttpServlet {
    
    	@Override
    	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
    			throws ServletException, IOException {
    		
    		HttpSession session = req.getSession();
    		
    		String RedirectURL ="index.jsp";
    
    		//如果将下面一行注解掉,则在index.jsp文件中的超链接将无法跳转
    		RedirectURL = resp.encodeRedirectURL("index.jsp");
    		
    		String url = resp.encodeURL("main.jsp");
    		
    		session.setAttribute("url", url);
    		
    		resp.sendRedirect(RedirectURL);
    	}
    }
    
  2. web.xml文件

      
      	SessionIdTest
      	com.xiaoming.SessionIdTest
      
      
      	SessionIdTest
      	/s
      
    
  3. index.jsp文件

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    
    
         
        index.jsp
       
      
        This is my JSP page. 
    " >去往main.html
  4. main.html文件

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    
    
        
        main.jsp
      
      
        This is my Html page. 

你可能感兴趣的:(Java,Web)