1、技術概述
現在大多數Web項目都采取前后端分離的方法,用Springboot后端獲取前端傳遞的數據並進行業務邏輯處理和接口封裝,是一項既簡單又重要的操作。
2、技術詳述
(1)確定傳輸方式
用POST提交不同傳輸方式獲取參數的方式不同。
前端Content-Type | JSON對象/字符串 | 后端參數獲取方法 |
---|---|---|
application/x-www-form-urlencoded | 對象 | @RequestParam 或者Servlet |
application/json | 字符串 | @RequestBody |
(2)定義規范的數據結構
建議最好自行定義一個規范的數據交互結構,既美觀又實用
public class JsonUtil {
public static HashMap<String, Object> success(Map<String, Object> data) {
HashMap<String, Object> res = new HashMap<>();
res.put("code", ResCode.SUCCESS.getCode()); //正確碼
res.put("msg", ""); //備注消息
res.put("data", data); //數據
return res;
}
效果如下:
{
code: 200, //響應代碼
msg: '', //消息,正常時不帶此條,出錯時附加錯誤信息
data: {} //數據
}
(3)GET請求
get請求一般用於查詢數據,采用明文進行傳輸,一般用來獲取一些無關用戶信息的數據
請求方式一般通過url傳參,如http://localhost:8080/hello
@GetMapping 組合注解,是 @RequestMapping(method = RequestMethod.GET) 的縮寫
一個簡單的例子:
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello() {
return "Hello Spring Boot!";
}
}
結果如下:
也可以在url后面帶上參數,如http://localhost:8080/config?id=1,可以使用@RequestParam注解獲取指定參數值。
代碼如下:
@RestController
public class UserController {
@Autowired
private UserService userService;
@Autowired
private ImageTypeService imageTypeService;
@Autowired
private CollectionService collectionService;
@RequestMapping(value = "/config",produces = "application/json;charset=utf-8",method= RequestMethod.GET)
@ResponseBody
public ResponseEntity<Map<String, Object>> getConfig(@RequestParam("id") Integer id){
User user = userService.getUserById(id);
List<String> imageTypeList = imageTypeService.getNameByUId(id);
List<String> collectionList = collectionService.getNameByUId(id);
Map<String,Object> map = new HashMap<String, Object>();
map.put("name",user.getName());
map.put("imageType",imageTypeList);
map.put("collection",collectionList);
return ResponseEntity.ok(JsonUtil.success(map));
}
}
結果如下:
(4)POST請求
post請求一般用於修改數據,將前端的數據傳送給后端,並返回指定內容。
當Ajax以application/x-www-form-urlencoded格式上傳即使用JSON對象,后台只能使用@RequestParam 或者Servlet獲取參數。 當Ajax以application/json格式上傳即使用JSON字符串,后台可以使用@RequestBody或者@RequestParam獲取。
@PostMapping 組合注解,是 @RequestMapping(method = RequestMethod.POST) 的縮寫
后端代碼如下:
public class UserController {
@Autowired
private UserService userService;
@Autowired
private ImageTypeService imageTypeService;
@Autowired
private CollectionService collectionService;
@RequestMapping(value = "/config",produces = "application/json;charset=utf-8",method= RequestMethod.POST)
@ResponseBody
public ResponseEntity<Map<String, Object>> postConfig(@RequestBody Map<String,Object> map){
User user = new User();
int id = (int)map.get("id");
user.setId(id);
user.setAmonutPerDay((int)map.get("amonutPerDay"));
user.setBookId((int)map.get("bookId"));
user.setTimesToChangeBackground((int)map.get("timesToChangeBackground"));
user.setDurationKeepAfterRecite((int)map.get("durationKeepAfterRecite"));
user.setTipsDuration((int)map.get("tipsDuration"));
List<String> imageTypeList = (List<String>)map.get("imageList");
List<String> collectionList = (List<String>)map.get("collection");
userService.update(user);
imageTypeService.update(imageTypeList,id);
collectionService.update(collectionList,id);
return ResponseEntity.ok(JsonUtil.success());
}
}
前端代碼:
function a(){
$.ajax({
url:"/config",
type:"post",
contentType: "application/json;charset=utf-8",
data:JSON.stringify({
"id":1,
"amountPerDay":100,
"bookId":1,
"timesToChangeBackground": 1,
"durationKeepAfterRecite": 1500,
"tipsDuration": 1000,
"imagesType": ['aa','abc','ade','cc'],
"collection": ['admin', 'apple']
})
})
}
結果展示:
3、技術使用中遇到的問題和解決過程
- 從前台傳輸的數據為空
解決:@RequestBody或@RequestParam使用有誤,首先要注意傳輸方式,其次要注意兩者的用法及讀取數據的格式有區別。 - @RequestBody與@ResponseBody的區別
解決:@RequestBody的作用是將前端傳來的json格式的數據轉為自己定義好的javabean對象,不能寫在方法名上方。@ResponseBody的作用是將后端以return返回的javabean類型數據轉為json類型數據。
4、總結
后端接口開發算是一個最基本最簡單的技術,但是它的意義非同一般,是Web項目能夠實現前后端分離的關鍵技術。想要成為一名優秀的后端工程師,還需要更加努力學習。
5、參考文獻、參考博客
CSDN博客:SpringBoot實現前后端數據交互、json數據交互、Controller接收參數的幾種常用方式
CSDN博客:Spring中的注解@RequestBody和@ResponseBody的使用和區別