博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Boot - 构建RESTful API与单元测试
阅读量:6892 次
发布时间:2019-06-27

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

  hot3.png

标记该 class为处理http请求的对象

@RestController Spring4后加入的注解,原来@Controller中返回 json需要返回@ResponseBody。使用@RestController不需要配置,自动默认返回 json。

RESTful api设计

请求类型 URL 功能说明
GET /users 查询用户列表
POST /users 创建一个用户
GET /users/id 根据 id查询用户
PUT /users/id 根据 id更新用户
DELETE /users/id 根据 id删除用户

 

@RestController@RequestMapping("/users")public class UserController {    //创建线程安全的 map    static Map
users = Collections.synchronizedMap(new HashMap
()); @RequestMapping(value = "/", method = RequestMethod.GET) public List
getUserList() { ArrayList
users = new ArrayList
(UserController.users.values()); return users; } @RequestMapping(value = "/", method = RequestMethod.POST) public String postUser(@ModelAttribute User user) { users.put(user.getId(), user); return "success"; } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public User getUser(@PathVariable Long id) { return users.get(id); } @RequestMapping(value = "/{id}", method = RequestMethod.PUT) public String putUser(@PathVariable Long id, @ModelAttribute User user) { User u = users.get(id); u.setName(user.getName()); u.setAge(user.getAge()); users.put(id, u); return "success"; } @RequestMapping(value = "/{id}", method = RequestMethod.DELETE) public String deleteUser(@PathVariable Long id) { users.remove(id); return "success"; }}

 

转载于:https://my.oschina.net/lemos/blog/829581

你可能感兴趣的文章
Opentracing Zipkin
查看>>
构建高可用服务器之四 Keepalive冗余Nginx
查看>>
android音频采集
查看>>
SHELL控制流结构笔记
查看>>
路由重分布新技术实现多种路由协议不同网络间通信案例实操应用
查看>>
打印机无法打印测试页
查看>>
【图文详解】Iptables
查看>>
Zabbix-web的中文显示及其乱码问题解决方法
查看>>
Gluster管理命令的总结与归纳
查看>>
FreeNAS如何配置LACP(链路聚合和故障)
查看>>
云场景实践研究第6期:游族网络
查看>>
记录由Equal基础知识引起的内存泄露
查看>>
Android:Sensor传感器
查看>>
Eclipse配置实现定制登录界面
查看>>
NO.1 进入IT世界
查看>>
Exceeded maximum number of retries. Exceeded max scheduling attempts 3 for instance
查看>>
Asp.net mvc 3.0新特性-浅析1
查看>>
Hadoop FSDataInputStream 流定位的例子
查看>>
在OWA页面中,增加忘记密码项
查看>>
Samba文件共享服务(共享脚本 让你工作更轻松)
查看>>