Spring Boot構建RESTful API


  • @Controller:修飾class,用來創建處理http請求的對象
  • @RestController:Spring4之后加入的注解,原來在@Controller中返回json需要@ResponseBody來配合,如果直接用@RestController替代@Controller就不需要再配置@ResponseBody,默認返回json格式。
  • @RequestMapping:配置url映射
  • RESTful API具體設計如下:
請求類型 URL 功能說明
GET /users 查詢用戶列表
POST /users 創建一個用戶
GET /users/id 根據id查詢一個用戶
PUT /users/id 根據id更新一個用戶
DELETE /users/id
  1. 根據id刪除一個用戶

User實體定義:

     private Long id; 
    private String name; 
    private Integer age; 

    // 省略setter和getter

User  restful接口聲明

@RequestMapping(value = "/users")
public interface UserRestService {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    List<User> getUserList();

    @RequestMapping(value = "/", method = RequestMethod.POST)
    String postUser(@ModelAttribute User user);

    @RequestMapping(value = "/{id}", method = RequestMethod.GET)
    User getUser(@PathVariable Long id);

    @RequestMapping(value="/{id}", method=RequestMethod.PUT)
     String putUser(@PathVariable Long id, @ModelAttribute User user);

    @RequestMapping(value="/{id}", method=RequestMethod.DELETE)
    String deleteUser(@PathVariable Long id);
}

接口實現

@RestController
public class UserRestServiceImpl implements  UserRestService {

    static Map<Long, User> users = Collections.synchronizedMap(new HashMap<Long, User>());

    @Override
    public List<User> getUserList() {
        List<User> r = new ArrayList<User>(users.values());
        return r;
    }

    @Override
    public String postUser(@ModelAttribute User user) {
        users.put(user.getId(), user);
        return "success";
    }

    @Override
    public User getUser(@PathVariable Long id) {
        return users.get(id);
    }

    @Override
    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";
    }

    @Override
    public String deleteUser(@PathVariable Long id) {
        users.remove(id);
        return "success";
    }
}

驗證:

以創建用戶為例

response

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM