Spring MVC怎么样设定重定向和转发的
时间: 2023-08-23 14:02:35 浏览: 63
在 Spring MVC 中,可以使用重定向和转发来进行请求的跳转。下面是设定重定向和转发的几种方式:
1. 重定向:
- 使用 `RedirectView` 类:可以在控制器方法中返回一个 `RedirectView` 对象,设置重定向的目标 URL。
- 使用 `RedirectAttributes` 类:可以在控制器方法中将重定向的目标 URL 添加到 `RedirectAttributes` 对象中,并使用 `redirect:` 前缀来指示重定向。
2. 转发:
- 使用 `ModelAndView` 类:可以在控制器方法中返回一个 `ModelAndView` 对象,设置转发的视图名称。
- 使用 `forward:` 前缀:可以在控制器方法中使用 `return "forward:/path"` 的方式来指示转发到指定的路径。
下面是一个示例,展示如何在控制器方法中设定重定向和转发:
```java
@Controller
public class MyController {
@GetMapping("/redirect")
public RedirectView redirectToUrl() {
RedirectView redirectView = new RedirectView();
redirectView.setUrl("https://www.example.com");
return redirectView;
}
@GetMapping("/redirectWithAttributes")
public String redirectWithAttributes(RedirectAttributes attributes) {
attributes.addAttribute("param", "value");
return "redirect:/targetUrl";
}
@GetMapping("/forward")
public ModelAndView forwardToView() {
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("forward:/targetView");
return modelAndView;
}
}
```
上述代码中,`/redirect` 路径的请求会被重定向到 `https://www.example.com`,`/redirectWithAttributes` 路径的请求会带着参数重定向到 `/targetUrl`,`/forward` 路径的请求会被转发到 `targetView` 视图。
需要注意的是,在设定重定向和转发时,可以使用绝对路径或相对路径,具体根据需求来确定。同时,还可以在路径中使用占位符和路径参数来实现动态的跳转。