Servlet实现重定向的两种方式
使用Servlet实现请求重定向:两种方式
1.
response.setStatus(302);
response.setHeader("location", "/ResponseDemo/ResponseDemo13");
2.
response.sendRedirect("/ResponseDemo/ResponseDemo13");
被访问的代码:
package chensi.com; 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; /** * Servlet 使用response实现重定向 */ @WebServlet("/ResponseDemo12") public class ResponseDemo12 extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("这个是最开始访问的页面"); /*response.setStatus(302); response.setHeader("location", "/ResponseDemo/ResponseDemo13");*/ response.sendRedirect("/ResponseDemo/ResponseDemo13"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
被重定向的Servlet的代码:
package chensi.com; 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; /** * Servlet 使用response实现重定向 */ @WebServlet("/ResponseDemo12") public class ResponseDemo12 extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); response.getWriter().write("这个是最开始访问的页面"); /*response.setStatus(302); response.setHeader("location", "/ResponseDemo/ResponseDemo13");*/ response.sendRedirect("/ResponseDemo/ResponseDemo13"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }