SpringBoot項目接收前端參數(shù)的11種方式
1 搭建項目
1.通過Spring Initializr選項創(chuàng)建一個項目名稱為【sb_receive_param】的SpringBoot項目。

2.給項目添加Spring Web依賴。

3.在com.cy.sb_receive_param.pojo包下創(chuàng)建User實體類。
package com.cy.sb_receive_param.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User implements Serializable {
private Integer id;
private String username;
private String password;
private Cat cat;
private List<Course> courses;
}4.在com.cy.sb_receive_param.controller包下創(chuàng)建UserController類。
package com.cy.sb_receive_param.controller;
import org.springframework.web.bind.annotation.*;
@RequestMapping("users")
@RestController
public class UserController {
}5.解決在前后端分離項目中的跨域問題。通過實現(xiàn)WebMvcConfigurer接口,并重寫addCorsMappings(CorsRegistry registry)方法來實現(xiàn)。
package com.cy.sb_receive_param.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class CrossOriginConfig implements WebMvcConfigurer {
/**
* addMapping("/**"):配置可以被跨域的路徑,可以任意配置,可以具體到直接請求路徑
* allowedOrigins("*"):允許所有的請求域名訪問我們的跨域資源,可以固定單條或者多條內容,如"http://www.yx.com",只有該域名可以訪問我們的跨域資源
* allowedHeaders("*"):允許所有的請求header訪問,可以自定義設置任意請求頭信息
* allowedMethods():允許所有的請求方法訪問該跨域資源服務器,如GET、POST、DELETE、PUT、OPTIONS、HEAD等
* maxAge(3600):配置客戶端可以緩存pre-flight請求的響應的時間(秒)。默認設置為1800秒(30分鐘)
*/
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOrigins("*")
.allowedHeaders("*")
.allowedMethods("GET", "POST", "DELETE", "PUT", "OPTIONS", "HEAD")
.maxAge(3600);
}
}2 Spring Boot接收前端參數(shù)方式
2.1 傳非JSON數(shù)據(jù)
2.1.1 注解介紹
@RequestParam主要用于在Spring MVC后臺控制層獲取參數(shù),它有三個常用參數(shù)。
參數(shù)名 | 描述 |
defaultValue | 表示設置默認值 |
required | 表示該參數(shù)是否必傳 |
value | 值表示接收傳入的參數(shù)的key |
@PathVariable用于將請求URL中的模板變量映射到功能處理方法的參數(shù)上,即取出URL模板中的變量作為參數(shù)。
2.1.2 案例演示
1.方式一
1.在UserController類中添加add1()請求處理方法。前端請求參數(shù)的key需和后端控制層處理請求的方法參數(shù)名稱一致。
@RequestMapping("add1")
public void add1(String username, String password) {
System.out.println("username=" + username + ", password=" + password);
}2.使用ApiPost工具測試(GET和POST請求都支持)。
localhost:8080/users/add1?username=tom&password=123456
3.創(chuàng)建param01.html頁面,通過Axios發(fā)送請求。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>前后端參數(shù)傳遞</title>
<script src="https://unpkg.com/vue@next"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const app = {
data() {
return {
username: '王小虎',
password: '123456'
}
},
mounted() {
axios.get('http://localhost:8888/users/add1', {
params: {
username: this.username,
password: this.password
}
}).then(response => {
console.log('success', response.data);
}).catch(error => {
console.log('fail', error.data);
});
}
}
Vue.createApp(app).mount('#app')
</script>
</body>
</html>2.方式二
1.在UserController類中添加add2()請求處理方法。如果前端請求參數(shù)的key與后端控制層處理請求的方法參數(shù)名稱不一致,使用@RequestParam注解來解決。
@RequestMapping("add2")
public void add2(@RequestParam("name") String username, @RequestParam("pwd") String password) {
System.out.println("username=" + username + ", password=" + password);
}2.使用ApiPost工具測試(GET和POST請求都支持)。
localhost:8080/users/add2?name=tom&pwd=123456
3.創(chuàng)建param02.html頁面,通過Axios發(fā)送請求。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>前后端參數(shù)傳遞</title>
<script src="https://unpkg.com/vue@next"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const app = {
data() {
return {
username: '張小三',
password: '654321'
}
},
mounted() {
axios.get('http://localhost:8888/users/add2', {
params: {
name: this.username,
pwd: this.password
}
}).then(response => {
console.log('success', response.data);
}).catch(error => {
console.log('fail', error.data);
});
}
}
Vue.createApp(app).mount('#app')
</script>
</body>
</html>3.接收前端傳數(shù)組參數(shù)
1.在UserController類中添加delete1()請求處理方法。
@DeleteMapping("batch_delete1")
public void delete1(@RequestParam(name = "ids") List<Integer> ids) {
for (Integer id : ids) {
System.out.println(id);
}
}2.使用ApiPost工具測試,在【Query】選項下添加ids參數(shù),參數(shù)值設置為1,3,5。

