@ResponseBody
今天碰见了一个问题,以前也碰到过,没有解决,只是换了个方式,今天又碰见了,于是乎,我就开始百度百度,但是就是解决不了,有的说是说缺少依赖的jar包,但是我这里面不缺少呀。我又手动导入jar包还是不行,终于找到了一篇文章关于Spring MVC HTTP Status 406 - 解决方法算是解决了我的406错误。
先放406的图片
代码:
@RequestMapping(value = "checkUsername.htm")
@ResponseBody
public JsonResult checkUsername(HttpServletRequest request) {
JsonResult result = new JsonResult();
String username = request.getParameter("username");
int count = this.homeService.queryForCount(username);
if (count > 0) {
result.setState(-1);
result.setMessage("该用户名已经存在");
} else {
result.setState(1);
result.setMessage("该用户名可以使用");
}
return result;
}
这里 JsonResult 放的是json数据
下面是解决方案,同时也是别人写的东西:-D
用的Spring版本是4.2.4,在用@ResponseBody标注返回json格式时候遇到这样的错误:“The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request “accept” headers.”。字面意思很明显,产生的格式跟能接受的格式不符,对不上眼。但是各种google、stackoverflow之后,大多数答案都只是说要加上json的相关依赖之类的,试了都无用。于是跟踪代码,发现Spring默认ContentNegotiationManager使用org.springframework.web.accept.ServletPathExtensionContentNegotiationStrategy解析可接受的media type,这貌似是Spring 3哪个版本以后开始的特性,因为我的的url-pattern 是*.htm格式的,于是解析出来能accept的media type只有text/html,自然报错。而另一个HeaderContentNegotiationStrategy根本没发挥作用。
一个可行的解决方案:
在spring-servelt中添加
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
</list>
</property>
</bean>
这两个bean处理请求映射的,在bean中默认会创建一个使用HeaderContentNegotiationStrategy的ContentNegotiationManager,这样就能解析htttp请求头Accept中的类型了。但要注意的是,上述两个bean要定义在之前。为什么呢?因为会注册RequestMappingHandlerMapping, RequestMappingHandlerAdapter以及 ExceptionHandlerExceptionResolver等等的东西,如果上述两个bean定义放在之后就不起作用了。
上面的东西来自[(http://xsylang.iteye.com/blog/2298887)
果然 我的路径是.htm结尾的,于是就发生了406错误,我尝试这换成了.do的请求,406就消失不见了。真是牛逼。现在也不管这是什么原理,我就乖乖的在我的配置文件里加上上面的代码就好了,对于原理什么的,以后再怼。老夫打代码从不考虑什么底层原理,逻辑啦,全部都是复制粘贴,拿起键盘就是干!!!