servlet实操之重定向
一个web资源收到客户端请求,收到后通知客户端去访问另外一个web资源
常见场景
用户登录
servlet实现:
void sendRedirect(String location) throws IOException
// resp.setHeader("Location","/Response_war/yanimage");
// resp.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
resp.sendRedirect("/Response_war/yanimage");
重定向和转发的区别:
不同点:
转发请求转发的时候url不会产生变化
重定向请求转发的时候url会产生变化
相同点:
都可以实现跳转
简单练习
项目首页jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<%--<提交的路径需要寻找到项目的路径>--%>
<%--<代表当前的项目pageContext.request.ContextPath>--%>
<form action="${pageContext.request.contextPath}/login" method="get">
用户名: <input type="text" name="username">
密码: <input type="password" name="password">
<input type="submit">
</form>
</body>
</html>
后端接受请求:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入请求");
//处理请求
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username + ":" + password);
//重定向一定要注意路径问题,否则就会404
resp.sendRedirect("/Response_war/success.jsp");
}