URL重写实现会话跟踪

来源:互联网 发布:淘宝充流量如何退款 编辑:程序博客网 时间:2024/05/16 17:33
         servlet创建的所有链接的重定向都必须将会话ID编码为URL的一部分。在服务器指定的URL编码的方法中,最可能的一种是给URL加入一些参数或者附加的路径信息。

     为了说明URL Rewriting技术,我们编写sevlet实现访问记数。下面代码显示了CounterRewriteServlet的源程序,它使用URL Rewriting技术来在HTTP请求之间维护会话信息。

package sample;
import javax.servlet.*;
import javax.servlet.http.*;
public class CounterRewrite extends HttpServlet
    {
    static final String COUNTER_KEY = "CounterRewrite.count";
public void doGet(HttpServletRequest req,
    HttpServletResponse resp)
    throws ServletException, java.io.IOException
    {
     resp.setContentType("text/html");
     java.io.PrintWriter out = resp.getWriter();
HttpSession session = req.getSession(true);
     int count = 1;
     Integer i = (Integer) session.getValue(COUNTER_KEY);
if (i != null) {
     count = i.intValue() + 1;
     }
    session.putValue(COUNTER_KEY, new Integer(count));
    out.println("<html>");
    out.println("<head>");
    out.println("<title>Session Counter " +"with URL rewriting</title>");
    out.println("</head>");
    out.println("<body>");
    out.println("Your session ID is <b>" +session.getId());
    out.println("</b> and you have hit this page <b>" +count +
"</b> time(s) during this browser session");
    String url = req.getRequestURI()+ ";" + SESSION_KEY +session.getId();
    out.println("<form method=POST action=\"" +resp.encodeUrl(url) + "\">");
    out.println("<input type=submit " +"value=\"Hit page again\">");
    out.println("</form>");
    out.println("</body>");
    out.println("</html>");
    out.flush();
    }
    public void doPost(HttpServletRequest req, HttpServletResponse resp)
    throws ServletException, java.io.IOException
   {
    doGet(req, resp);
    }
  }


请注意,encodeURL方法被用来修改URL,使URL包含会话IDencodeRedirectURL被用来重定向页面

原创粉丝点击