Spring全家桶——SpringBoot Rest API

作者:cuifuan;
來源:Java知音


Spring Boot通過提供開箱即用的默認依賴或者轉換來補充Spring REST支持。在Spring Boot中編寫RESTful服務與SpringMVC沒有什麼不同。總而言之,基於Spring Boot的REST服務與基於Spring的REST服務完全相同,只是在我們引導底層應用程序的方式上有所不同。

1.REST簡短介紹

REST代表Representational State Transfer. 是一種架構風格,設計風格而不是標準,可用於設計Web服務,可以從各種客戶端使用.

基於REST的基本設計,其是根據一組動詞來控制的操作

  • 創建操作:應使用HTTP POST
  • 查詢操作:應使用HTTP GET
  • 更新操作:應使用HTTP PUT
  • 刪除操作:應使用HTTP DELETE

作為REST服務開發人員或客戶端,您應該遵守上述標準。

2.準備工作

項目的環境工具

  • SpringBoot 2.0.1.RELEASE
  • Gradle 4.7
  • IDEA 2018.2
  • MySQL5.7

項目結構圖

Spring全家桶——SpringBoot Rest API


3.開始

下面基於一種方式講解Restful

package com.example.controller;
import com.example.beans.PageResultBean;
import com.example.beans.ResultBean;
import com.example.entity.User;
import com.example.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("/user")
public class UserControllerAPI {
private final UserService userService;
@Autowired
public UserControllerAPI(UserService userService) {
this.userService = userService;
}
@RequestMapping(value = "/api", method = RequestMethod.GET)
public PageResultBean> getUserAll(PageResultBean page) {
return new PageResultBean<>(userService.getUserAll(page.getPageNo(), page.getPageSize()));
}
@RequestMapping(value = "/api/{id}", method = RequestMethod.GET)
public ResultBean getUserByPrimaryKey(@PathVariable("id") Integer id) {
return new ResultBean<>(userService.selectByPrimaryKey(id));
}
@RequestMapping(value = "/api/{id}", method = RequestMethod.PUT)
public ResultBean updateUserByPrimaryKey(@PathVariable("id") Integer id,User user) {
user.setId(id);
return new ResultBean<>(userService.updateByPrimaryKeySelective(user));
}
@RequestMapping(value = "/api/{id}", method = RequestMethod.DELETE)
public ResultBean deletePrimaryKey(@PathVariable("id") Integer id) {
return new ResultBean<>(userService.deleteByPrimaryKey(id));
}

@RequestMapping(value = "/api", method = RequestMethod.POST)
public ResultBean deletePrimaryKey(User user) {
return new ResultBean<>(userService.insertSelective(user));
}
}


  • 對於/user/api HTTP GET來請求獲取全部用戶
  • 對於/user/api HTTP POST來創建用戶
  • 對於/user/api/1 HTTP GET請求來獲取id為1的用戶
  • 對於/user/api/1 HTTP PUT請求來更新
  • 對於/user/api/1 HTTP DELETE請求來刪除id為1的用戶

HTTP GET請求/user/api 查詢全部

URL:http://localhost:8080/user/api

Spring全家桶——SpringBoot Rest API


HTTP GET請求/user/api/65 跟據id查詢

URL:http://localhost:8080/user/api/65

Spring全家桶——SpringBoot Rest API


HTTP POST請求/user/api 創建用戶

URL:http://localhost:8080/user/api

Spring全家桶——SpringBoot Rest API


HTTP PUT請求/user/api/65 來更新用戶信息

URL:http://localhost:8080/user/api/65

Spring全家桶——SpringBoot Rest API


HTTP DELETE請求/user/api/85 來刪除id為85的用戶

URL:http://localhost:8080/user/api/85

Spring全家桶——SpringBoot Rest API


4.業務層及dao層代碼

UserService.java 接口

package com.example.service;
import com.example.entity.User;
import java.util.List;
public interface UserService {
/**
* 刪除
* @param id
* @return
*/
String deleteByPrimaryKey(Integer id);
/**
* 創建
* @param record
* @return
*/
int insertSelective(User record);
/**
* 單個查詢
* @param id
* @return
*/
User selectByPrimaryKey(Integer id);
/**
* 更新
* @param record
* @return
*/
int updateByPrimaryKeySelective(User record);
/**
* 查詢全部
* @return
*/
List getUserAll(Integer pageNum, Integer pageSize);
}

