URL重写

 encodeURL(java.lang.String URL): encodes the specified URL by includeing the session ID in it, or, if encoding is not needed, return the URL unchanged.

encodeRedirectURL(java.lang.String url):encodes the specified URL for use in the sendRedirect method or,  if encoding is not needed, return the URL unchanged.

 

一般情况选择encodeURL,重定向的时候用第二个。
  两个方法区别在于,如果参数为空字符串,返回结果不同。

public class URLSessionServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        this.doPost(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        //获得session
        HttpSession session = request.getSession();
        System.out.println("urlsession " + session.getId());
        
        String url = "/urlSessionServlet2";
        
        /* 当前页面:http://localhost:8080/day07/urlSessionServlet
         * 目标页面:http://localhost:8080/day07/urlSessionServlet2
         */
        //URL重写
        url = response.encodeURL(url);   //处理:如果需要sessionId,则在URL中追加
        
        this.getServletContext().getRealPath(""); //获得真实的路径  web项目 / WebRoot
        //浏览器  / web站点 webapps 
        
        System.out.println(url);
        String path = request.getContextPath();
        System.out.println(path);
        System.out.println(response.encodeURL("/day07/urlSessionServlet2"));
        System.out.println(response.encodeURL(""));
        
        
        //将此链接,以a标签的输出
        PrintWriter out = response.getWriter();
        out.print("<a href='"+url+"'>demosession</a>");

    }

}

 

 

 public String encodeURL(String url) {


String absolute = toAbsolute(url);
if (isEncodeable(absolute)) {
// W3c spec clearly said
if (url.equalsIgnoreCase("")){ //
url = absolute;
}
return (toEncoded(url, request.getSessionInternal().getIdInternal()));
} else {
return (url);
}

}

public String encodeRedirectURL(String url) {

if (isEncodeable(toAbsolute(url))) {
return (toEncoded(url, request.getSessionInternal().getIdInternal()));
} else {
return (url);
}

}
注意:参数url必须有效,否则返回没有改变的URL
当使用"/"开头,相对于web站点
    写的方法:response.encodeURL("/day07/urlSessionServlet2")
    返回的是:/day07/urlSessionServlet2;jsessionid=F85DB5EFDDB9A6B170AF2B4959EFC4FC
获得Web的绝对路径
    String absolute = toAbsolute(url);
    http://localhost:8080/day07/
总结:
需要考虑用户的Cookie是否禁用了
将所有的链接全部进行URL重写(过滤器)

posted @ 2017-03-31 17:25  xuyatao  阅读(431)  评论(0编辑  收藏  举报