在查看下面部分内容之前,请先检查你的请求蚕食是否正确,如果全部正确,请继续往下看

刚开始用SpringMVC, 页面要使用jQuery的ajax请求Controller。 但总是失败,主要表现为以下两个异常为:

异常一:Java.lang.ClassNotFoundException: org.springframework.http.converter.json.MappingJacksonHttpMessageConverter

异常二:SpringMVC @ResponseBody 415错误处理

网上分析原因很多,但找了很久都没解决,基本是以下几类:

  • springmvc添加配置、注解;
  • pom.xml添加jackson包引用;
  • Ajax请求时没有设置Content-Type为application/json
  • 发送的请求内容不要转成JSON对象,直接发送JSON字符串即可

这些其实都没错!!!

以下是我分析的解决步骤方法:

(1)springMVC配置文件开启注解

   <!-- 开启注解-->
<mvc:annotation-driven />

(2)添加springMVC需要添加如下配置。 (这个要注意spring版本,3.x和4.x配置不同)

spring3.x是org.springframework.http.converter.json.MappingJacksonHttpMessageConverter

spring4.x是org.springframework.http.converter.json.MappingJackson2HttpMessageConverter

具体可以查看spring-web的jar确认,哪个存在用哪个!

spring3.x配置:

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

spring4.x配置:

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

