RequestURI、ServletPath、ContextPath和转发重定向的参数

一、requestURI、servletPath、contextPath

假设:

  • 当前的项目根目录为:/demo,即访问首页的路径为http://localhost:8080/demo/index.jsp
  • 页面全部位于 web 根目录下。

假设有一个 Servlet:

public class TestServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        super.service(request, response);
        System.out.println("context-path=" + request.getContextPath());
        System.out.println("servlet-path=" + request.getServletPath());
        System.out.println("request-uri=" + request.getRequestURI());
    }
}

那么访问首页 http://localhost:8080/demo/index.jsp则会输出:

context-path=/demo
servlet-path=/index.jsp
request-uri=/demo/index.jsp

二、转发、重定向的参数

假设当前 Servlet 正在处理的请求的请求路径为/demo/control/login

/转发

假设转发的方式为:

request.getRequestDispatcher("/home.jsp").forward(request, response);

那么转发到的路径为:

  • http://localhost:8080/demo/home.jsp
  • 相对 web 根目录转发。符合期望。

不带/转发

假设转发的方式为:

request.getRequestDispatcher("home.jsp").forward(request, response);

那么转发到的路径为:

  • http://localhost:8080/demo/control/home.jsp

  • 相对当前请求路径转发。不符合期望。

/重定向

假设重定向的方式为:

response.sendRedirect("/login.jsp");

那么重定向的路径为:

  • http://localhost:8080/login.jsp
  • 相对项目路径(或 context-path)重定向。不符合期望。

不带/重定向

假设重定向的方式为:

response.sendRedirect("login.jsp");

那么重定向的路径为:

  • http://localhost:8080/demo/control/login.jsp
  • 相对当前请求路径转发。不符合期望。

URL地址重定向

假设重定向的方式为:

response.sendRedirect("https://www.google.com/");

那么重定向的地址为:

  • https://www.google.com/
  • 符合期望

统一格式化

可以定义一个方法来统一处理:

    public static void formatResponse(HttpServletRequest request,
                                      HttpServletResponse response, 
                                      String target,
                                      String responseMethod) throws ServletException, IOException {
        switch (responseMethod) {
            case "FORWARD": {
                String url = ("/" + target).replaceAll("/+", "/");
                request.getRequestDispatcher(url).forward(request, response);
            }
            case "REDIRECT": {
                String url;
                if (target.startsWith("http") || target.startsWith("www.")) {
                    url = target;
                } else {
                    url = ("/" + request.getContextPath() + "/" + target).replaceAll("/+", "/");
                }
                response.sendRedirect(url);
                break;
            }
            default: {

            }
        }
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值