在SpringBoot中如何使用重定向和请求转发呢??这里大致总结了几种常见的方式。
1 跳转页面
首先,页面必须在templates下面,不经过配置,无法直接跳转到public,static,等目录下的页面。
@ControllerpublicclassTestController{@RequestMapping("/redirect")publicStringtest(String userName,Model model){
model.addAttribute("name",userName);//跳转到index页面return"index";}}
2 重定向:
方式1:使用 "redirect"关键字
@GetMapping("/test01")publicStringtest01(){return"redirect:/path/hello.html";}
注意:
- 控制器类的注解不能使用**@RestController**,要用**@Controller**。因为@RestController内含@ResponseBody,解析返回的是json串,就不再是跳转页面了
方式2:使用servlet 提供的API
@GetMapping("/test02")publicvoidtest02(HttpServletResponse response){
response.sendRedirect("/path/hello.html");}
注意:
- 此时控制器类注解可以使用@RestController,也可以使用@Controller
3 请求转发:
方式1:使用 “forward” 关键字
@GetMapping("/test03")publicStringtest03(){return"forward:/path/hello.html";}
注意:
- 类的注解不能使用@RestController,要用@Controller
方式2:使用servlet 提供的API
@GetMapping("/test04")publicvoidtest04(HttpServletRequest request,HttpServletResponse response){
request.getRequestDispatcher("/feng/hello.html").forward(request,response);}
注意:
- 类的注解可以使用@RestController,也可以使用@Controller