url 重写实现会话概述
URL重写是对GET请求参数的应用,当服务器响应浏览器上一次请求时,将某些相关信息以超链接方式响应给浏览器,超链接中包括请求参数信息。
特点:URL必须以GET方式发送请求。
缺点:URL在某些浏览器上最大长度为2000字符;不适用敏感数据的传递。
应用:最典型应用是分页、辅助Session会话管理。
example
package com.test; 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; import java.io.PrintWriter; @WebServlet("/search") public class Search extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); PrintWriter out = response.getWriter(); out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<meta charset='UTF-8'>"); out.println("<title>搜索结果</title>"); out.println("</head>"); out.println("<body>"); String start = request.getParameter("start"); if (start == null) { start = "1"; } int count = Integer.parseInt(start); int begin = 10 * count - 9; int end = 10 * count; out.println("第" + begin + "到" + end + "搜索结果:<br>"); for (int i=1; i<10; i++) { if (i == count) { out.println(i); continue; } out.println("<a href='search?start=" + i + "'>" + i +"</a>"); } out.println("</body>"); out.println("</html>"); out.close(); } }
响应结果: