若客户端未禁用cookie,sessionId会自动的写入Cookie中,不需要编程,web容器自动完成
1 当客户端禁用cookie时,通过URL重写来实现会话跟踪
-
servlet
HttpSession session = req.getSession(); String url = resp.encodeRedirectURL("index.jsp"); resp.sendRedirect(url);
-
浏览器地址栏中的地址
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)
-
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); } }
-
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>
-
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>
-
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>