spring boot前后端傳參的實(shí)現(xiàn)
獲取傳參
@PathVariable注解主要用來(lái)獲取URL參數(shù)。即這種風(fēng)格的 URL:http://localhost:8080/user/{id}
@GetMapping("/user/{id}") public String testPathVariable(@PathVariable Integer id) { System.out.println("獲取到的id為:" + id); return "success"; }
對(duì)于多個(gè)參數(shù)的獲取
@GetMapping("/user/{idd}/{name}") public String testPathVariable(@PathVariable(value = "idd") Integer id, @PathVariable String name) { System.out.println("獲取到的id為:" + id); System.out.println("獲取到的name為:" + name); return "success"; }
@RequestParam:是從 Request 里獲取參數(shù)值,即這種風(fēng)格的 URL:http://localhost:8080/user?id=1。除此之外,該注解還可以用于 POST 請(qǐng)求,接收前端表單提交的參數(shù)
@RequestMapping("/user") public String testRequestParam(@RequestParam(value = "idd", required = false) Integer id) { System.out.println("獲取到的id為:" + id); return "success"; }
當(dāng)參數(shù)較多時(shí),可以不用@RequestParam。而是通過(guò)封裝實(shí)體類來(lái)接收參數(shù)。
public class User { private String username; private String password; //添加setter和getter }
使用實(shí)體接收的話,我們不必在前面加 @RequestParam 注解,直接使用即可。
@PostMapping("/form2") public String testForm(User user) { System.out.println("獲取到的username為:" + user.getUsername()); System.out.println("獲取到的password為:" + user.getPassword()); return "success"; }
上面的是表單實(shí)體提交。當(dāng)JSON格式提交時(shí),需要用@RequestBody。
@RequestBody 注解用于接收前端傳來(lái)的實(shí)體。接收參數(shù)為JSON格式的傳遞。
public class User { private String username; private String password; // set get } @PostMapping("/user") public String testRequestBody(@RequestBody User user) { System.out.println("獲取到的username為:" + user.getUsername()); System.out.println("獲取到的password為:" + user.getPassword()); return "success"; }
傳輸時(shí)需要傳JSON格式的參數(shù)。
Restful格式
前后端傳參一般使用Restful規(guī)范
RESTful 架構(gòu)一個(gè)核心概念是“資源”(Resource)。從 RESTful 的角度看,網(wǎng)絡(luò)里的任何東西都是資源,可以是一段文本、一張圖片、一首歌曲、一種服務(wù)等,每個(gè)資源都對(duì)應(yīng)一個(gè)特定的 URI(統(tǒng)一資源定位符),并用它進(jìn)行標(biāo)示,訪問(wèn)這個(gè) URI 就可以獲得這個(gè)資源。
spring boot的注解很好的支持了restful格式
- @GetMapping,處理 Get 請(qǐng)求
- @PostMapping,處理 Post 請(qǐng)求
- @PutMapping,用于更新資源
- @DeleteMapping,處理刪除請(qǐng)求
- @PatchMapping,用于更新部分資源
@RestController注解可將返回的數(shù)據(jù)結(jié)果轉(zhuǎn)換成json格式,在sprinboot中默認(rèn)使用的JSON解析技術(shù)框架是Jackson。
基本示例
@RestController @RequestMapping("/") public class Hello { @GetMapping(value = "hello") public String hello(){ return "hello world"; } }
對(duì)null的處理
在項(xiàng)目中,遇到null值時(shí),希望把null都轉(zhuǎn)成""。需要設(shè)置一個(gè)配置
@Configuration public class Jackson { @Bean @Primary @ConditionalOnMissingBean(ObjectMapper.class) public ObjectMapper jacksonObjectMapper(Jackson2ObjectMapperBuilder builder) { ObjectMapper objectMapper = builder.createXmlMapper(false).build(); objectMapper.getSerializerProvider().setNullValueSerializer(new JsonSerializer<Object>() { @Override public void serialize(Object o, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException { jsonGenerator.writeString(""); } }); return objectMapper; } }
就會(huì)自動(dòng)把null值轉(zhuǎn)換為空值""
包裝統(tǒng)一的JSON返回結(jié)構(gòu)
在后臺(tái)返回的接口數(shù)據(jù)中,一般要求結(jié)構(gòu)是統(tǒng)一的,包括有狀態(tài)碼、返回信息。所以可以用泛型封裝一個(gè)統(tǒng)一的JSON返回結(jié)構(gòu)
public class JsonResult<T> { private T data; private String code; private String msg; /** * 若沒(méi)有數(shù)據(jù)返回,默認(rèn)狀態(tài)碼為0 */ public JsonResult(T data){ this.data = data; this.code = "10200"; this.msg = "操作成功"; } //省略getter和setter
修改controller中的代碼
@RequestMapping("/list") public JsonResult<List> getStudentList(){ List<Student> list = new ArrayList<>(); Student stu1 = new Student(2,"22",null); Student stu2 = new Student(3,"33",null); list.add(stu1); list.add(stu2); return new JsonResult<>(list); }
訪問(wèn)url,返回的格式將是:
{"data": [{"id":2,"username":"22","password":""}, {"id":3,"username":"33","password":""}], "code":"10200", "msg":"操作成功"}
取配置文件中的值
1、取配置文件中的配置
author.name=zhangsan
可以使用@Value注解即可獲取配置文件中的配置信息
@Value("${author.name}") private String userName;
2、設(shè)置配置類來(lái)保存配置
配置信息如下:
url.orderUrl=http://localhost:8002 url.userUrl=http://localhost:8003 url.shoppingUrl=http://localhost:8004
新建一個(gè)配置類,來(lái)保存配置
@Component @ConfigurationProperties(prefix = "url") public class MicroServiceUrl { private String orderUrl; private String userUrl; private String shoppingUrl; // 省去 get 和 set 方法 }
@Component 注解是把該類作為組件放在spring容器中,使用時(shí)直接注入即可。
@ConfigurationProperties注解就是指明該類中的屬性名就是配置中去掉前綴后的名字
使用ConfigurationProperties需要加依賴
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-configuration-processor</artifactId> <optional>true</optional> </dependency>
使用Resource注解就可以將添加配置類MicroServiceUrl引入到controller中使用了
@Resource private MicroServiceUrl microServiceUrl; @GetMapping(value = "getResource") public String getR(){ return microServiceUrl.getUserUrl(); }
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
java arrayList遍歷的四種方法及Java中ArrayList類的用法
arraylist是動(dòng)態(tài)數(shù)組,它具有三個(gè)好處分別是:動(dòng)態(tài)的增加和減少元素 、實(shí)現(xiàn)了ICollection和IList接口、靈活的設(shè)置數(shù)組的大小,本文給大家介紹java arraylist遍歷及Java arraylist 用法,感興趣的朋友一起學(xué)習(xí)吧2015-11-11詳解Struts2中json 相互引用死循環(huán)解決辦法
本篇文章主要介紹詳解Struts2中json 相互引用死循環(huán)解決辦法,具有一定的參考價(jià)值,有興趣的可以了解一下。2017-01-01idea中springboot項(xiàng)目連接數(shù)據(jù)庫(kù)報(bào)錯(cuò)的原因解析
這篇文章主要介紹了idea中springboot項(xiàng)目連接數(shù)據(jù)庫(kù)報(bào)錯(cuò)的原因解析,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2020-12-12springboot讀取文件,打成jar包后訪問(wèn)不到的解決
這篇文章主要介紹了springboot讀取文件,打成jar包后訪問(wèn)不到的解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-07-07Spring?Lifecycle?和?SmartLifecycle區(qū)別面試精講
這篇文章主要為大家介紹了Spring?Lifecycle和SmartLifecycle的區(qū)別面試精講,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-10-10Java生成Echarts表圖的2種實(shí)現(xiàn)方案
這篇文章主要給大家介紹了關(guān)于Java生成Echarts表圖的2種實(shí)現(xiàn)方案,ECharts是一款功能非常強(qiáng)大的JavaScript圖表庫(kù),文中通過(guò)代碼實(shí)例介紹的非常詳細(xì),需要的朋友可以參考下2023-09-09