今天就跟大家聊聊有關使用spring boot怎么實現前后端傳參,可能很多人都不太了解,為了讓大家更加了解,小編給大家總結了以下內容,希望大家根據這篇文章可以有所收獲。
獲取傳參
@PathVariable注解主要用來獲取URL參數。即這種風格的 URL:http://localhost:8080/user/{id}
@GetMapping("/user/{id}")
public String testPathVariable(@PathVariable Integer id) { System.out.println("獲取到的id為:" + id);
return "success"; }對于多個參數的獲取
@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 里獲取參數值,即這種風格的 URL:http://localhost:8080/user?id=1。除此之外,該注解還可以用于 POST 請求,接收前端表單提交的參數
@RequestMapping("/user")
public String testRequestParam(@RequestParam(value = "idd", required = false) Integer id) {
System.out.println("獲取到的id為:" + id);
return "success"; }當參數較多時,可以不用@RequestParam。而是通過封裝實體類來接收參數。
public class User {
private String username;
private String password;
//添加setter和getter }使用實體接收的話,我們不必在前面加 @RequestParam 注解,直接使用即可。
@PostMapping("/form2")
public String testForm(User user) {
System.out.println("獲取到的username為:" + user.getUsername());
System.out.println("獲取到的password為:" + user.getPassword());
return "success";
}上面的是表單實體提交。當JSON格式提交時,需要用@RequestBody。
@RequestBody 注解用于接收前端傳來的實體。接收參數為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"; }傳輸時需要傳JSON格式的參數。
Restful格式
前后端傳參一般使用Restful規范
RESTful 架構一個核心概念是“資源”(Resource)。從 RESTful 的角度看,網絡里的任何東西都是資源,可以是一段文本、一張圖片、一首歌曲、一種服務等,每個資源都對應一個特定的 URI(統一資源定位符),并用它進行標示,訪問這個 URI 就可以獲得這個資源。
spring boot的注解很好的支持了restful格式
@GetMapping,處理 Get 請求
@PostMapping,處理 Post 請求
@PutMapping,用于更新資源
@DeleteMapping,處理刪除請求
@PatchMapping,用于更新部分資源
@RestController注解可將返回的數據結果轉換成json格式,在sprinboot中默認使用的JSON解析技術框架是Jackson。
基本示例
@RestController
@RequestMapping("/")
public class Hello {
@GetMapping(value = "hello")
public String hello(){
return "hello world";
}
}對null的處理
在項目中,遇到null值時,希望把null都轉成""。需要設置一個配置
@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值轉換為空值""
包裝統一的JSON返回結構
在后臺返回的接口數據中,一般要求結構是統一的,包括有狀態碼、返回信息。所以可以用泛型封裝一個統一的JSON返回結構
public class JsonResult<T> {
private T data;
private String code;
private String msg;
/**
* 若沒有數據返回,默認狀態碼為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、設置配置類來保存配置
配置信息如下:
url.orderUrl=http://localhost:8002 url.userUrl=http://localhost:8003 url.shoppingUrl=http://localhost:8004
新建一個配置類,來保存配置
@Component
@ConfigurationProperties(prefix = "url")
public class MicroServiceUrl {
private String orderUrl;
private String userUrl;
private String shoppingUrl;
// 省去 get 和 set 方法
}@Component 注解是把該類作為組件放在spring容器中,使用時直接注入即可。
@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();
}看完上述內容,你們對使用spring boot怎么實現前后端傳參有進一步的了解嗎?如果還想了解更多知識或者相關內容,請關注億速云行業資訊頻道,感謝大家的支持。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。