重定向与错误发送
重定向状态码
301、302
重定向demo
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.test; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/first") public class First extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // response.sendRedirect("https://www.baidu.com"); response.sendRedirect("sencond"); // 重定向可以指定相对url,也可以指定绝对url } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.test; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/sencond") public class Sencond extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendRedirect("https://www.sina.com.cn"); } }
发送错误
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
package com.test; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; @WebServlet("/first") public class First extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //response.sendError(HttpServletResponse.SC_NOT_FOUND); response.sendError(HttpServletResponse.SC_NOT_FOUND, "笔记文件"); } }
response.sendError(HttpServletResponse.SC_NOT_FOUND)响应内容如下:
response.sendError(HttpServletResponse.SC_NOT_FOUND, "笔记文件")响应内容如下: