Java-Response实现重定向

白衣少年
2022-11-07 / 0 评论 / 54 阅读 / 正在检测是否收录...
温馨提示:
本文最后更新于2022年11月07日,已超过536天没有更新,若内容或图片失效,请留言反馈。

什么是重定向

重定向(Redirect)就是通过各种方法将各种网络请求重新定个方向转到其它位置(如:网页重定向、域名的重定向、路由选择的变化也是对数据报文经由路径的一种重定向)。
重定向作用在客户端,客户端将请求发送给服务器后,服务器响应给客户端一个新的请求地址,客户端重新发送新请求。
重定向.png

转发与重定向的区别

相同点 :页面都会跳转
不同点

  • 请求转发时,url不会发生变化
  • 重定向时,浏览器地址栏的url会发生变化。
public class Servlet4 extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        重定向的时候,一定要注意路径问题,否则就会出现404
        resp.sendRedirect("/s1/index.jsp");
    }
}

重定向

web资源B收到A的请求后,B会通知A客户端去反问另一个web资源C,这个过程叫重定向

void sendRedirect(String var1) throws IOException;

重定向.png

Status Code:302 重定向
Location:/r/img

代码

public class RedirectServlet extends HttpServlet {
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    resp.sendRedirect("/r/img");//重定向
//拆分
/*
resp.setHeader("Location","/r/img");
resp.setStatus(302);
*/
  }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
  }
}

常见场景:用户登录

场景代码

  • jsp文件
  <!-- index文件 -->
  <html>
    <body>
      <h2>Hello World!</h2>
      <%--这里提交的路径需要寻找到项目的路径--%>
      <%--
        pageContext.request.contextPath() 这段代码表示的是当前项目
      --%>
      <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>
  <!-- success文件 -->
  <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  <html>
  <head>
    <title>Title</title>
  </head>
    <body>
      <h1>Success</h1>
    </body>
  </html>
public class RequestTest extends HttpServlet {
  @Override
  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);
      //重定向一定要注意路径问题
      resp.sendRedirect("/r/success.jsp");
    }
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    doGet(req, resp);
  }
}

错误总结:

1.配置maven的时候没有导入jsp的文件包,需要导入该包,导入代码如下

  <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
  <groupId>javax.servlet.jsp</groupId>
  <artifactId>javax.servlet.jsp-api</artifactId>
  <version>2.3.3</version>
  <scope>provided</scope>
</dependency>

2.检查index.jsp form表单的拼写
3.检查web.xml文件的配置

面试题:重定向与转发的区别

转发与重定向的区别.png

  • 相同点
    页面都会跳转
  • 不同点
    请求转发的时候,url不会产生变化
    重定向的时候,url地址栏会发生变化
3

打赏

评论 (0)

OwO
取消