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

猜你喜欢

转载自www.cnblogs.com/it-yansx666/p/10096795.html