重定向的几种方式:
- 方式一:使用
RedirectView,支持内部接口、外部URL
- 方式二:使用
HttpServletResponse#sendRedirect(),支持内部接口、外部URL
- 方式三:使用
redirect:,支持内部接口、外部URL
- 方式四:使用
ModelAndView,支持内部接口
示例:
@Controller
public class RedirectController {
@GetMapping("/test")
public RedirectView test() {
String testUrl = "https://www.baidu.com";
return new RedirectView(testUrl);
}
@GetMapping("/test1")
public void test1(HttpServletResponse response) throws IOException {
String testUrl = "https://www.baidu.com";
response.sendRedirect(testUrl);
}
@GetMapping("/test2")
public String test2() {
return "redirect:https://www.baidu.com";
}
@GetMapping("/test3")
public ModelAndView test3() {
String testUrl = "hello";
return new ModelAndView(testUrl);
}
@ResponseBody
@GetMapping("/hello")
public String hello() {
return "Hello World!";
}
}