请求转发与重定向

221 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路

启动服务器加载SpringMVC

图片1.png

index.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>index</title>
  </head>
  <body>
      <a href="${pageContext.request.contextPath}/first.action">转发方式跳转到first.jsp</a>
      <br>
      <a href="${pageContext.request.contextPath}/second.action">重定向方式跳转到second.jsp</a>
  </body>
</html>

first.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>First.jsp</title>
</head>
<body>
  我是转发方式跳转过来的页面
</body>
</html>

Second.jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Second.jsp</title>
</head>
<body>
  我是重定向过来的页面
</body>
</html>

请求转发

@RequestMapping("/first.action")
public ModelAndView show(){
    //创建ModelAndView用来存放数据和视图
    ModelAndView modelAndView = new ModelAndView();
    //设置数据到视图中
    modelAndView.addObject("name","转发");
    //设置视图
    modelAndView.setViewName("first");//会根据springMVC.xml中的配置自动拼接成/first.jsp
    //将modelAndView返回
    return modelAndView;
}

重定向

@RequestMapping("/second.action")
public String secondshow(){
    return "redirect:/second.jsp";
}

运行结果

图片2.png

图片3.png

图片4.png