目录
二、method = RequestMethod.POST/RequestMethod.GET
一、请求类型
form-data、x-www-form-urlencoded(默认格式):不可以用 @RequestBody;可以用 @RequestParam;
application/json:json 字符串部分可以用 @RequestBody;
Params 格式可以用 @RequestParam。
POST请求时
@RequestBody --> JSON 字符串部分
@RequestParam --> 一般请求参数部分
HttpServletRequest request --> 请求信息
首先看一下简单的 Controller测试类:
@RequestMapping(value = "/test")
@ResponseBody
public String test(HttpServletRequest request,
@RequestBody Map map) throws ParseException {
System.out.println("request = [" + request + "], map = [" + map + "]");
String startDateparam = (String) map.get("startDate");
String dateType = (String) map.get("type");
JSONObject jo = new JSONObject();
jo.put("name",startDateparam);
jo.put("dsc", dateType);
String returns = jo.toJSONString();
return returns;
}
application/json 请求如下图:
注:JSON(application/json):请求信息类型,如果不设置或是设置错误,后台会报不支持的错误。
返回结果:
JSON (Map、Object) 格式的都可以使用 @RequestBody
但是 form-data、x-www-form-urlencoded 时候不可用。此时就需要 @RequestParam 接收参数:
另外 Params 参数拼接到 url 后也是可以的,如下图
@RequestMapping(value = "/test")
@ResponseBody
public String test(HttpServletRequest request,
@RequestParam String startDate,
@RequestParam String type) throws ParseException {
...
}
参数可以没有顺序(即前端传过来的参数或者url中的参数顺序不必和后台接口中的参数顺序一致,只要字段名相同就可以)
当然,上面代码中注解 @RequestParam 不加也是可以的。
@RequestMapping(value = "/test")
@ResponseBody
public String test(HttpServletRequest request,
String startDate,
String type) throws ParseException {
...
}
只有上述 String等基本类型可以接收,如果是 Object/Map 就接收不到,此时不妨看看 HttpServletRequest request。
GET请求时
Postman 中,application/json 请求如下图:
后台可以 @RequestBody Map map 接收参数。
Params 形式参数自动拼接到url后,后台可以 @RequestBody Map map 接收参数。
后台使用 @RequestParam 接收:
@RequestMapping(value = "/test")
@ResponseBody
public String test(HttpServletRequest request,
@RequestParam String startDate,
@RequestParam String type) throws ParseException {
...
}
二、method = RequestMethod.POST/RequestMethod.GET
@RequestMapping 中参数 method ,无非为了安全考虑,可加可不加。
spring mvc @RequestMapping method 不写的话,默认GET、POST都支持,根据前端方式自动适应
三、produces = MediaType.
public class MediaType extends MimeType implements Serializable {}
子类 MimeType 增加了对HTTP规范中定义的质量参数的支持。
简单来说:produces,它的作用是指定返回值类型,不但可以设置返回值类型还可以设定返回值的字符编码;
需要注意的是:使用了注解 @responseBody 就是返回值是 json 数据:此时 produces 不需要设置。
@RequestMapping(value = "/test",produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
@RequestMapping(value = "/test}", produces="MediaType.APPLICATION_JSON_VALUE"+";charset=utf-8")