springMVC 4.3.7 @RequestBody 报错415 Unsupported Media Type
我的目的是希望用@RequestBody
这个注解帮我实现把请求体里的application/json;charset=UTF-8
参数数据直接序列化成对象,所以我这样写controller
@PostMapping(value = "/test", produces = "application/json;charset=UTF-8", consumes = "application/json;charset=UTF-8")
@ResponseBody
public Pagination<User> test(@RequestBody Parameter parameter, HttpServletRequest request) {
return userServiceBean.paging(parameter.getPage(), parameter.getSize());
}
前端用的angularjs做的请求, 结果一直收到的响应都是415 Unsupported Media Type
.
在网上找了一圈, 全都逃不开两点:
- 前端没有写头
application/json;charset=UTF-8
(很显然我写了) - 后台springMVC配置文件没有加
<mvc:annotation-driven/>
(很显然我也写了)
最后发现问题出现在配置文件的命名空间写的版本号和我使用的spring版本号不一致:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
改成
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
改了之后就一切如我预期了