在SpringBoot中如何使用重定向和请求转发呢??这里大致总结了几种常见的方式。

1 跳转页面

首先,页面必须在templates下面,不经过配置,无法直接跳转到public,static,等目录下的页面。

@Controller
public class TestController {
    @RequestMapping("/redirect")
    public String test(String userName,Model model){
        model.addAttribute("name",userName);
        //跳转到index页面
        return "index";
    }
}

2 重定向:

方式1:使用 "redirect"关键字
@GetMapping("/test01")
public String test01() {
  return "redirect:/path/hello.html";
}

注意:

  • 控制器类的注解不能使用**@RestController**,要用**@Controller**。因为@RestController内含@ResponseBody,解析返回的是json串,就不再是跳转页面了
方式2:使用servlet 提供的API
@GetMapping("/test02")
public void test02(HttpServletResponse response) {
  response.sendRedirect("/path/hello.html");
}

注意:

  • 此时控制器类注解可以使用@RestController,也可以使用@Controller

3 请求转发:

方式1:使用 “forward” 关键字
@GetMapping("/test03")
public String test03() {
  return "forward:/path/hello.html";
}

注意:

  • 类的注解不能使用@RestController,要用@Controller
方式2:使用servlet 提供的API
@GetMapping("/test04")
public void test04(HttpServletRequest request, HttpServletResponse response) {
  request.getRequestDispatcher("/feng/hello.html").forward(request,response);
}

注意:

  • 类的注解可以使用@RestController,也可以使用@Controller
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