创建空工程,在工程中创建javaEE模块
配置中设置tomcat的部署
编写register界面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>重定向测试</title>
</head>
<body>
<form action="redirectServlet" method="post">
<input type="submit" value="重定向">
</form>
</body>
</html>
编写servlet
RedirectServlet
package com.example.sendredirect_demo02;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("接收到重定向请求~");
//重定向,给浏览器发送一个新的位置
response.sendRedirect("target.html");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>RedirectServlet</servlet-name>
<servlet-class>com.example.sendredirect_demo02.RedirectServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RedirectServlet</servlet-name>
<url-pattern>/redirectServlet</url-pattern>
</servlet-mapping>
</web-app>
部署测试:
运行tomcat
访问重定向界面,发送重定向请求
跳转到目标页面
F12查看调试信息
可以看出响应了一个302代码,页面会自动发送请求,跳转到Location指定的目标界面