实现重定向
一个web资源(B)收到客户端请求后,他会通知客户端(A)去访问另一个web资源(C),这个过程叫重定向
常见场景
- 用户登录
面试题:请你聊聊重定向和转发的区别?
相同点:
- 页面都会实现跳转
不同点: - 请求转发的时候,url不会发生变化
- 重定向时,url地址栏会发生变化
重定向代码
- index.jsp
<html>
<body>
<h2>Hello World!</h2>
<%--这里提交的路径,需要寻找到项目的路径--%>
<%--${pageContext.request.contextPath}代表当前项目路径--%>
<form action="${pageContext.request.contextPath}/login" method="get">
username:<input type="text" name="username"><br>
password:<input type="password" name="password"><br>
<input type="submit">
</form>
</body>
</html>
- RequestTest 类
package com.kuang.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 {
System.out.println("进入这个请求了");
//处理请求
String username = req.getParameter("username");
final String password = req.getParameter("password");
System.out.println(username+":"+password);
//重定向一定要注意路径问题,否则就会404.一定要加项目名,比如本项目的/re
resp.sendRedirect("/re/success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
- success.jsp
<%--
Created by IntelliJ IDEA.
User: levon
Date: 2022/7/12
Time: 17:09
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Success</h1>
</body>
</html>
- web.xml
<servlet>
<servlet-name>request</servlet-name>
<servlet-class>com.kuang.servlet.RequestTest</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>request</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
首先在index.jsp页面输入用户名和密码,然后RequestTest 类处理请求,并重定向到success.jsp.