Response
重定向
一个web资源收到客户端的请求后,他会通知客户端去访问另外一个web资源,这个过程叫做重定向。
常见场景
- 用户登录:
void sendRedirect(String var1) throws IOException;
2.路径重定向:
注意:路径要写完全路径
package com.xin.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//resp.setHeader("Location","/r/image");
// resp.setStatus(302);
resp.sendRedirect("/r/image");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
面试:重定向和转发的区别
相同:
- 页面都会跳转
不同: - 请求转发的时候url不会变化,重定向的时候url会发生变化
编写登录页面
<html>
<body>
<h2>Hello World!</h2>
<%@page contentType="text/html; charset=utf-8" %>
<%--提交的路径需要寻找到项目的路径--%>
<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>
package com.xin.servlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RequestTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// resp.setContentType("text/html;charset=utf-8");
System.out.println("进入这个请求");
//处理请求
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username+":"+password);
resp.sendRedirect("/r/success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}
重定向
新建一个网页,使我们提交成功之后跳转
注意新建的jsp在webapp目录下
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>XIXI</title>
</head>
<body>
<h1>SUCCESS</h1>
</body>
</html>

浙公网安备 33010602011771号