新建一個項目,具體步驟可參照上文:SpringBoot系列(二) https://blog.csdn.net/mu_wind/article/details/94294138#_189
項目依賴
pom.xml 中添加依賴(添加此依賴並安裝插件後,在實體類中使用@data註解,可以省略set和get方法):
<!--Web 依賴-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<!--省略set、get方法-->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
項目結構
1、啓動類:
@SpringBootApplication
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
2、實體類 Student:
package com.example.demo.model;
import lombok.Data;
@Data
public class Student {
private String name;
private int age;
private int score;
}
3、接口類 StudentController:
package com.example.demo.controller;
@RestController
public class StudentController {
@RequestMapping(name="/getStudent", method= RequestMethod.POST)
public User getStudent() {
Student student = new Student();
student.setName("小紅");
student.setAge(12);
student .setScore(560);
return user;
}
}
@RestController 註解相當於 @ResponseBody + @Controller 合在一起的作用,如果 Web 層的類上使用了 @RestController 註解,就代表這個類中所有的方法都會以 JSON 的形式返回結果,也相當於 JSON 的一種快捷使用方式;
@RequestMapping(name="/getStudent", method= RequestMethod.POST),以 /getStudent 的方式去請求,method= RequestMethod.POST 是指只可以使用 Post 的方式去請求,如果使用 Get 的方式去請求的話,則會報 405 不允許訪問的錯誤。
4、測試類:
在 test 包下新建 ControllerTest 測試類,對 getUser() 方法使用MockMvc進行測試。
package com.example.demo;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void getStudent() throws Exception{
String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/getStudent"))
.andReturn().getResponse().getContentAsString();
System.out.println("result : "+responseString);
}
}
運行Test,得到結果:
result : {"name":"小紅","age":12,"score":650}
說明 Spring Boot 自動將 Student對象轉成了 JSON 進行返回。那麼如果返回的是一個 list 呢?
@RequestMapping("/getStudents")
public List<Student> getStudents() {
List<Student> students = new ArrayList<>();
Student student1 = new Student();
student1.setName("王小宏");
student1.setAge(31);
student1.setScore(635);
students.add(student1);
Student student2 = new Student();
student2.setName("宋小專");
student2.setAge(27);
student2.setScore(522);
students.add(student2);
return students;
}
添加測試方法:
@Test
public void getStudents() throws Exception{
String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/getStudents"))
.andReturn().getResponse().getContentAsString();
System.out.println("result : "+responseString);
}
運行測試結果,得到結果:
result : [{"name":"王小宏","age":31,"score":635},{"name":"宋小專","age":27,"score":522}]
請求傳參
前端瀏覽器和後端服務器正是依賴交互過程中的參數完成了諸多用戶操作行爲,因此參數的傳遞和接收是一個 Web 系統最基礎的功能。SpringBoot對參數接收做了很好的支持,內置了很多種參數接收方式,提供一些註解來幫助限制請求的類型、接收不同格式的參數等。
Get與Post:
如果我們希望一個接口以Post方式訪問,在方法上添加一個配置(method= RequestMethod.POST)即可:
@RequestMapping(name="/getStudent", method= RequestMethod.POST)
public User getStudent() {
...
}
如果以Get方法請求該接口,將得到【Request method ‘GET’ not supported】的報錯。
同樣,如果是GET 請求,method 設置爲:method= RequestMethod.GET;如果不進行設置默認兩種方式的請求都支持。
請求傳參一般分爲 URL 地址傳參和表單傳參兩種方式,都以鍵值對的方式將參數傳遞到後端。作爲後端程序不用關注前端採用的那種方式,只需要根據參數的鍵來獲取值。
通過 URL 傳參
只要後端處理請求的方法中存在參數鍵相同名稱的屬性,在請求的過程中 Spring 會自動將參數值賦值到屬性中,最後在方法中直接使用即可。
@RequestMapping(name = "/test", method = RequestMethod.GET)
public String test(String name) {
return name;
}
測試:
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ControllerTest {
@Autowired
private MockMvc mockMvc;
@Test
public void getStudents() throws Exception {
String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/test?name=xiaohong"))
.andReturn().getResponse().getContentAsString();
System.out.println("result : " + responseString);
}
}
結果:
result : xiaohong
另一種方式:
@RequestMapping(value="test/{name}", method=RequestMethod.GET)
public String get(@PathVariable String name) {
return name;
}
這樣的寫法,傳參地址欄會更加美觀一些。
測試:
@Test
public void getStudents() throws Exception {
String responseString = mockMvc.perform(MockMvcRequestBuilders.get("/test/xiaohong"))
.andReturn().getResponse().getContentAsString();
System.out.println("result : " + responseString);
}
結果同上例。
表單傳參
通過表單傳參一般適用於Post請求。例如下面這個接口,只要前端請求帶入name和age兩個參數,就能被解析到。
@RequestMapping(value = "/test", method = RequestMethod.POST)
public String get(String name, String age) {
return "姓名:" + name + ",年齡:" + age;
}
使用Jmeter發送一個接口請求:
結果:
姓名:小宏,年齡:31
實體傳參
有時候前端直接提交一個form表單,傳入後端的參數就是JSON格式的,這種參數後端如何接收和處理呢,下面進行示範:
首先,在pom.xml中引入fastjson依賴
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.47</version>
</dependency>
後端接口:
測試:
Jmeter中發送一個接口請求:
結果同上例。