您的位置:首页 > 其它

URL重写实现会话跟踪

2013-06-22 14:20 465 查看
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包含会话ID;encodeRedirectURL被用来重定向页面

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: