文章目录
前言
前面介绍了视图解析器的使用,但是对我们原有转发和重定向有影响,接下来我们通过案例,来使用学习转发和重定向的用法。
一、准备
我们以params下的params.jsp和根目录下的index.jsp为例
二、转发
1. 视图解析器(推荐)
根据视图解析器配置的前缀和后缀,我们仅需完成中间部分的拼接即可。
http://localhost:8080/forward01
package org.example.springmvc.params.controller;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.IOException;
/**
* Create by zjg on 2024/5/1
*/
@Controller
public class ForwardController {
@RequestMapping("forward01")
public String forward01(){
return "params/params";
}
}
2. 关键字(forward)
http://localhost:8080/forward02
@RequestMapping("forward02")
public String forward02(){
return "forward:/WEB-INF/views/params/params.jsp";
}
3. request
http://localhost:8080/forward03
@RequestMapping("forward03")
public void forward03(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/views/params/params.jsp").forward(request,response);
}
三、重定向
1.关键字(redirect)
http://localhost:8080/redirect01
package org.example.springmvc.params.controller;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.io.IOException;
/**
* Create by zjg on 2024/5/1
*/
@Controller
public class RedirectController {
@RequestMapping("redirect01")
public String redirect01(){
return "redirect:index.jsp";
}
}
2. HttpServletResponse
http://localhost:8080/redirect02
@RequestMapping("redirect02")
public void redirect02(HttpServletResponse response) throws IOException {
response.sendRedirect("index.jsp");
}
四、区别
特性 | 转发(Forward) | 重定向(Redirect) |
---|---|---|
请求次数 | 一次请求 | 至少两次请求 |
地址栏变化 | 地址栏不会发生变化 | 地址栏会发生变化 |
数据共享 | 共享数据(在request级别) | 不共享数据 |
跳转限制 | 只能跳转本站点资源 | 可以跳转到任意URL |
发生行为 | 服务器端行为 | 客户端行为 |
示例描述 | 张三向你借钱,你去找李四借到钱之后借给张三。张三并不知道钱是从李四那里借的。 | 浏览器首先请求A页面,服务器响应并告诉浏览器去B页面。浏览器根据这个指令重新发起请求到B页面。 |
重定向无法直接访问/WEB-INF下内容,可以使用之前【第8章】spring-mvc视图解析器、控制器来进行访问