天天看點

Axios與SpringBoot參數互動方式Get請求Post請求總結與建議

Axios與SpringBoot的請求參數互動方法

  • Get請求
    • 普通類型參數、對象類型參數
      • 前端
      • 背景
        • 實體類
        • Controller
    • 數組、集合類型參數
      • 前端
      • 背景
  • Post請求
    • json類型傳遞
      • 前端
      • 背景
        • 實體類
        • Controller
    • x-www-form-urlencoded類型傳遞
      • 前端
      • 背景
    • x-www-form-urlencoded傳遞複雜對象集合的可行方案
      • 前端
      • 背景
  • 總結與建議
    • 總結
      • x-www-form-urlencoded
      • application/json
    • 建議

Get請求

普通類型參數、對象類型參數

前端

const params={
	username1:"5",
	password1:"6",
	username:"7",
	password:"8"
}
this.$http.get(`/index`,{
	params,
})
           

背景

實體類

public class User1 implements Serializable {
    private String username1;
    private String password1;
}
           

Controller

@GetMapping("/index")
public AjaxResult index(User1 user1, String username, String password){
      AjaxResult rs = new AjaxResult();
      System.out.println(user1);
      System.out.println(username);
      System.out.println(password);
      rs.setCode(200);
      return rs;
  }
           

qs子產品在axios中存在,無需單獨安裝,如果報錯,可通過npm install qs -S進行安裝

注意:在/Index這個請求處理方法下,所有參數名、類中所有屬性名不允許重複,重名則值會被覆寫

數組、集合類型參數

前端

const params={
	ids:['1','2','3','4','5','6','7'],
	listIds:['7','6','5','4','3','2','1']
}
this.$http.get(`/index`,{
	params,
	paramsSerializer: {
		serialize:function(params) {
			return qs.stringify(params, {arrayFormat: 'repeat',allowDots:false})
		}
	}
})
           

背景

@GetMapping("/index")
public AjaxResult index(
	@RequestParam("ids") String[] ids,
	@RequestParam("listIds") List<String> listIds){
	       AjaxResult rs = new AjaxResult();
	       for (String id : ids) {
	           System.out.println(id);
	       }
	       listIds.forEach(System.out::println);
	       rs.setCode(200);
	       return rs;
}
           

注意:此處的@RequestParam不可省略;不可傳遞類似List<User> users的複雜對象集合(需自定義參數解析器)

Post請求

json類型傳遞

前端

const data={
	users:[
		{
			username:1,
			password:2
		},
		{
			username:3,
			password:4
		}
	],
	username:5,
	password:6
}
this.$http.post(`/index`,data)
           

背景

實體類

public class RequestVo implements Serializable {
    private List<User> users;
    private String username;
    private String password;
}
           

Controller

@PostMapping ("/index")
 public AjaxResult index(@RequestBody RequestVo vo){
     AjaxResult rs = new AjaxResult();
     System.out.println(vo);
     rs.setCode(200);
     return rs;
 }
           

注意:

1. 一個@RequestMapping隻能有一個@RequestBody

2. get請求沒有請求體,不支援@RequestBody

x-www-form-urlencoded類型傳遞

前端

const data={
	ids:[1,2,3],
	username1:3,
	password1:4,
	username:5,
	password:6
}
this.$http.post(`/index`,data,{
	transformRequest: [function (data, headers) {
		return qs.stringify(data, {arrayFormat: 'repeat',allowDots:false});
	}],
})
           

背景

@PostMapping ("/index")
public AjaxResult index(
	User1 user1,
	String username,
	String password,
	@RequestParam("ids") List<String> ids){
	    AjaxResult rs = new AjaxResult();
	    System.out.println(user1);
	    System.out.println(username);
	    System.out.println(password);
	    ids.forEach(System.out::println);
	    rs.setCode(200);
    return rs;
}
           

注意:

1. 屬性名、對象内的屬性名不允許重複,重複會被覆寫

2. 通過該方式仍然不能傳輸List<User>這種複雜對象的集合

x-www-form-urlencoded傳遞複雜對象集合的可行方案

如果不想封裝VO對象,使用@RequestBody接收資料,可采用如下方式傳遞List<User>這種複雜對象的集合。

前端

const users=[
	{
		username:1,
		password:2
	},
	{
		username:3,
		password:4
	}
]
const data = {
	users:JSON.stringify(users),
	username1:5,
	password1:6,
	username:7,
	password:8
}
this.$http.post(`/index`,data,{
	transformRequest: [function (data, headers) {
		return qs.stringify(data,{arrayFormat:'repeat',allowDots:false})
	}],
})
           

背景

@PostMapping ("/index")
public AjaxResult index(String users,User1 user1,String username,String password){
    AjaxResult rs = new AjaxResult();
    // com.alibaba.fastjson.JSONObject
    List<User> list = JSONObject.parseArray(users, User.class);
    list.forEach(System.out::println);
    System.out.println(user1);
    System.out.println(username);
    System.out.println(password);
    rs.setCode(200);
    return rs;
}
           

總結與建議

總結

x-www-form-urlencoded

  • 請求頭支援以下3種内容的傳遞:

    1. 基本類型:如Integer、String、Boolean等

    2. 對象類型:如User等自定義類(隻包含基本類型)

    3. 由基本類型構成的數組或集合:如List<String>、List<Long>等

  • 傳遞數組或集合時必須指定@RequestParam(“屬性名”)
  • 傳遞的參數名和對象的屬性名之間不允許重名,否則對象屬性值會被覆寫

    例如:

public class User{
	public String username;
	public String password;
}
@GetMapping("/index")
public AjaxResult index(User user,String username,String password){
	//...
}
           

注意:上述寫法會造成user對象被注入的username和password值不正确

application/json

  • 前台設定請求頭為application/json;charset=utf-8後,直接發送資料即可
  • 背景将多個複雜參數封裝為一個Vo對象,用@RequestBody接收即可
  • 僅post請求支援該方式,且一個RequestMapping隻能有一個@RequestBody
  • 也可以通過Springboot自定義參數解析器實作@MultiRequestBody

建議

  • 不建議Get請求傳List<User>這種複雜對象,建議傳List<Long> ids,由背景進行查詢
  • 不建議Post請求使用x-www-form-urlencoded類型傳List<User>這種複雜對象,麻煩且容易丢失資料,建議封裝Vo對象通過@RequestBody接收
  • axios可通過如下方式進行封裝,統一處理參數:
// src/main.js
import Vue from 'vue'
import App from './App.vue'
import axios from 'axios'

// 根據需要2選1即可
//axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
//axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8';

/*
// get請求的參數處理器(x-www-form-urlencoded)
axios.defaults.paramsSerializer = {
	serialize:function(params) {
		return qs.stringify(params, {arrayFormat: 'repeat',allowDots:false})
	}
}

// post請求的參數處理器(x-www-form-urlencoded,背景如果用@RequestBody無需此部分)
axios.defaults.transformRequest = [function (data, headers) {
	return qs.stringify(data,{arrayFormat:'repeat',allowDots:false})
}]

Vue.prototype.$http=axios;

new Vue({
  render: h => h(App),
}).$mount('#app')

*/