spring boot前后端傳參的實(shí)現(xiàn)
獲取傳參
@PathVariable注解主要用來獲取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"; }
對于多個(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 請求,接收前端表單提交的參數(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。而是通過封裝實(shí)體類來接收參數(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 注解用于接收前端傳來的實(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è)資源都對應(yīng)一個(gè)特定的 URI(統(tǒng)一資源定位符),并用它進(jìn)行標(biāo)示,訪問這個(gè) URI 就可以獲得這個(gè)資源。
spring boot的注解很好的支持了restful格式
- @GetMapping,處理 Get 請求
- @PostMapping,處理 Post 請求
- @PutMapping,用于更新資源
- @DeleteMapping,處理刪除請求
- @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";
}
}
對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;
}
}
就會自動把null值轉(zhuǎn)換為空值""
包裝統(tǒng)一的JSON返回結(jié)構(gòu)
在后臺返回的接口數(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;
/**
* 若沒有數(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);
}
訪問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è)置配置類來保存配置
配置信息如下:
url.orderUrl=http://localhost:8002 url.userUrl=http://localhost:8003 url.shoppingUrl=http://localhost:8004
新建一個(gè)配置類,來保存配置
@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();
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
springboot集成Swagger的方法(讓你擁有屬于自己的api管理器)
在大型的項(xiàng)目中,如果你有非常多的接口需要統(tǒng)一管理,或者需要進(jìn)行接口測試,那么我們通常會在繁雜地api中找到需要進(jìn)行測試或者管理的接口,接下來通過本文給大家介紹springboot集成Swagger的方法讓你擁有屬于自己的api管理器,感興趣的朋友一起看看吧2021-11-11
Java基于正則表達(dá)式實(shí)現(xiàn)的替換匹配文本功能【經(jīng)典實(shí)例】
這篇文章主要介紹了Java基于正則表達(dá)式實(shí)現(xiàn)的替換匹配文本功能,結(jié)合完整實(shí)例形式分析了java字符串正則替換操作技巧,需要的朋友可以參考下2017-04-04
JavaWeb實(shí)現(xiàn)文件上傳下載功能實(shí)例解析
這篇文章主要為大家詳細(xì)介紹了JavaWeb中的文件上傳和下載功能的實(shí)現(xiàn),在Web應(yīng)用系統(tǒng)開發(fā)中,文件上傳和下載功能是非常常用的功能,需要的朋友可以參考下2015-08-08
Maven項(xiàng)目外部jar包導(dǎo)入的實(shí)現(xiàn)示例
在Maven項(xiàng)目里,我們經(jīng)常需要導(dǎo)入jar包依賴,本文主要介紹了Maven項(xiàng)目外部jar包導(dǎo)入的實(shí)現(xiàn)示例,具有一定的參考價(jià)值,感興趣的可以了解一下2024-08-08
mybatis-plus 如何判斷參數(shù)是否為空并作為查詢條件
這篇文章主要介紹了mybatis-plus 如何判斷參數(shù)是否為空并作為查詢條件,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2022-03-03
Java Socket通信(一)之客戶端程序 發(fā)送和接收數(shù)據(jù)
對于Socket通信簡述,服務(wù)端往Socket的輸出流里面寫東西,客戶端就可以通過Socket的輸入流讀取對應(yīng)的內(nèi)容,Socket與Socket之間是雙向連通的,所以客戶端也可以往對應(yīng)的Socket輸出流里面寫東西,然后服務(wù)端對應(yīng)的Socket的輸入流就可以讀出對應(yīng)的內(nèi)容2016-03-03

