实现重定向
一个web资源受到客户端请求后他会通知客户端去访问另一个web资源,这个过程叫做重定向
常见场景:
* 用户登录
测试
public class RedirectServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { resp.sendRedirect("/r/image"); /*resp.setStatus(302); resp.setHeader("Location","/r/image"); */ }
进行数据保存
<form action="${pageContext.request.contextPath}/zf" method="get"> 用户名:<input type="text" name="username"> <br> 密码:<input type="text" name="password"> <br> <input type="submit"> </form>
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //处理请求 String username = req.getParameter("username"); String password = req.getParameter("password"); System.out.println(username+":"+password); //重定向时候一定要注意,路径问题,否则404 resp.sendRedirect("/r/success.jsp"); }