springboot实现转发和重定向
时间: 2023-06-29 15:03:26 浏览: 201
在Spring Boot中,可以使用`@Controller`注解来标记控制器类,使用`@RequestMapping`注解来进行请求映射。在控制器方法中,可以使用`ModelAndView`对象进行页面转发和重定向。
1. 页面转发:
```java
@Controller
public class MyController {
@RequestMapping("/forward")
public ModelAndView forward() {
ModelAndView mav = new ModelAndView();
mav.setViewName("forward:/index.html");
return mav;
}
}
```
在上述代码中,`@RequestMapping`注解表示映射到`/forward`路径的请求。在`forward()`方法中,创建一个`ModelAndView`对象,并设置视图名称为`forward:/index.html`,表示将请求转发到`index.html`页面。
2. 页面重定向:
```java
@Controller
public class MyController {
@RequestMapping("/redirect")
public ModelAndView redirect() {
ModelAndView mav = new ModelAndView();
mav.setViewName("redirect:/index.html");
return mav;
}
}
```
在上述代码中,`@RequestMapping`注解表示映射到`/redirect`路径的请求。在`redirect()`方法中,创建一个`ModelAndView`对象,并设置视图名称为`redirect:/index.html`,表示将请求重定向到`index.html`页面。
需要注意的是,重定向时需要使用完整的URL路径或者相对路径,而不是仅仅一个视图名称。