(3)pom.xml添加jackson依赖(这个要注意spring版本,3.x和4.x配置不同

如果是spring 3.x,pom.xml添加如下配置

           <dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-lgpl</artifactId>
<version>1.8.1</version>
</dependency> <dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-lgpl</artifactId>
<version>1.8.1</version>
</dependency></span>

spring4.x,  pom.xml添加如下配置

        <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.2</version>
</dependency> <dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.2</version>
</dependency>

这里要说明一下,spring3.x用的是com.fasterxml.jackson,版本对应为2.x

(4)ajax请求要求

  • dataType 为 json
  • contentType 为 'application/json;charse=UTF-8'
  • data 转JSON字符串

我的代码:如下:  (注意:这里只是针对POST +JSON字符串形式请求,后面我会详细讲解不同形式请求,的处理方法和案例)

         var data = {
userAccount: lock_username,
userPasswd:hex_md5(lock_password).toUpperCase()
} $.ajax({
url : ctx + "/unlock.do",
type : "POST",
data : JSON.stringify(data),
dataType: 'json',
contentType:'application/json;charset=UTF-8',
success : function(result) {
console.log(result);
}
});

(5)  Controller 接收响应JSON

以上配置OK,Controller中使用JSON方式有多种。这里简单介绍几种。

这个关键在于ajax请求是将数据以什么形式传递到后台,这里我总结了三种形式

  • POST + JSON字符串形式
  • POST + JSON对象形式
  • GET + 参数字符串
  • 方式一: POST + JSON字符串形式,如下:

    //请求数据,登录账号 +密码
    var data = {
    userAccount: lock_username,
    userPasswd:hex_md5(lock_password).toUpperCase()
    } $.ajax({
    url : ctx + "/unlock.do",
    type : "POST",
    data : JSON.stringify(data), //转JSON字符串
    dataType: 'json',
    contentType:'application/json;charset=UTF-8', //contentType很重要
    success : function(result) {
    console.log(result);
    }
    });

    方式二: POST + JSON对象形式,如下:

         //请求数据,登录账号 +密码
    var data = {
    userAccount: lock_username,
    userPasswd:hex_md5(lock_password).toUpperCase()
    } $.ajax({
    url : ctx + "/unlock.do",
    type : "POST",
    data : data, //直接用JSON对象
    dataType: 'json',
    success : function(result) {
    console.log(result);
    }
    });

    代码案例:

    5-1: 使用@RequestBody来设置输入 ,@ResponseBody设置输出 (POST + JSON字符串形式)

    JS请求:

         //请求数据,登录账号 +密码
    var data = {
    userAccount: lock_username,
    userPasswd:hex_md5(lock_password).toUpperCase()
    } $.ajax({
    url : ctx + "/unlock.do",
    type : "POST",
    data : JSON.stringify(data), //转JSON字符串
    dataType: 'json',
    contentType:'application/json;charset=UTF-8', //contentType很重要
    success : function(result) {
    console.log(result);
    }
    });

    Controller处理:

        @RequestMapping(value = "/unlock", method = RequestMethod.POST,consumes = "application/json")
    @ResponseBody
    public Object unlock(@RequestBody User user) {
    JSONObject jsonObject = new JSONObject(); try{
    Assert.notNull(user.getUserAccount(), "解锁账号为空");
    Assert.notNull(user.getUserPasswd(), "解锁密码为空"); User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);
    Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!"); Assert.isTrue(StringUtils.equals(user.getUserAccount(),currentLoginUser.getUserAccount()), "解锁账号错误");
    Assert.isTrue(StringUtils.equalsIgnoreCase(user.getUserPasswd(),currentLoginUser.getUserPasswd()), "解锁密码错误"); jsonObject.put("message", "解锁成功");
    jsonObject.put("status", "success");
    }catch(Exception ex){
    jsonObject.put("message", ex.getMessage());
    jsonObject.put("status", "error");
    }
    return jsonObject;
    }

    浏览器控制台输出:

  • 5-2: 使用HttpEntity来实现输入绑定,来ResponseEntit输出绑定POST
    + JSON字符串形式

    JS请求:

         //请求数据,登录账号 +密码
    var data = {
    userAccount: lock_username,
    userPasswd:hex_md5(lock_password).toUpperCase()
    } $.ajax({
    url : ctx + "/unlock.do",
    type : "POST",
    data : JSON.stringify(data), //转JSON字符串
    dataType: 'json',
    contentType:'application/json;charset=UTF-8', //contentType很重要
    success : function(result) {
    console.log(result);
    }
    });

    Controller处理:

        @RequestMapping(value = "/unlock", method = RequestMethod.POST,consumes = "application/json")
    public ResponseEntity<Object> unlock(HttpEntity<User> user) {
    JSONObject jsonObject = new JSONObject(); try{
    Assert.notNull(user.getBody().getUserAccount(), "解锁账号为空");
    Assert.notNull(user.getBody().getUserPasswd(), "解锁密码为空"); User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);
    Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!"); Assert.isTrue(StringUtils.equals(user.getBody().getUserAccount(),currentLoginUser.getUserAccount()), "解锁账号错误");
    Assert.isTrue(StringUtils.equalsIgnoreCase(user.getBody().getUserPasswd(),currentLoginUser.getUserPasswd()), "解锁密码错误"); jsonObject.put("message", "解锁成功");
    jsonObject.put("status", "success");
    }catch(Exception ex){
    jsonObject.put("message", ex.getMessage());
    jsonObject.put("status", "error");
    }
    ResponseEntity<Object> responseResult = new ResponseEntity<Object>(jsonObject,HttpStatus.OK);
    return responseResult;
    }

    5-3: 使用request.getParameter获取请求参数,响应JSONPOST + JSON对象形式) 和(GET + 参数字符串),Controller处理一样,区别在于是否加注解如果不加适用GET + POST ;

    POST 请求;

    如果method=RequestMethod.GET,用于GET请求;

     POST+ JSON对象形式请求:

     var data = {
    userAccount: lock_username,
    userPasswd:hex_md5(lock_password).toUpperCase()
    } $.ajax({
    url : ctx + "/unlock.do",
    type : "POST",
    data : data,
    dataType: 'json',
    success : function(result) {
    console.log(result);
    }
    });

    GET + 参数字符串请求:

         $.ajax({
    url : ctx + "/unlock.do",
    type : "GET",
    dataType: "text",
    data : "userAccount="+lock_username+"&userPasswd=" + hex_md5(lock_password).toUpperCase(),//等价于URL后面拼接参数
    success : function(result) {
    console.log(result);
    }
    });

    Controller处理:

        @RequestMapping(value = "/unlock")
    public void unlock(HttpServletRequest request,HttpServletResponse response) throws IOException {
    JSONObject jsonObject = new JSONObject(); String userAccount = (String)request.getParameter("userAccount");
    String userPasswd = (String)request.getParameter("userPasswd");
    try{
    Assert.notNull(userAccount, "解锁账号为空");
    Assert.notNull(userPasswd, "解锁密码为空"); User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);
    Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!"); Assert.isTrue(StringUtils.equals(userAccount,currentLoginUser.getUserAccount()), "解锁账号错误");
    Assert.isTrue(StringUtils.equalsIgnoreCase(userPasswd,currentLoginUser.getUserPasswd()), "解锁密码错误"); jsonObject.put("message", "解锁成功");
    jsonObject.put("status", "success");
    }catch(Exception ex){
    jsonObject.put("message", ex.getMessage());
    jsonObject.put("status", "error");
    } response.getWriter().print(jsonObject.toString());
    }

    5-4: 使用@ModelAttribute将参数封装对象,响应JSON(POST + JSON对象形式) 和(GET + 参数字符串),Controller处理一样,区别在于是否加注解

    如果不加适用GET + POST ;

    如果method=RequestMethod.GET,用于GET请求;


     POST+ JSON对象形式请求:

         var data = {
    userAccount: lock_username,
    userPasswd:hex_md5(lock_password).toUpperCase()
    } $.ajax({
    url : ctx + "/unlock.do",
    type : "POST",
    data : data,
    dataType: 'json',
    success : function(result) {
    console.log(result);
    }
    });

    GET + 参数字符串请求:

         $.ajax({
    url : ctx + "/unlock.do",
    type : "GET",
    dataType: "text",
    data : "userAccount="+lock_username+"&userPasswd=" + hex_md5(lock_password).toUpperCase(),//等价于URL后面拼接参数
    success : function(result) {
    console.log(result);
    }
    });

    Controller处理:(这个案例只支持POST)

        @RequestMapping(value = "/unlock",method = RequestMethod.POST)
    public void unlock(@ModelAttribute("user") User user,PrintWriter printWriter) throws IOException {
    JSONObject jsonObject = new JSONObject(); try{
    Assert.notNull(user.getUserAccount(), "解锁账号为空");
    Assert.notNull(user.getUserPasswd(), "解锁密码为空"); User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);
    Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!"); Assert.isTrue(StringUtils.equals(user.getUserAccount(),currentLoginUser.getUserAccount()), "解锁账号错误");
    Assert.isTrue(StringUtils.equalsIgnoreCase(user.getUserPasswd(),currentLoginUser.getUserPasswd()), "解锁密码错误"); jsonObject.put("message", "解锁成功");
    jsonObject.put("status", "success");
    }catch(Exception ex){
    jsonObject.put("message", ex.getMessage());
    jsonObject.put("status", "error");
    }
    printWriter.print(jsonObject.toString());
    }

