@controller注解
时间: 2023-07-03 19:07:40 浏览: 46
`@Controller`是Spring框架中的注解之一,用于标识一个类为控制器(Controller)。在Spring MVC中,控制器负责接受用户请求,并根据请求的内容调用相应的业务逻辑处理方法,并返回对应的响应结果。
`@Controller`注解通常与`@RequestMapping`注解结合使用,`@RequestMapping`用于指定请求的URL路径和请求方式,从而将请求映射到对应的控制器方法上。
示例代码:
```
@Controller
@RequestMapping("/user")
public class UserController {
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public ModelAndView getUser(@PathVariable("id") Long id) {
// 根据用户ID查询用户信息
User user = userService.getUserById(id);
// 构建响应视图和数据模型
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("user");
modelAndView.addObject("user", user);
return modelAndView;
}
}
```
在上面的示例中,`@Controller`注解标识了`UserController`类为控制器,`@RequestMapping`注解指定了请求的URL路径为`/user/{id}`,请求方式为`GET`。`getUser`方法接受一个`id`参数,并根据该参数查询用户信息,并将查询结果放入响应数据模型中,最后返回响应视图和数据模型。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)