@ResponseBody 遇见406

@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就消失不见了。真是牛逼。现在也不管这是什么原理,我就乖乖的在我的配置文件里加上上面的代码就好了,对于原理什么的,以后再怼。老夫打代码从不考虑什么底层原理,逻辑啦,全部都是复制粘贴,拿起键盘就是干!!!

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值