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);
}
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM