Controller层参数注解
发布日期:2021-05-17 08:12:25 浏览次数:19 分类:精选文章

本文共 1740 字,大约阅读时间需要 5 分钟。

controller层常用的注解

controller层是springmvc的核心,常用的注解包括@controller、@restcontroller、@modelattribute、@requestmapping、@getmapping、@postmapping、@putmapping、@deletemapping、@patchmapping,以下是这些注解的作用及其示例代码:

@controller默认注解,用于处理http请求

@restcontroller配合@responsebody使用,可与控制器一样处理json返回,但要单独声明返回类型

@modelattribute用于将parameters转换为domain对象,可用于模型绑定

@requestmapping用于配置uri的值,可使用多个模板匹配如/{id}、/{category}等

@getmapping组合注解,等同于requestmapping配合method.get

@postmapping同理,等同于requestmapping配合method.post

@putmapping等同于requestmapping配合method.put

@deletemapping等同于requestmapping配合method.delete

@patchmapping等同于requestmapping配合method.patch

@PathVariable用于获取uri中的动态参数例如:@RequestMapping("/user/{id}")public user getuser(@PathVariable String id) {//代码}

@RequestParam用于获取请求参数的值,可以指定名称和可选性可用同时指定多个参数例如:@RequestMapping("/updateuser")public string updateuser(@RequestParam(required=false, defaultValue="3333") long id,@RequestParam(hasValue=true) String username,@RequestBody user user) {//代码}

@RequestBody用于将http请求体参数转换为对象,可传递json数据例如:@PostMapping("/adduser")public void adduser(@RequestBody user user) {//代码}

@ModelAttribute可用于将参数自动转换为model属性,可以结合PathVariable和RequestParam使用例如:@RequestMapping("/userinfo")public object getuser(@ModelAttribute("extras") Map<String, Object> extras) {//代码}

uri模板与可选参数可在@RequestMapping的value属性中定义uri模板,支持可选参数例如:@RequestMapping({"getcategorized/{categori}/{itemid}"} , method=GET)public object getitems(@PathVariable String category,@PathVariable String itemid,@RequestParam(required=false) String location) {//代码}

@RequestParam中的参数可设置required属性决定是否必填,可通过defaultValue 设置默认值例如:@RequestMapping("/checkdata")public object getdata(@RequestParam(name="param", required=false, defaultValue="123") String param) {//代码}

以上都是常用注解的应用示例,配合工具插件可以更方便地查看注解生成的处理逻辑

上一篇:Springboot实现热部署
下一篇:Springboot整合SQLServer

发表评论

最新留言

感谢大佬
[***.8.128.20]2025年05月05日 10时36分19秒