欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Session会话跟踪的三种方式

程序员文章站 2024-03-20 10:54:04
...

若客户端未禁用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文件

      <servlet>
      	<servlet-name>SessionIdTest</servlet-name>
      	<servlet-class>com.xiaoming.SessionIdTest</servlet-class>
      </servlet>
      <servlet-mapping>
      	<servlet-name>SessionIdTest</servlet-name>
      	<url-pattern>/s</url-pattern>
      </servlet-mapping>
    
  3. index.jsp文件

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <!DOCTYPE>
    <html>
      <head>   
        <title>index.jsp</title>
      </head> 
      <body>
        This is my JSP page. <br>
    
       <a href="<%=request.getSession().getAttribute("url")%>" >去往main.html</a>
    
      </body>
    </html>
    
  4. main.html文件

    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <!DOCTYPE>
    <html>
      <head>  
        <title>main.jsp</title>
      </head>
      <body>
        This is my Html page. <br>
      </body>
    </html>
    
相关标签: 会话跟踪