3.使用ApiPost工具測試,在【Query】選項下添加ids參數(shù),將參數(shù)的值單獨一個個進行添加。

4.創(chuàng)建param03.html頁面,通過Axios發(fā)送請求。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>前后端參數(shù)傳遞</title>
<script src="https://unpkg.com/vue@next"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const app = {
data() {
return {
ids: [1, 3, 5]
}
},
mounted() {
axios.delete('http://localhost:8888/users/batch_delete1', {
params: {
ids: this.ids.join(',')
}
}).then(response => {
console.log('success', response.data);
}).catch(error => {
console.log('fail', error.data);
});
}
}
Vue.createApp(app).mount('#app')
</script>
</body>
</html>4.方式四
1.在UserController類中添加add3()請求處理方法。前端請求參數(shù)的key需和后端控制層處理請求方法的參數(shù)pojo實體類的屬性名稱一致。
@RequestMapping("add3")
public void add3(User user) {
System.out.println(user);
}2.使用ApiPost工具測試(GET和POST請求都支持)。
localhost:8080/users/add3?id=1&username=tom&password=123
3.創(chuàng)建param04.html頁面,通過Axios發(fā)送請求。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>前后端參數(shù)傳遞</title>
<script src="https://unpkg.com/vue@next"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const app = {
data() {
return {
id: 1,
username: '王小明',
password: '123456'
}
},
mounted() {
axios.get('http://localhost:8888/users/add3', {
params: {
id: this.id,
username: this.username,
password: this.password
}
})
.then(response => {
console.log('success', response.data);
}).catch(error => {
console.log('fail', error.data);
});
}
}
Vue.createApp(app).mount('#app')
</script>
</body>
</html>5.方式五
1.在UserController類中添加add4()請求處理方法。使用@PathVariable注解將請求URL中的模板變量映射到功能處理方法的參數(shù)上,如果模板變量名稱和方法的參數(shù)名稱不同需要在@PathVariable注解上顯示的指定映射關系。
@RequestMapping("add4/{username}/{pwd}")
public void add4(@PathVariable String username, @PathVariable("pwd") String password) {
System.out.println("username=" + username + ", password=" + password);
}2.使用ApiPost工具測試(GET和POST請求都支持)。
localhost:8080/users/add4/tom/123456
3.創(chuàng)建param05.html頁面,通過Axios發(fā)送請求。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>前后端參數(shù)傳遞</title>
<script src="https://unpkg.com/vue@next"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const app = {
data() {
return {
username: '袁庭新',
password: '123456'
}
},
mounted() {
axios.post(`http://localhost:8888/users/add4/${this.username}/${this.password}`)
.then(response => {
console.log('success', response.data);
}).catch(error => {
console.log('fail', error.data);
});
}
}
Vue.createApp(app).mount('#app')
</script>
</body>
</html>6.方式六
1.在UserController類中添加add5()請求處理方法。通過HttpServletRequest對象獲取數(shù)據(jù),前端請求參數(shù)的key需和getParameter(String name)方法傳遞的參數(shù)名稱一致。
@RequestMapping("add5")
public void add5(HttpServletRequest request) {
String username = request.getParameter("username");
String password = request.getParameter("password");
System.out.println("username=" + username + ", password=" + password);
}2.使用ApiPost工具測試(GET和POST請求都支持)。
localhost:8080/users/add5?username=tom&password=123
3.創(chuàng)建param06.html頁面,通過Axios發(fā)送請求。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>前后端參數(shù)傳遞</title>
<script src="https://unpkg.com/vue@next"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const app = {
data() {
return {
username: '袁庭新',
password: '123456'
}
},
mounted() {
axios.post('http://localhost:8888/users/add5', null, {
params: {
username: this.username,
password: this.password
}
})
.then(response => {
console.log('success', response.data);
}).catch(error => {
console.log('fail', error.data);
});
}
}
Vue.createApp(app).mount('#app')
</script>
</body>
</html>2.2 傳JSON數(shù)據(jù)
2.2.1 注解介紹
@RequestBody該注解會把接收到的參數(shù)轉為JSON格式。如果前端通過application/json類型提交JSON格式的數(shù)據(jù)給后端控制層處理請求的方法,方法的參數(shù)必須使用@RequestBody注解進行修飾,才能接收來自前端提交的JSON數(shù)據(jù)。
2.2.2 案例演示
1.接收前端傳數(shù)組參數(shù)
1.在UserController類中添加delete2()請求處理方法。
@DeleteMapping("batch_delete2")
public void delete2(@RequestBody ArrayList<Integer> ids) {
for (Integer id : ids) {
System.out.println(id);
}
}2.使用ApiPost工具測試,在【Body】選項選項下發(fā)送JSON格式數(shù)據(jù)[1, 3, 5]給后臺。

