转发参数不会自动包含在新的请求中。若要将参数传递给重定向地址,可以在服务器端显式地添加参数到重定向URL中。
在重定向URL中包含参数
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/initialRequest")
public class InitialRequestServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取原始请求参数
String param = request.getParameter("param");
// 重定向到新的URL,并在重定向URL中包含原始参数
response.sendRedirect("redirectedRequest?param=" + param);
}
}
处理重定向后的请求
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/redirectedRequest")
public class RedirectedRequestServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取重定向后请求中的参数
String param = request.getParameter("param");
response.setContentType("text/html");
response.getWriter().println("<h1>Redirected Request</h1>");
response.getWriter().println("<p>Param: " + param + "</p>");
}
}
转发会携带初始请求的参数
转发
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/initialRequest")
public class InitialRequestServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取原始请求参数
String param = request.getParameter("param");
// 在请求属性中保存参数
request.setAttribute("param", param);
// 转发请求到新的Servlet
request.getRequestDispatcher("/forwardedRequest").forward(request, response);
}
}
转发之后
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet("/forwardedRequest")
public class ForwardedRequestServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 获取转发请求中的参数
String param = (String) request.getAttribute("param");
response.setContentType("text/html");
response.getWriter().println("<h1>Forwarded Request</h1>");
response.getWriter().println("<p>Param: " + param + "</p>");
}
}
区别补充: 重定向不会自动携带初始请求参数,如需要需手动在代码里补全对应的参数;转发会自动携带初始请求的参数。