最近两年工做的主要内容是给前端提供API接口,包括各类联调等,项目中使用的框架有spring全家桶、Jfinal等,最近学习了下很火的SpringBoot,配合Swagger2写Restful接口及文档很是方便简洁,一下是一些相关笔记。前端
当使用@RequestMapping URI template 样式映射时,@PathVariable能使传过来的参数绑定到路由上,这样比较容易写出restful api,看代码spring
@RequestMapping(value="/{id}", method=RequestMethod.GET) public List<Map<String, Object>> getUser(@PathVariable Integer id) { return userService.getUserById(id); }
上面这个接口可经过get请求 http://xxxxx/1111来获得想要的数据,1111既是getUser的方法参数又是@RequestMapping的路由。若是方法参数不想写成和路由同样的应该怎么办?看代码:json
@RequestMapping(value="/{uid}", method=RequestMethod.GET) public List<Map<String, Object>> getUser(@PathVariable("uid") Integer id) { return userService.getUserById(id); }
在@PathVariable后面接入“uid”就能够了。api
@RequestParam和@PathVariable的区别就在于请求时当前参数是在url路由上仍是在请求的body上,例若有下面一段代码:restful
@RequestMapping(value="", method=RequestMethod.POST) public String postUser(@RequestParam(value="phoneNum", required=true) String phoneNum ) String userName) { userService.create(phoneNum, userName); return "success"; }
这个接口的请求url这样写:http://xxxxx?phoneNum=xxxxxx,也就是说被@RequestParam修饰的参数最后经过key=value的形式放在http请求的Body传过来,对比下上面的@PathVariable就很容易看出二者的区别了。app
@RequestBody能把简单json结构参数转换成实体类,以下代码:框架
@RequestMapping(value = "/testUser", method = RequestMethod.POST) public String testUser(@RequestBody User user){ System.out.print(user.getAge()); return "success"; }
参数为:post
{"id":1,"user":"pkxutao","name":"name","age":18}