SpringMVC @ResponseBody 415错误处理的更多相关文章

  1. 解决微信小程序用 SpringMVC 处理http post时请求报415错误

    解决微信小程序用 SpringMVC 处理http post时请求返回415错误 写微信小程序时遇到的问题,这个坑硬是让我整了半天 wx.request请求跟ajax类似处理方法一致 小程序端请求代码 ...

  2. springmvc 使用jq传递json数据时出现415错误

    出现415错误是因为解析json时出现了错误,通过排查几点就能解决. 样例: <script> function requestByJson() { var datatest = {&qu ...

  3. ajax往后台传json格式数据报415错误

    问题描述: ajax往后台传json格式数据报415错误,如下图所示 页面代码 function saveUser(){ var uuId = document.getElementById(&quo ...

  4. springMvc中406错误解决,springMvc使用json出现406 (Not Acceptable)

    springMvc中406错误解决, springMvc使用json出现406 (Not Acceptable) >>>>>>>>>>> ...

  5. HTTP请求415错误 – 不支持的媒体类型(Unsupported media type)

    HTTP请求415错误 – 不支持的媒体类型(Unsupported media type) 通常有以下情况: 1:检查你的 http 请求头信息,比如 因为 User-Agent 被服务器设置 拒绝 ...

  6. 使用GBK编码请求访问nodejs程序报415错误:Error: unsupported charset at urlencodedParser ...

    最近遇到一个问题,第三方用户向我们提供给的回调地址发送请求时一直报415错误,结果发现他们使用的是GBK编码请求,而我们使用的node + express4 程序,不支持GBK编码请求. 问题出在下面 ...

  7. spring参数类型异常输出(二), SpringMvc参数类型转换错误输出(二)

    spring参数类型异常输出(二), SpringMvc参数类型转换错误输出(二) >>>>>>>>>>>>>>&g ...

  8. spring参数类型异常输出,SpringMvc参数类型转换错误输出

    spring参数类型异常输出, SpringMvc参数类型转换错误输出 >>>>>>>>>>>>>>>> ...

  9. http请求415错误Unsupported Media Type

    王子乔 每一个认真生活的人,都值得被认真对待 http请求415错误Unsupported Media Type 之前用了封装的ajax,因为请求出了点问题,我试了下jQuery的$.ajax,报出了 ...

随机推荐

  1. Oracle 经常使用的改动语句

    一.表Table 測试表:MY_TEST_TABLE -- Create table create table MY_TEST_TABLE ( A VARCHAR2(30), B NUMBER(10) ...

  2. 在DLL中封装的VCL窗体Tab键响应的问题

    在DLL中的子窗体不会响应Tab按键的,这个时候就需要手动去指定Tab键的操作,但是前提是主窗体要向这个窗体发送一个消息,一个Tab键按下的消息.基本顺序是这样的: 1. 主窗体用Hook技术捕获Ta ...

  3. JQuery 插件之Ajax Autocomplete(ajax自动完成)

    平时用百度,谷歌搜索的时候 会有一个下 拉列表进行提示 这是一个非常好的功能 本文要介绍的这个JQuery 插件 名叫Ajax Autocomplete 顾名思义 ajax 也就是用ajax的方式获取 ...

  4. js实现class样式的修改、添加及删除的方法

    本文实例讲述了js实现class样式的修改.添加及删除的方法.分享给大家供大家参考.具体分析如下: 比较常见的js前端功能,通过修改标签的className实现相应的功能. 具体代码如下: <t ...

  5. 去掉Enter字符(\r)的几个方法

    数据:test.txt: f1:f2:f3:# Shell: #!/bin/bash while read line do echo $line result1=$(echo $line|awk -F ...

  6. MFC 总体理解

    在MFC程序中,我们并不经常直接调用Windows API,而是从MFC类创建对象并调用属于这些对象的成员函数.也就是说MFC封装了Windows API 你说你喜欢C++而MFC换一种说法就是一个用 ...

  7. 用"池"来提升对象的复用

    对象池化是目前常用的一种系统优化的技术.通俗的说也就是一个对象不用多次的被实例化,来消耗性能,可以把这些常用的类放入一个池中,当需要的时候在去池里去拿去,不用的时候 在放入池中.可以叫做对象池.他可以 ...

  8. setenv 和 set

    setenv 和 set 是在csh系列的命令,当然bash中也有set,还是有出入的.   set 是对当前进程有效,不会传递给子进程 setenv 不仅对当前进程有效,也会传递给子进程.   语法 ...

  9. Hibernate(六)——多对多关联映射

    前面几篇文章已经较讲解了三大种关联映射,多对多映射就非常简单了,不过出于对关联映射完整性的考虑,本文还是会简要介绍下多对多关联映射. 1.单向多对多关联映射 情景:一个用户可以有多个角色,比如数据录入 ...

  10. 44个JAVA代码质量管理工具(转)

    1. CodePro AnalytixIt’s a great tool (Eclipse plugin) for improving software quality. It has the nex ...