JSP 页面重定向

sendRedirect 与 jsp:forward 的差别、选择依据、常见错误。

Beginner
Key Points重定向让浏览器再发一次请求,地址栏会变;forward 在服务端转交,地址栏不变且 request 域保留。

两种跳转

JSP
<%-- 重定向:浏览器地址栏变成 /home.jsp --%>
<% response.sendRedirect(request.getContextPath() + "/home.jsp"); return; %>

<%-- 转发:地址栏仍是当前页,request 属性可带过去 --%>
<jsp:forward page="/WEB-INF/views/home.jsp"/>
jsp:forward
Requests21
URL改变不变
Request scope丢失保留
Target可跨应用、可外站仅本应用
Use for登录后跳转、PRGController 交给 View

登录校验里的重定向

JSP
<%
    if (session.getAttribute("uid") == null) {
        String from = request.getRequestURI();
        response.sendRedirect(request.getContextPath()
                + "/login.jsp?from=" + java.net.URLEncoder.encode(from, "UTF-8"));
        return;
    }
%>

Carry the original address in from so login returns the user where they were instead of dumping them on the home page. Encode it with URLEncoder or Chinese paths break.

PRG 模式

JSP
<%-- save.jsp:处理完重定向,避免刷新重复提交 --%>
<%
    orderService.create(order);
    response.sendRedirect("orderList.jsp?msg=created");
    return;
%>

Forwarding to a result page after a POST means F5 submits again — and the order is placed twice. Always redirect after POST (Post/Redirect/Get) so a refresh is a harmless GET.

三个常见错误

  • 忘了 return —— 后面的 HTML 照样输出,容器抛 IllegalStateException
  • 在输出之后重定向 —— 响应已提交,sendRedirect 静默失败
  • URL 少了 contextPath —— 部署在 /myapp 下会跳到服务器根
A BOM or blank line before <%@ page %> gets written as response body, after which sendRedirect silently fails. A JSP must start at line one with no leading whitespace.

Friends & Partners