SpringBoot重定向的几种方式

7,923 阅读1分钟

重定向的几种方式:

  • 方式一:使用RedirectView,支持内部接口、外部URL
  • 方式二:使用HttpServletResponse#sendRedirect(),支持内部接口、外部URL
  • 方式三:使用redirect:,支持内部接口、外部URL
  • 方式四:使用ModelAndView,支持内部接口

示例:

/**
 * SpringBoot重定向的几种方式
 * @author fay
 * @date 2022-07-13
 */
@Controller
public class RedirectController {

    /**
     * 方式一:使用RedirectView,支持内部接口、外部URL
     */
    @GetMapping("/test")
    public RedirectView test() {
        // String testUrl = "hello";
        String testUrl = "https://www.baidu.com";
        return new RedirectView(testUrl);
    }
    
    /**
     * 方式二:使用HttpServletResponse#sendRedirect(),支持内部接口、外部URL
     */
    @GetMapping("/test1")
    public void test1(HttpServletResponse response) throws IOException {
        // String testUrl = "hello";
        String testUrl = "https://www.baidu.com";
        response.sendRedirect(testUrl);
    }

    /**
     * 方式三:使用redirect:,支持内部接口、外部URL
     */
    @GetMapping("/test2")
    public String test2() {
        // return "redirect:hello";
        return "redirect:https://www.baidu.com";
    }

    /**
     * 方式四:使用ModelAndView,支持内部接口
     */
    @GetMapping("/test3")
    public ModelAndView test3() {
        String testUrl = "hello";
        return new ModelAndView(testUrl);
    }

    @ResponseBody
    @GetMapping("/hello")
    public String hello() {
        return "Hello World!";
    }

}