SpringBoot項(xiàng)目接收前端參數(shù)的11種方式
1 搭建項(xiàng)目
1.通過(guò)Spring Initializr選項(xiàng)創(chuàng)建一個(gè)項(xiàng)目名稱為【sb_receive_param】的SpringBoot項(xiàng)目。
2.給項(xiàng)目添加Spring Web依賴。
3.在com.cy.sb_receive_param.pojo包下創(chuàng)建User實(shí)體類。
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àng)目中的跨域問題。通過(guò)實(shí)現(xiàn)WebMvcConfigurer接口,并重寫addCorsMappings(CorsRegistry registry)方法來(lái)實(shí)現(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("/**"):配置可以被跨域的路徑,可以任意配置,可以具體到直接請(qǐng)求路徑 * allowedOrigins("*"):允許所有的請(qǐng)求域名訪問我們的跨域資源,可以固定單條或者多條內(nèi)容,如"http://www.yx.com",只有該域名可以訪問我們的跨域資源 * allowedHeaders("*"):允許所有的請(qǐng)求header訪問,可以自定義設(shè)置任意請(qǐng)求頭信息 * allowedMethods():允許所有的請(qǐng)求方法訪問該跨域資源服務(wù)器,如GET、POST、DELETE、PUT、OPTIONS、HEAD等 * maxAge(3600):配置客戶端可以緩存pre-flight請(qǐng)求的響應(yīng)的時(shí)間(秒)。默認(rèn)設(shè)置為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后臺(tái)控制層獲取參數(shù),它有三個(gè)常用參數(shù)。
參數(shù)名 | 描述 |
defaultValue | 表示設(shè)置默認(rèn)值 |
required | 表示該參數(shù)是否必傳 |
value | 值表示接收傳入的參數(shù)的key |
@PathVariable用于將請(qǐng)求URL中的模板變量映射到功能處理方法的參數(shù)上,即取出URL模板中的變量作為參數(shù)。
2.1.2 案例演示
1.方式一
1.在UserController類中添加add1()請(qǐng)求處理方法。前端請(qǐng)求參數(shù)的key需和后端控制層處理請(qǐng)求的方法參數(shù)名稱一致。
@RequestMapping("add1") public void add1(String username, String password) { System.out.println("username=" + username + ", password=" + password); }
2.使用ApiPost工具測(cè)試(GET和POST請(qǐng)求都支持)。
localhost:8080/users/add1?username=tom&password=123456
3.創(chuàng)建param01.html頁(yè)面,通過(guò)Axios發(fā)送請(qǐng)求。
<!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()請(qǐng)求處理方法。如果前端請(qǐng)求參數(shù)的key與后端控制層處理請(qǐng)求的方法參數(shù)名稱不一致,使用@RequestParam注解來(lái)解決。
@RequestMapping("add2") public void add2(@RequestParam("name") String username, @RequestParam("pwd") String password) { System.out.println("username=" + username + ", password=" + password); }
2.使用ApiPost工具測(cè)試(GET和POST請(qǐng)求都支持)。
localhost:8080/users/add2?name=tom&pwd=123456
3.創(chuàng)建param02.html頁(yè)面,通過(guò)Axios發(fā)送請(qǐng)求。
<!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()請(qǐng)求處理方法。
@DeleteMapping("batch_delete1") public void delete1(@RequestParam(name = "ids") List<Integer> ids) { for (Integer id : ids) { System.out.println(id); } }
2.使用ApiPost工具測(cè)試,在【Query】選項(xiàng)下添加ids參數(shù),參數(shù)值設(shè)置為1,3,5
。
3.使用ApiPost工具測(cè)試,在【Query】選項(xiàng)下添加ids參數(shù),將參數(shù)的值單獨(dú)一個(gè)個(gè)進(jìn)行添加。
4.創(chuàng)建param03.html頁(yè)面,通過(guò)Axios發(fā)送請(qǐng)求。
<!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()請(qǐng)求處理方法。前端請(qǐng)求參數(shù)的key需和后端控制層處理請(qǐng)求方法的參數(shù)pojo實(shí)體類的屬性名稱一致。
@RequestMapping("add3") public void add3(User user) { System.out.println(user); }
2.使用ApiPost工具測(cè)試(GET和POST請(qǐng)求都支持)。
localhost:8080/users/add3?id=1&username=tom&password=123
3.創(chuàng)建param04.html頁(yè)面,通過(guò)Axios發(fā)送請(qǐng)求。
<!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()請(qǐng)求處理方法。使用@PathVariable注解將請(qǐng)求URL中的模板變量映射到功能處理方法的參數(shù)上,如果模板變量名稱和方法的參數(shù)名稱不同需要在@PathVariable注解上顯示的指定映射關(guān)系。
@RequestMapping("add4/{username}/{pwd}") public void add4(@PathVariable String username, @PathVariable("pwd") String password) { System.out.println("username=" + username + ", password=" + password); }
2.使用ApiPost工具測(cè)試(GET和POST請(qǐng)求都支持)。
localhost:8080/users/add4/tom/123456
3.創(chuàng)建param05.html頁(yè)面,通過(guò)Axios發(fā)送請(qǐng)求。
<!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()請(qǐng)求處理方法。通過(guò)HttpServletRequest對(duì)象獲取數(shù)據(jù),前端請(qǐng)求參數(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工具測(cè)試(GET和POST請(qǐng)求都支持)。
localhost:8080/users/add5?username=tom&password=123
3.創(chuàng)建param06.html頁(yè)面,通過(guò)Axios發(fā)送請(qǐng)求。
<!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該注解會(huì)把接收到的參數(shù)轉(zhuǎn)為JSON格式。如果前端通過(guò)application/json類型提交JSON格式的數(shù)據(jù)給后端控制層處理請(qǐng)求的方法,方法的參數(shù)必須使用@RequestBody注解進(jìn)行修飾,才能接收來(lái)自前端提交的JSON數(shù)據(jù)。
2.2.2 案例演示
1.接收前端傳數(shù)組參數(shù)
1.在UserController類中添加delete2()請(qǐng)求處理方法。
@DeleteMapping("batch_delete2") public void delete2(@RequestBody ArrayList<Integer> ids) { for (Integer id : ids) { System.out.println(id); } }
2.使用ApiPost工具測(cè)試,在【Body】選項(xiàng)選項(xiàng)下發(fā)送JSON格式數(shù)據(jù)[1, 3, 5]給后臺(tái)。
3.創(chuàng)建param07.html頁(yè)面,通過(guò)Axios發(fā)送請(qǐng)求。
<!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.單個(gè)實(shí)體接收參數(shù)
1.在UserController類中添加add6()請(qǐng)求處理方法。
@RequestMapping("add6") public User add6(@RequestBody User user) { System.out.println(user); return user; }
2.使用ApiPost工具測(cè)試,需將提交的數(shù)據(jù)類型設(shè)置為application/json格式(GET和POST請(qǐng)求都支持)。
{ "id": 1, "username": "tom", "password": "123456" }
3.創(chuàng)建param08.html頁(yè)面,通過(guò)Axios發(fā)送請(qǐng)求。
<!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í)體嵌套實(shí)體接收參數(shù)
1.在pojo包下創(chuàng)建Cat實(shí)體類。
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實(shí)體類中聲明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()請(qǐng)求處理方法。
@RequestMapping("add7") public User add7(@RequestBody User user) { System.out.println(user); return user; }
4.使用ApiPost工具測(cè)試,需將提交的數(shù)據(jù)類型設(shè)置為application/json格式(GET和POST請(qǐng)求都支持)。
{ "id": 1, "username": "袁庭新", "password": "123456", "cat": { "id": 1, "breed": "藍(lán)白", "name": "花花" } }
5.創(chuàng)建param09.html頁(yè)面,通過(guò)Axios發(fā)送請(qǐng)求。
<!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: '藍(lán)白', 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.實(shí)體嵌套List集合接收參數(shù)
1.在pojo包下創(chuàng)建Course實(shí)體類。
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實(shí)體類中聲明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()請(qǐng)求處理方法。
@RequestMapping("add8") public User add8(@RequestBody User user) { System.out.println(user); return user; }
4.使用ApiPost工具測(cè)試,需將提交的數(shù)據(jù)類型設(shè)置為application/json格式(GET和POST請(qǐng)求都支持)。
{ "id": 1, "username": "tom", "password": "123456", "courses": [ { "id": 1, "courseName": "Java", "lecturer": "袁庭新老師" }, { "id": 2, "courseName": "Python", "lecturer": "李小紅老師" } ] }
5.創(chuàng)建param10.html頁(yè)面,通過(guò)Axios發(fā)送請(qǐng)求。
<!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: '藍(lán)白', 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()請(qǐng)求處理方法。
@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工具測(cè)試,需將提交的數(shù)據(jù)類型設(shè)置為application/json格式(GET和POST請(qǐng)求都支持)。
{ "id": 1, "username": "tom", "password": "123456", "courses": [ { "id": 1, "courseName": "Java", "lecturer": "袁庭新老師" }, { "id": 2, "courseName": "Python", "lecturer": "李小紅老師" } ] }
3.創(chuàng)建param11.html頁(yè)面,通過(guò)Axios發(fā)送請(qǐng)求。
<!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: '藍(lán)白', 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 總結(jié)
本文介紹了在Spring Boot項(xiàng)目中接收前端數(shù)據(jù)的多種方式。通過(guò)創(chuàng)建Spring Boot項(xiàng)目、配置Web依賴和跨域問題,展示了如何使用@RequestParam、@PathVariable、@RequestBody等注解接收不同類型的參數(shù),包括基本類型、數(shù)組、復(fù)雜對(duì)象及嵌套結(jié)構(gòu)。通過(guò)實(shí)例演示了如何在Controller中處理GET、POST等請(qǐng)求,并通過(guò)前端頁(yè)面發(fā)送請(qǐng)求驗(yàn)證后端接收邏輯。
以上就是SpringBoot項(xiàng)目接收前端參數(shù)的11種方式的詳細(xì)內(nèi)容,更多關(guān)于SpringBoot接收前端參數(shù)的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
Eclipse手動(dòng)導(dǎo)入DTD文件實(shí)現(xiàn)方法解析
這篇文章主要介紹了Eclipse手動(dòng)導(dǎo)入DTD文件實(shí)現(xiàn)方法解析,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-10-10基于struts2和hibernate實(shí)現(xiàn)登錄和注冊(cè)功能
這篇文章主要為大家詳細(xì)介紹了基于struts2和hibernate實(shí)現(xiàn)登錄和注冊(cè)功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-10-10SpringBoot利用Junit動(dòng)態(tài)代理實(shí)現(xiàn)Mock方法
說(shuō)到Spring Boot 單元測(cè)試主要有兩個(gè)主流集成分別是Mockito,Junit,這個(gè)各有特點(diǎn),在實(shí)際開發(fā)中,我想要的測(cè)試框架應(yīng)該是這個(gè)框架集成者,本文給大家介紹了SpringBoot利用Junit動(dòng)態(tài)代理實(shí)現(xiàn)Mock方法,需要的朋友可以參考下2024-04-04使用Maven創(chuàng)建和管理多模塊項(xiàng)目的詳細(xì)步驟
使用Maven進(jìn)行多模塊項(xiàng)目管理是一種常見的做法,它可以幫助你組織大型項(xiàng)目,使其結(jié)構(gòu)更加清晰,便于維護(hù)和構(gòu)建,以下是使用Maven創(chuàng)建和管理多模塊項(xiàng)目的詳細(xì)步驟,需要的朋友可以參考下2024-10-10Java線程之join_動(dòng)力節(jié)點(diǎn)Java學(xué)院整理
join() 定義在Thread.java中,下文通過(guò)源碼分享join(),需要的朋友參考下吧2017-05-05mybatis update set 多個(gè)字段實(shí)例
這篇文章主要介紹了mybatis update set 多個(gè)字段實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2021-01-01