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(); }
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。