Servlet实现重定向的两种方式
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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); } }
以上是关于Servlet实现重定向的两种方式的主要内容,如果未能解决你的问题,请参考以下文章
Springboot以Tomcat为容器实现http重定向到https的两种方式
nginx实现内容重定向的两种方式:rewrite和反向代理