1. 程式人生 > >MVC get,post接收引數的幾種方式

MVC get,post接收引數的幾種方式

註釋上都寫得很清楚哦

/**
* Description: MVC get,post接收引數的幾種方式
* 配合postman模擬請求來測試
*/
@RestController
@RequestMapping("/mvc")
public class MvcPostAndGet {
private static final Logger LOGGER = LoggerFactory.getLogger(MvcPostAndGet.class);

/**
* localhost:2000/mvc/get1?name=小明
* 直接在方法體寫 ?後的引數
*/
@GetMapping("/get1")
public void getParamByGET1(String name) {
LOGGER.info(
"get1接收到的引數:{}", name);
}

/**
* 使用HttpServletRequest獲取引數
* localhost:2000/mvc/get2?name=小明
* @param request
*/
@GetMapping("/get2")
public void getParamByGET2(HttpServletRequest request) {
String name = request.getParameter("name");
LOGGER.info("get2接收到的引數:{}", name);
}

/**
* localhost:2000/mvc/get3?name=小明
* 使用@requestParam註解獲取引數
*/
@GetMapping("/get3")
public void getParamByGET3(@RequestParam String name) {
LOGGER.info(
"get3接收到的引數:{}", name);
}

/**
* localhost:2000/mvc/get4/ABC
* 注意用該註解獲取get請求引數時,有坑,引數是中文或者帶點時,解析不到,查詢資料需要設定tomcat配置
* 使用@PathVariable註解獲取
*/
@RequestMapping("/get4/{name}")
public void getParamByGET4(@PathVariable(name = "name", required = true) String name) {
LOGGER.info(
"get4接收到的引數:{}", name);
}

/**
* 下面post請求的請求體:
* {
"name":"小明",
"idType":"0",
"idno":"123"
}
*/

/**
* 使用@RequestBody獲取,Content-Type是application/json
* @param userKey 對應引數中的每個欄位
*/
@PostMapping("/post1")
public void getParamByPOST1(@RequestBody UserKey userKey){
LOGGER.info("post1接收到的引數:{}",userKey);
}

/**
* 使用Map來獲取
* map中存放的鍵值對就對應於json中的鍵值對 content-type:application/json
*/
@PostMapping("/post2")
public void getParamByPOST2(@RequestBody Map<String,String> map){
String name = map.get("name");
String idNo = map.get("idNo");
String idType = map.get("idType");
LOGGER.info("post2獲取到的引數:{}.{},{}",name,idNo,idType);
}

/**
* 使用HttpServletRequest來獲取,這裡必須把content-type改為x-www-form-urlencoded方式才可以
*/
@PostMapping("/post3")
public void getParamByPOST3(HttpServletRequest request){
String name = request.getParameter("name");
String idType = request.getParameter("idType");
String idNo = request.getParameter("idNo");
LOGGER.info("post2獲取到的引數:{}.{},{}",name,idNo,idType);
}
}