您的位置:首页 > 编程语言 > Java开发

Spring Boot - 构建RESTful API与单元测试

2017-01-23 00:00 274 查看
原文

@Controller 标记该 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<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());

@RequestMapping(value = "/", method = RequestMethod.GET)
public List<User> getUserList() {
ArrayList<User> users = new ArrayList<User>(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";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: