Response实现重定向
当一个web资源(B)收到客户端A请求后,B 会通知A客户端去访问另外一个web资源C,这个过程叫做重定向
常见场景:
用户登录:
void sendRedirect(String var1) throws IOException;
测试:
@WebServlet("/red")
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.sendRedirect("/response/img");
//上面这行等价于下面两行
/*
resp.setHeader("Location","/response/img");
resp.setStatus(302);*/
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
注意事项:
重定向一定要注意路径问题,例如resp.sendRedirect("/response/img");其中要加入本项目的根路径/response,否则找不到img资源
案例:重定向登录成功
<html>
<body>
<h2>Hello World!</h2>
<%--这里提交的路径,需要寻找到项目的路径--%>
<%--${pageContext.request.contextPath}代表当前的项目--%>
<form action="${pageContext.request.contextPath}/login" method="get">
账号:<input type="text" name = "username"><br>
密码:<input type="password" name = "password"><br>
<input type="submit">
</form>
</body>
</html>
@WebServlet("/login")
public class RequestTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("请求成功");
String username = req.getParameter("username");
String pwd = req.getParameter("password");
System.out.println(username+":"+ pwd);
//重定向一定要注意路径问题,否则404,路径中要加上本项目的根路径/response
resp.sendRedirect("/response/success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}