什么是restful rest是一种设计风格 它是一种思想
直接上例子。。
GET http://127.0.0.1/user/{id} 获取用户数据
POST http://127.0.0.1/user form表单数据 新增用户数据
PUT http://127.0.0.1/user 更新用户数据
DELETE http://127.0.0.1/user 删除用户数据
user表示接收的参数是实体类
springMvc 实现restful
@Autowired
private UserService userService;
/**
* 根据ID查询用户数据
* @param id
* @return
*/
@RequestMapping(value = "user/{id}", method = RequestMethod.GET)
@ResponseBody
public ResponseEntity<User> queryUserById(@PathVariable("id") Long id) {
try {
User user = this.userService.queryUserById(id);
if (user != null) {
return ResponseEntity.ok(user);
}
return ResponseEntity.status(HttpStatus.NOT_FOUND).body(user);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(null);
}
}
/**
* 新增用户数据
* @param user
* @return
*/
@RequestMapping(value = "user", method = RequestMethod.POST)
public ResponseEntity<Void> saveUser(User user){
try {
this.userService.saveUser(user);
//返回201状态
return ResponseEntity.status(HttpStatus.CREATED).build();
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
/**
* 更新数据
* @param user
* @return
*/
@RequestMapping(value = "user", method = RequestMethod.PUT)
public ResponseEntity<Void> updateUser(User user){
try {
this.userService.updateUser(user);
//返回201状态
return ResponseEntity.ok(null);
} catch (Exception e) {
e.printStackTrace();
//500
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
/**
* 删除数据
* @param user
* @return
*/
@RequestMapping(value = "user", method = RequestMethod.DELETE)
public ResponseEntity<Void> updateUser(@RequestParam("ids")Long[] ids){
try {
this.userService.deleteUser(ids);
//返回204状态
return ResponseEntity.status(HttpStatus.NO_CONTENT).build();
} catch (Exception e) {
e.printStackTrace();
//500
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).build();
}
}
附上http响应状态码: