[翻译]Spring MVC RESTFul Web Service CRUD 例子
转自:http://www.cnblogs.com/leftthen/p/6378713.html
Spring MVC RESTFul Web Service CRUD 例子
本文主要翻译自:http://memorynotfound.com/spring-mvc-restful-web-service-crud-example/
本文主要讲解如何使用Spring MVC4搭建RestFul Web service。我们新建一个进行CRUD操作的controller,使用http方法的POST、GET、PUT、DELETE来区分新建、查询、修改、删除。这个rest service使用json进行数据传输。我们使用CrossOrigin来解决跨域问题。
Rest Controller
使用spring MVC4实现 一个REST Web Service 有很多种方式,我们选取下面这种最简单的。使用ResponseEntity直接控制response的响应头和http状态码。
- http GET方法 /users 请求全部用户数据
- http GET方法 /users/1 请求id为1的用户
- http POST方法 /users 使用json格式新建一个用户
- http PUT方法 /users/1 修改id为1的用户
- http DELETE方法 /users/1 删除id为1的用户
package com.memorynotfound.controller;
import com.memorynotfound.model.User;
import com.memorynotfound.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.util.UriComponentsBuilder;
import java.util.List;
@RestController
@RequestMapping("/users")
public class UserController {
private final Logger LOG = LoggerFactory.getLogger(UserController.class);
@Autowired
private UserService userService;
// =========================================== Get All Users ==========================================
@RequestMapping(method = RequestMethod.GET)
public ResponseEntity<List<User>> getAll() {
LOG.info("getting all users");
List<User> users = userService.getAll();
if (users == null || users.isEmpty()){
LOG.info("no users found");
return new ResponseEntity<List<User>>(HttpStatus.NO_CONTENT);
}
return new ResponseEntity<List<User>>(users, HttpStatus.OK);
}
// =========================================== Get User By ID =========================================
@RequestMapping(value = "{id}", method = RequestMethod.GET)
public ResponseEntity<User> get(@PathVariable("id") int id){
LOG.info("getting user with id: {}", id);
User user = userService.findById(id);
if (user == null){
LOG.info("user with id {} not found", id);
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
return new ResponseEntity<User>(user, HttpStatus.OK);
}
// =========================================== Create New User ========================================
@RequestMapping(method = RequestMethod.POST)
public ResponseEntity<Void> create(@RequestBody User user, UriComponentsBuilder ucBuilder){
LOG.info("creating new user: {}", user);
if (userService.exists(user)){
LOG.info("a user with name " + user.getUsername() + " already exists");
return new ResponseEntity<Void>(HttpStatus.CONFLICT);
}
userService.create(user);
HttpHeaders headers = new HttpHeaders();
headers.setLocation(ucBuilder.path("/user/{id}").buildAndExpand(user.getId()).toUri());
return new ResponseEntity<Void>(headers, HttpStatus.CREATED);
}
// =========================================== Update Existing User ===================================
@RequestMapping(value = "{id}", method = RequestMethod.PUT)
public ResponseEntity<User> update(@PathVariable int id, @RequestBody User user){
LOG.info("updating user: {}", user);
User currentUser = userService.findById(id);
if (currentUser == null){
LOG.info("User with id {} not found", id);
return new ResponseEntity<User>(HttpStatus.NOT_FOUND);
}
currentUser.setId(user.getId());
currentUser.setUsername(user.getUsername());
userService.update(user);
return new ResponseEntity<User>(currentUser, HttpStatus.OK);
}
// =========================================== Delete User ============================================
@RequestMapping(value =
