一、重定向的概念
- 客户浏览器发送http请求,当web服务器接受后发送302状态码响应及对应新的location给客 户浏览器
- 客户浏览器发现是302响应,则自动再发送一个新的http请求,请求url是新的location地址,服务器根据此请求寻找资源并发送给客户。
二、代码演示
1、编写界面
-
创建空工程,在工程中创建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>
2、编写Servlet 重定向
-
编写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指定的目标界面
-