以用戶增刪改查爲例,設計 REST API.前端
這裏,咱們主要關注Spring Mvc中的Controller的設計:web
UserController類:ajax
@RestController @RequestMapping(value = "/users") public class UserController extends BaseController {
@Autowired
private IUserService userService; ... }
這裏使用了@RestController註解,Spring將會爲該Controller的全部處理方法應用消息轉換功能,所以咱們能夠沒必要爲每一個方法都添加@ResponseBody。json
Spring支持多種資源表述形式(JSON/XML/HTML...),不過通常使用JSON形式。服務器
對應請求的URL示例(無分頁):http://localhost:8080/webbf/usersapp
對應的URL示例(有分頁):http://localhost:8080/webbf/users?offset=0&limit=10async
使用的HTTP方法:GET工具
若是查詢不到用戶,返回狀態碼204,No Contentpost
不然,返回狀態碼200, OK,返回的數據類型爲 application/json;charset=utf-8測試
@RequestMapping(method = RequestMethod.GET, produces = "application/json; charset=utf-8") public ResponseEntity<List<User>> getUserList( @RequestParam(value = "offset", defaultValue = "0") long offset, @RequestParam(value = "limit", defaultValue = MAX_LONG_AS_STRING) long limit) { Map<String, Object> param = new HashMap<String, Object>(); param.put("offset", offset); param.put("limit", limit); List<User> userList = userService.query(param); if (userList.size() == 0) { return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT); } return new ResponseEntity<List<User>>(userList, HttpStatus.OK); }
對應請求的URL示例:http://localhost:8080/webbf/users/1
使用的HTTP方法:GET
若是查詢不到用戶,返回狀態碼404,Not Found
不然,返回狀態碼200, OK,返回的數據類型爲 application/json;charset=utf-8
@RequestMapping(value = "/{id}", method = RequestMethod.GET, produces = "application/json; charset=utf-8") public ResponseEntity<User> getUserById(@PathVariable Long id) { User user = userService.findById(id); if (user == null) { return new ResponseEntity<User>(HttpStatus.NOT_FOUND); } return new ResponseEntity<User>(userService.findById(id), HttpStatus.OK); }
對應請求的URL示例:http://localhost:8080/webbf/users/1
使用的HTTP方法:DELETE
若是查詢不到被刪除的用戶,返回狀態碼404,Not Found
不然,刪除成功,返回狀態碼204, No Content
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE, produces = "application/json; charset=utf-8") public ResponseEntity<User> deleteUser(@PathVariable Long id) { User user = userService.findById(id); if (user == null) { return new ResponseEntity<User>(HttpStatus.NOT_FOUND); } userService.deleteUser(id); return new ResponseEntity<User>(HttpStatus.NO_CONTENT); }
對應請求的URL示例:http://localhost:8080/webbf/users
請求體:
{
"name":"1",
"address":"aa"
}
Content-Type: application/json
使用的HTTP方法:POST
響應的body爲新建立的用戶;
響應頭的Location:http://localhost:8080/webbf/users/60
//若是用戶已存在,返回狀態碼,409, Conflict
保存成功,返回狀態碼201, Created,返回的數據類型爲 application/json;charset=utf-8
@RequestMapping(method = RequestMethod.POST, consumes = "application/json; charset=utf-8") public ResponseEntity<User> saveUser(@RequestBody User user, UriComponentsBuilder ucb) { // if (userService.isUserExist(user)) { // System.out.println("A User with name " + user.getName() + // " already exist"); // return new ResponseEntity<User>(user, HttpStatus.CONFLICT); // } User saved = userService.saveUser(user); HttpHeaders headers = new HttpHeaders(); URI locationUri = ucb.path("/users/").path(String.valueOf(saved.getId())).build().toUri(); headers.setLocation(locationUri); ResponseEntity<User> responseEntity = new ResponseEntity<User>(saved, headers, HttpStatus.CREATED); return responseEntity; }
對應請求的URL示例:http://localhost:8080/webbf/users/1
請求體:
{
"name":"1",
"address":"aa"
}
Content-Type: application/json
使用的HTTP方法:PUT
響應的body爲新建立的用戶;
若是查詢不到被修改的用戶,返回狀態碼404,Not Found
保存成功,返回狀態碼201, Created,返回的數據類型爲 application/json;charset=utf-8
@RequestMapping(value = "/{id}", method = RequestMethod.PUT, consumes = "application/json; charset=utf-8") public ResponseEntity<User> updateUser(@PathVariable("id") long id, @RequestBody User user) { User currentUser = userService.findById(id); if (currentUser == null) { return new ResponseEntity<User>(HttpStatus.NOT_FOUND); } currentUser.setId(id); currentUser.setName(user.getName()); currentUser.setAddress(user.getAddress()); userService.updateUser(currentUser); return new ResponseEntity<User>(currentUser, HttpStatus.OK); }
請求中發生異常,返回500 Internal Server Error。
@ExceptionHandler(Exception.class) @ResponseBody public ResponseEntity<Exception> handleException(HttpServletRequest request, Exception e) { logger.error("Request FAILD, URL = {} method = {}", request.getRequestURI(), request.getMethod()); logger.error(e.toString(), e); return new ResponseEntity<Exception>(e, HttpStatus.INTERNAL_SERVER_ERROR); }
由於我喜歡用fireFox, 因此我用restclient測試工具測試 REST API:
chrom的話,能夠使用Postman。
$.ajax({ async: false, type : "get", url : "/webbf/users", data: {}, datatype : 'json', success : function(data,textStatus) { this.trigger({userList:data}); }.bind(this), error: function(jqXHR, textStatus, errorThrown) { alert(jqXHR.status + ' ' + jqXHR.responseText); } });
$.ajax({ async: false, type : "delete", url : "/webbf/users/" + userId, data: {}, datatype : 'json', success : function(data) { alert("刪除成功"); this.getAllUser(); }.bind(this), error: function(jqXHR, textStatus, errorThrown) { alert(jqXHR.status + ' ' + jqXHR.responseText); } });
$.ajax({ async: false, contentType: "application/json; charset=utf-8", type : "post", url : "/webbf/users", data: JSON.stringify({name:userName,address:address}), datatype : 'json', success : function(data) { alert("操做成功"); this.openAddModal(false); this.getAllUser(); }.bind(this), error: function(jqXHR, textStatus, errorThrown) { alert(jqXHR.status + ' ' + jqXHR.responseText); } });
Spring in action 4