springMVC 解决ajax请求的406错误

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了springMVC 解决ajax请求的406错误相关的知识,希望对你有一定的参考价值。

直入主题--

页面表单异步提交:$.post(‘<%=request.getContextPath()%>/web/register.html‘, $(form).serialize(), function(data){...});

java后台springMVC的controller接受请求:

@RequestMapping("register")
@ResponseBody
public Map<String, String> register(HttpServletRequest request, HttpServletResponse response, User user) {
  Map<String, String> resMap = loginService.insertUser(user);
  return resMap;
}

错误描述,springMVC的controller中接收到页面发送的ajax请求,java后台处理时报错:


[DEBUG] [2016-02-14 20:08:09] org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(133) | Resolving exception from handler [[email protected]]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
[DEBUG] [2016-02-14 20:08:09] org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(133) | Resolving exception from handler [[email protected]]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
[DEBUG] [2016-02-14 20:08:09] org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(133) | Resolving exception from handler [[email protected]]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation
[DEBUG] [2016-02-14 20:08:09] org.springframework.web.servlet.DispatcherServlet.processDispatchResult(1034) | Null ModelAndView returned to DispatcherServlet with name ‘rest‘: assuming HandlerAdapter completed request handling
[DEBUG] [2016-02-14 20:08:09] org.springframework.web.servlet.FrameworkServlet.processRequest(999) | Successfully completed request
[DEBUG] [2016-02-14 20:08:09] org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(251) | Returning cached instance of singleton bean ‘sqlSessionFactory‘

此时对应的页面报错为:

POST http://127.0.0.1:8080/maven-web-demo/web/register.html 406 (Not Acceptable)

 

原因:缺少spring-mvc的json配置

解决方法:

1.添加spring-mvc的json依赖jar包:jackson-core和jackson-databind

2.在spring-mvc.xml中添加:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="mappingJacksonHttpMessageConverter" />
</list>
</property>
</bean>
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>

OK,问题解决!

 

以上是关于springMVC 解决ajax请求的406错误的主要内容,如果未能解决你的问题,请参考以下文章

SSM框架整合时ajax请求返回406

SpringMVC出现406错误的解决办法

http请求后台报406错误

http请求出现406错误解决方案

springmvc之json交互406异常(Not Acceptable)和415异常(Unsupported Media Type)

SpringMVC注解@RequestMapping之produces属性导致的406错误