3.創(chuàng)建param07.html頁面,通過Axios發(fā)送請求。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>前后端參數(shù)傳遞</title>
<script src="https://unpkg.com/vue@next"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const app = {
data() {
return {
ids: [1, 3, 5]
}
},
mounted() {
axios.post('http://localhost:8888/users/batch_delete2', this.ids)
.then(response => {
console.log('success', response.data);
})
.catch(error => {
console.log('fail', error.data);
});
}
}
Vue.createApp(app).mount('#app')
</script>
</body>
</html>2.單個實體接收參數(shù)
1.在UserController類中添加add6()請求處理方法。
@RequestMapping("add6")
public User add6(@RequestBody User user) {
System.out.println(user);
return user;
}2.使用ApiPost工具測試,需將提交的數(shù)據(jù)類型設置為application/json格式(GET和POST請求都支持)。
{
"id": 1,
"username": "tom",
"password": "123456"
}3.創(chuàng)建param08.html頁面,通過Axios發(fā)送請求。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>前后端參數(shù)傳遞</title>
<script src="https://unpkg.com/vue@next"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const app = {
data() {
return {
user: {
username: '袁庭新',
password: '123456'
}
}
},
mounted() {
axios.post('http://localhost:8888/users/add6', this.user)
.then(response => {
console.log('success', response.data);
})
.catch(error => {
console.log('fail', error.data);
});
}
}
Vue.createApp(app).mount('#app')
</script>
</body>
</html>3.實體嵌套實體接收參數(shù)
1.在pojo包下創(chuàng)建Cat實體類。
package com.cy.sb_receive_param.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Cat {
private Integer id;
private String breed;
private String name;
}2.在pojo包下的User實體類中聲明Cat類型的屬性。
package com.cy.sb_receive_param.pojo;
import lombok.Data;
import lombok.ToString;
@Data
@ToString
public class User {
private Integer id;
private String username;
private String password;
private Cat cat;
}3.在UserController類中添加add7()請求處理方法。
@RequestMapping("add7")
public User add7(@RequestBody User user) {
System.out.println(user);
return user;
}4.使用ApiPost工具測試,需將提交的數(shù)據(jù)類型設置為application/json格式(GET和POST請求都支持)。
{
"id": 1,
"username": "袁庭新",
"password": "123456",
"cat": {
"id": 1,
"breed": "藍白",
"name": "花花"
}
}5.創(chuàng)建param09.html頁面,通過Axios發(fā)送請求。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>前后端參數(shù)傳遞</title>
<script src="https://unpkg.com/vue@next"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const app = {
data() {
return {
user: {
id: 1,
username: '袁庭新',
password: '123456',
cat: {
id: 1,
breed: '藍白',
name: '花花'
}
}
}
},
mounted() {
axios.post('http://localhost:8888/users/add7', this.user)
.then(response => {
console.log('success', response.data);
})
.catch(error => {
console.log('fail', error.data);
});
}
}
Vue.createApp(app).mount('#app')
</script>
</body>
</html>4.實體嵌套List集合接收參數(shù)
1.在pojo包下創(chuàng)建Course實體類。
package com.cy.sb_receive_param.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Course {
private Integer id;
private String courseName;
private String lecturer;
}2.在pojo包下的User實體類中聲明List<Course>類型的屬性。
package com.cy.sb_receive_param.pojo;
import lombok.Data;
import lombok.ToString;
import java.util.List;
@Data
@ToString
public class User {
private Integer id;
private String username;
private String password;
private List<Course> courses;
}3.在UserController類中添加add8()請求處理方法。
@RequestMapping("add8")
public User add8(@RequestBody User user) {
System.out.println(user);
return user;
}4.使用ApiPost工具測試,需將提交的數(shù)據(jù)類型設置為application/json格式(GET和POST請求都支持)。
{
"id": 1,
"username": "tom",
"password": "123456",
"courses": [
{
"id": 1,
"courseName": "Java",
"lecturer": "袁庭新老師"
},
{
"id": 2,
"courseName": "Python",
"lecturer": "李小紅老師"
}
]
}5.創(chuàng)建param10.html頁面,通過Axios發(fā)送請求。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>前后端參數(shù)傳遞</title>
<script src="https://unpkg.com/vue@next"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const app = {
data() {
return {
user: {
id: 1,
username: 'tom',
password: '123456',
cat: {
id: 1,
breed: '藍白',
name: '花花'
},
courses: [
{
id: 1,
courseName: "Java",
lecturer: "袁庭新老師"
},
{
id: 2,
courseName: "Python",
lecturer: "張曉東老師"
}
]
}
}
},
mounted() {
axios.post('http://localhost:8888/users/add8', this.user)
.then(response => {
console.log('success', response.data);
})
.catch(error => {
console.log('fail', error.data);
});
}
}
Vue.createApp(app).mount('#app')
</script>
</body>
</html>5.Map集合接收參數(shù)
1.在UserController類中添加add9()請求處理方法。
@RequestMapping("add9")
public Map<String, Object> add9(@RequestBody Map<String, Object> map) {
String username = (String) map.get("username");
System.out.println("username : " + username);
Map<String, Object> catMap = (Map<String, Object>) map.get("cat");
Set<Map.Entry<String, Object>> catSet = catMap.entrySet();
for (Map.Entry<String, Object> entry : catSet) {
String key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + " : " + value);
}
List<Map<String, Object>> courseMapList = (List<Map<String, Object>>) map.get("courses");
for (Map<String, Object> courseMap : courseMapList) {
Set<Map.Entry<String, Object>> courseSet = courseMap.entrySet();
for (Map.Entry<String, Object> entry : courseSet) {
String key = entry.getKey();
Object value = entry.getValue();
System.out.println(key + " : " + value);
}
}
return map;
}2.使用ApiPost工具測試,需將提交的數(shù)據(jù)類型設置為application/json格式(GET和POST請求都支持)。
{
"id": 1,
"username": "tom",
"password": "123456",
"courses": [
{
"id": 1,
"courseName": "Java",
"lecturer": "袁庭新老師"
},
{
"id": 2,
"courseName": "Python",
"lecturer": "李小紅老師"
}
]
}3.創(chuàng)建param11.html頁面,通過Axios發(fā)送請求。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>前后端參數(shù)傳遞</title>
<script src="https://unpkg.com/vue@next"></script>
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
</head>
<body>
<div id="app">
</div>
<script>
const app = {
data() {
return {
user: {
id: 1,
username: 'tom',
password: '123456',
cat: {
id: 1,
breed: '藍白',
name: '花花'
},
courses: [
{
id: 1,
courseName: "Java",
lecturer: "袁庭新老師"
},
{
id: 2,
courseName: "Python",
lecturer: "張曉東老師"
}
]
}
}
},
mounted() {
axios.post('http://localhost:8888/users/add9', this.user)
.then(response => {
console.log('success', response.data);
})
.catch(error => {
console.log('fail', error.data);
});
}
}
Vue.createApp(app).mount('#app')
</script>
</body>
</html>3 總結
本文介紹了在Spring Boot項目中接收前端數(shù)據(jù)的多種方式。通過創(chuàng)建Spring Boot項目、配置Web依賴和跨域問題,展示了如何使用@RequestParam、@PathVariable、@RequestBody等注解接收不同類型的參數(shù),包括基本類型、數(shù)組、復雜對象及嵌套結構。通過實例演示了如何在Controller中處理GET、POST等請求,并通過前端頁面發(fā)送請求驗證后端接收邏輯。
以上就是SpringBoot項目接收前端參數(shù)的11種方式的詳細內容,更多關于SpringBoot接收前端參數(shù)的資料請關注腳本之家其它相關文章!
相關文章
基于struts2和hibernate實現(xiàn)登錄和注冊功能
這篇文章主要為大家詳細介紹了基于struts2和hibernate實現(xiàn)登錄和注冊功能,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-10-10
SpringBoot利用Junit動態(tài)代理實現(xiàn)Mock方法
說到Spring Boot 單元測試主要有兩個主流集成分別是Mockito,Junit,這個各有特點,在實際開發(fā)中,我想要的測試框架應該是這個框架集成者,本文給大家介紹了SpringBoot利用Junit動態(tài)代理實現(xiàn)Mock方法,需要的朋友可以參考下2024-04-04
使用Maven創(chuàng)建和管理多模塊項目的詳細步驟
使用Maven進行多模塊項目管理是一種常見的做法,它可以幫助你組織大型項目,使其結構更加清晰,便于維護和構建,以下是使用Maven創(chuàng)建和管理多模塊項目的詳細步驟,需要的朋友可以參考下2024-10-10