UserServiceImpl.java


package com.example.service.impl;
import com.example.dao.UserMapper;
import com.example.entity.User;
import com.example.service.UserService;
import com.github.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Service
public class UserServiceImpl implements UserService {
private final static Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
private final UserMapper userMapper;
@Autowired(required = false)
public UserServiceImpl(UserMapper userMapper) {
this.userMapper = userMapper;
}
/**
* 刪除
*
* @param id
* @return
*/
@Transactional
@Override
public String deleteByPrimaryKey(Integer id) {
logger.info("UserServiceImpl deleteByPrimaryKey id => " + id);
User user = userMapper.selectByPrimaryKey(id);
String result;
if (user == null) {
result = "用戶ID[" + id + "]找不到!";
} else {
result = String.valueOf(userMapper.deleteByPrimaryKey(id));
}
return result;
}
/**
* 創建
*
* @param record
* @return
*/
@Transactional
@Override
public int insertSelective(User record) {

logger.info("UserServiceImpl insertSelective record=>"+record.toString());
return userMapper.insertSelective(record);
}
/**
* 單個查詢
*
* @param id
* @return
*/
@Override
public User selectByPrimaryKey(Integer id) {
logger.info("UserServiceImpl selectByPrimaryKey id=>"+id);
return userMapper.selectByPrimaryKey(id);
}
/**
* 更新
*
* @param record
* @return
*/
@Override
public int updateByPrimaryKeySelective(User record) {
logger.info("UserServiceImpl updateByPrimaryKeySelective record=>"+record.toString());
return userMapper.updateByPrimaryKeySelective(record);
}
/**
* 查詢全部
*
* @param pageNum
* @param pageSize
* @return
*/
@Override
public List getUserAll(Integer pageNum, Integer pageSize) {
logger.info("UserServiceImpl getUserAll pageNum=>"+pageNum+"=>pageSize=>"+pageSize);
PageHelper.startPage(pageNum,pageSize);
List userList = userMapper.getUserAll();
logger.info("UserServiceImpl getUserAll userList"+userList.size());
return userList;
}
}

UserMapper.java

Spring全家桶——SpringBoot Rest API


PageResultBean和ResultBean的代碼在GitHub

https://github.com/cuifuan/springboot-demo

實體層和mapper.xml代碼都是可以自動生成的,教程導航:

Spring全家桶系列--SpringBoot與Mybatis結合

4.理解RESTful

通過上面的編碼,如果你已經走通了上面的代碼,相信你已經對REST有了大致的掌握,時今當下的前端Client層出不窮,後端接口或許來自不同平臺,這時候需要請求一批接口,而RESTful風格的api,

使人從請求方式和地址一看就知道是要做什麼操作,根據返回code狀態就知道結果如何

使用RESTful直接帶來的便利:

之前的接口

  • 刪除 /user/delete
  • 添加 /user/create
  • 單個查詢 /user/queryById
  • 查詢全部 /user/queryAll
  • 更新 /user/update

採用RESTful設計API之後 /user/api一個URL地址解決,再也不用跟前端廢舌頭了,同時GET請求是冪等的,什麼是冪等?簡單通俗的說就是多次請求返回的效果都是相同的,例如GET去請求一個資源,無論請求多少次,都不會對數據造成創建修改等操作,PUT用來更新數據也是,無論執行多次的都是最終一樣的效果

問題:使用PUT改變學生年齡並且這樣做10次和做了一次,學生的年齡是相同的,是冪等的,那麼如果POST做相同操作,那麼它是如何不是冪等的?答:因為POST請求會在服務端創建與請求次數相同的服務,假如服務端每次請求服務會存在一個密鑰,那麼這個POST請求就可能不是冪等的,也或許是冪等的,所以POST不是冪等的。

因為PUT請求URL到客戶端定義的URL處完整地創建或替換資源,所以PUT是冪等的。 DELETE請求也是冪等的,用來刪除操作,其實REST就是相當於一個風格規範。

注意了,GET請求請不要用在delete操作上,你要問我為啥不行,你偏要那麼做,其實,整個CRUD操作你也都可以用GET來完成,哈哈,這個只是一個開發的設計風格。


分享到:


相關文章: