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 [com.org.action.LoginController@4c79ace8]: 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 [com.org.action.LoginController@4c79ace8]: 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 [com.org.action.LoginController@4c79ace8]: 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错误)