1.Spring MVC中,處理的比較多的幾種 HTTP請求信息格式(Content-Type)
- application/x-www-form-urlencoded(默認)
- multipart/form-data (form表單里面有文件上傳時,必須要指定enctype屬性值為multipart/form-data,意思是以二進制流的形式傳輸文件)
- application/json、application/xml等格式的數據
HTTP請求中,request的body部分的數據編碼格式由header部分的Content-Type指定
2.Spring MVC 用來處理請求參數的注解
Spring MVC 提供了多個注解來獲取HTTP請求中的提交的數據內容,具體用哪個注解是根據請求的編碼方式(request header content-type 值)來決定的。
@PathVariable
@PathVariable 用來獲取請求url中的參數
@RequestParam
@RequestParam接收的數據是來自HTTP請求體 或 即請求頭requestHeader中(也就是在url中,格式為xxx?)的QueryString中
@RequestParam 用來處理 請求體(RequestBody)中 以application/x-www-form-urlencoded 或者 multipart/form-data編碼方式提交的 數據
RequestParam可以接受簡單類型的屬性,也可以接受對象類型
RequestParam實質是將Request.getParameter() 中的Key-Value參數Map 利用Spring的轉化機制ConversionService配置,轉化成參數接收對象或字段。get方式中query String的值,和post方式中body data的值都會被Servlet接受到並轉化到Request.getParameter()參數集中,所以@RequestParam可以獲取的到
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/person") public class PersonController { Logger logger = LoggerFactory.getLogger(PersonController.class); @PostMapping("/list") public String findList(@RequestParam String firstName, @RequestParam String lastName) { logger.info("wow, firstName is : " + firstName); logger.info("wow, lastName is : " + lastName); return "ok"; } }
請求參數放在請求體中,並且請求體的編碼方式是application/x-www-form-urlencoded

請求參數放在請求頭中
請求參數放在請求頭中,如果是打開F12看到的是如下信息


@RequestBody
@RequestBody接收的參數是來自RequestBody中,即HTTP請求體。所以Get請求不能用@RequestBody注解。
@RequestBody 用來處理 請求體(RequestBody)中 以application/json、application/xml等格式提交的數據
import lombok.Data; @Data public class PersonRequest { private Long id; private String firstName; private String lastName; private Integer age; private String phone; private String address; }
import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import com.alibaba.fastjson.JSON; @RestController @RequestMapping("/api/person") public class PersonController { Logger logger = LoggerFactory.getLogger(PersonController.class); @PostMapping("/list") public void findList(@RequestBody PersonRequest request) { logger.info("request is : " + JSON.toJSONString(request)); } }
POST測試如下

打開F12測試,會看到如下


@ModelAttribute
@ModelAttribute 注解類型將參數綁定到Model對象
3.Spring MVC 控制器方法的兩種返回值
Spring MVC 在使用 @RequestMapping 后,返回值通常解析為跳轉路徑,
但是加上 @ResponseBody 后返回結果不會被解析為跳轉路徑,會直接返回 json 數據,寫入 HTTP response body 中。 比如異步獲取 json 數據。
@RequestBody @RequestParam 用混的話會報錯:MissingServletRequestParameterException: Required String parameter 'xxx' is not present
