分享

SpringMVC @ResponseBody 415错误处理

 再生资源保存站 2017-05-02

闲话少说,刚开始用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配置文件开启注解

  1. <!-- 开启注解-->  
  2.  <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配置:

  1. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
  2.     <property name="messageConverters">  
  3.         <list>  
  4.             <ref bean="jsonHttpMessageConverter" />  
  5.         </list>  
  6.     </property>  
  7. </bean>  
  8.   
  9. <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter">  
  10.     <property name="supportedMediaTypes">  
  11.         <list>  
  12.             <value>application/json;charset=UTF-8</value>  
  13.         </list>  
  14.     </property>  
  15. </bean>  


spring4.x配置:

  1. <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">  
  2.     <property name="messageConverters">  
  3.         <list>  
  4.             <ref bean="jsonHttpMessageConverter" />  
  5.         </list>  
  6.     </property>  
  7. </bean>  
  8.   
  9. <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
  10.     <property name="supportedMediaTypes">  
  11.         <list>  
  12.             <value>application/json;charset=UTF-8</value>  
  13.         </list>  
  14.     </property>  
  15. </bean>  

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

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

  1.        <dependency>  
  2.             <groupId>org.codehaus.jackson</groupId>  
  3.             <artifactId>jackson-core-lgpl</artifactId>  
  4.             <version>1.8.1</version>  
  5.          </dependency>  
  6.   
  7.   
  8.         <dependency>  
  9.             <groupId>org.codehaus.jackson</groupId>  
  10.             <artifactId>jackson-mapper-lgpl</artifactId>  
  11.             <version>1.8.1</version>  
  12.         </dependency></span>  
spring4.x,  pom.xml添加如下配置

  1.    <dependency>  
  2.     <groupId>com.fasterxml.jackson.core</groupId>  
  3.     <artifactId>jackson-core</artifactId>  
  4.     <version>2.5.2</version>  
  5. </dependency>  
  6.   
  7. <dependency>  
  8.     <groupId>com.fasterxml.jackson.core</groupId>  
  9.     <artifactId>jackson-databind</artifactId>  
  10.     <version>2.5.2</version>  
  11. </dependency>  


这里要说明一下,spring3.x用的是org.codehaus.jackson的1.x版本,在maven资源库,已经不在维护,统一迁移到com.fasterxml.jackson,版本对应为2.x





(4)ajax请求要求

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

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

  1.        var data = {  
  2. userAccount: lock_username,  
  3. userPasswd:hex_md5(lock_password).toUpperCase()  
  4. }  
  5.   
  6. $.ajax({  
  7.     url : ctx + "/unlock.do",  
  8.     type : "POST",  
  9.     data : JSON.stringify(data),  
  10.         dataType: 'json',  
  11.                contentType:'application/json;charset=UTF-8',      
  12.     success : function(result) {  
  13.         console.log(result);  
  14.     }  
  15. });  

(5)  Controller 接收响应JSON

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

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

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

[javascript] view plain copy
  1. //请求数据,登录账号 +密码  
  2.      var data = {  
  3.              userAccount: lock_username,  
  4.              userPasswd:hex_md5(lock_password).toUpperCase()  
  5.      }  
  6.        
  7.      $.ajax({  
  8.             url : ctx + "/unlock.do",  
  9.             type : "POST",  
  10.             data : JSON.stringify(data), //转JSON字符串  
  11.             dataType: 'json',  
  12.             contentType:'application/json;charset=UTF-8', //contentType很重要     
  13.             success : function(result) {  
  14.                 console.log(result);  
  15.             }  
  16.      });  
  • 方式二: POST + JSON对象形式,如下:
[javascript] view plain copy
  1. //请求数据,登录账号 +密码  
  2. ar data = {  
  3.      userAccount: lock_username,  
  4.      userPasswd:hex_md5(lock_password).toUpperCase()  
  5. }  
  6.   
  7. $.ajax({  
  8.     url : ctx + "/unlock.do",  
  9.     type : "POST",  
  10.     data : data, //直接用JSON对象  
  11.     dataType: 'json',  
  12.     success : function(result) {  
  13.         console.log(result);  
  14.     }  
  15. });  

代码案例:

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

JS请求:

[javascript] view plain copy
  1. //请求数据,登录账号 +密码  
  2. var data = {  
  3.      userAccount: lock_username,  
  4.      userPasswd:hex_md5(lock_password).toUpperCase()  
  5. }  
  6.   
  7. $.ajax({  
  8.     url : ctx + "/unlock.do",  
  9.     type : "POST",  
  10.     data : JSON.stringify(data), //转JSON字符串  
  11.     dataType: 'json',  
  12.        contentType:'application/json;charset=UTF-8', //contentType很重要     
  13.     success : function(result) {  
  14.         console.log(result);  
  15.     }  
  16. });  

Controller处理:

  1.     @RequestMapping(value = "/unlock", method = RequestMethod.POST,consumes = "application/json")   
  2.     @ResponseBody  
  3.     public Object unlock(@RequestBody User user) {    
  4.         JSONObject jsonObject = new JSONObject();    
  5.           
  6.         try{  
  7.             Assert.notNull(user.getUserAccount(), "解锁账号为空");  
  8.             Assert.notNull(user.getUserPasswd(), "解锁密码为空");  
  9.               
  10.             User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);  
  11.             Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!");  
  12.               
  13.             Assert.isTrue(StringUtils.equals(user.getUserAccount(),currentLoginUser.getUserAccount()), "解锁账号错误");  
  14.             Assert.isTrue(StringUtils.equalsIgnoreCase(user.getUserPasswd(),currentLoginUser.getUserPasswd()), "解锁密码错误");  
  15.               
  16. jsonObject.put("message", "解锁成功");    
  17. jsonObject.put("status", "success");  
  18.         }catch(Exception ex){  
  19.             jsonObject.put("message", ex.getMessage());    
  20.                 jsonObject.put("status", "error");  
  21.         }  
  22.        return jsonObject;    
  23.     }    

  1. 浏览器控制台输出:  


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

JS请求:

[javascript] view plain copy
  1. //请求数据,登录账号 +密码  
  2. var data = {  
  3.      userAccount: lock_username,  
  4.      userPasswd:hex_md5(lock_password).toUpperCase()  
  5. }  
  6.   
  7. $.ajax({  
  8.     url : ctx + "/unlock.do",  
  9.     type : "POST",  
  10.     data : JSON.stringify(data), //转JSON字符串  
  11.     dataType: 'json',  
  12.        contentType:'application/json;charset=UTF-8', //contentType很重要     
  13.     success : function(result) {  
  14.         console.log(result);  
  15.     }  
  16. });  

Controller处理:

  1.   @RequestMapping(value = "/unlock", method = RequestMethod.POST,consumes = "application/json")   
  2.   public ResponseEntity<Object> unlock(HttpEntity<User> user) {    
  3. JSONObject jsonObject = new JSONObject();    
  4.   
  5. try{  
  6.     Assert.notNull(user.getBody().getUserAccount(), "解锁账号为空");  
  7.     Assert.notNull(user.getBody().getUserPasswd(), "解锁密码为空");  
  8.       
  9.     User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);  
  10.     Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!");  
  11.       
  12.     Assert.isTrue(StringUtils.equals(user.getBody().getUserAccount(),currentLoginUser.getUserAccount()), "解锁账号错误");  
  13.     Assert.isTrue(StringUtils.equalsIgnoreCase(user.getBody().getUserPasswd(),currentLoginUser.getUserPasswd()), "解锁密码错误");  
  14.       
  15.               jsonObject.put("message", "解锁成功");    
  16.               jsonObject.put("status", "success");  
  17. }catch(Exception ex){  
  18.     jsonObject.put("message", ex.getMessage());    
  19.         jsonObject.put("status", "error");  
  20. }  
  21. ResponseEntity<Object> responseResult = new ResponseEntity<Object>(jsonObject,HttpStatus.OK);  
  22.        return responseResult;  
  23.   }    

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

如果不加适用GET + POST ;

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

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

 POST+ JSON对象形式请求:

[javascript] view plain copy
  1. var data = {  
  2.          userAccount: lock_username,  
  3.          userPasswd:hex_md5(lock_password).toUpperCase()  
  4.  }  
  5.    
  6.  $.ajax({  
  7.         url : ctx + "/unlock.do",  
  8.         type : "POST",  
  9.         data : data,  
  10.         dataType: 'json',  
  11.         success : function(result) {  
  12.             console.log(result);  
  13.         }  
  14.  });  

GET + 参数字符串请求:

[javascript] view plain copy
  1. $.ajax({  
  2.     url : ctx + "/unlock.do",  
  3.     type : "GET",  
  4.     dataType: "text",   
  5.     data : "userAccount="+lock_username+"&userPasswd=" + hex_md5(lock_password).toUpperCase(),//等价于URL后面拼接参数  
  6.     success : function(result) {  
  7.         console.log(result);  
  8.     }  
  9. });  
Controller处理:

  1. @RequestMapping(value = "/unlock")   
  2.    public void unlock(HttpServletRequest request,HttpServletResponse response)  throws IOException {    
  3.     JSONObject jsonObject = new JSONObject();    
  4.       
  5.     String userAccount = (String)request.getParameter("userAccount");  
  6.     String userPasswd = (String)request.getParameter("userPasswd");  
  7.     try{  
  8.         Assert.notNull(userAccount, "解锁账号为空");  
  9.         Assert.notNull(userPasswd, "解锁密码为空");  
  10.           
  11.         User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);  
  12.         Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!");  
  13.           
  14.         Assert.isTrue(StringUtils.equals(userAccount,currentLoginUser.getUserAccount()), "解锁账号错误");  
  15.         Assert.isTrue(StringUtils.equalsIgnoreCase(userPasswd,currentLoginUser.getUserPasswd()), "解锁密码错误");  
  16.           
  17.         jsonObject.put("message", "解锁成功");    
  18.         jsonObject.put("status", "success");  
  19.     }catch(Exception ex){  
  20.         jsonObject.put("message", ex.getMessage());    
  21.         jsonObject.put("status", "error");  
  22.     }  
  23.       
  24.        response.getWriter().print(jsonObject.toString());    
  25.    }    

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

如果不加适用GET + POST ;

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

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


 POST+ JSON对象形式请求:

[javascript] view plain copy
  1. var data = {  
  2.      userAccount: lock_username,  
  3.      userPasswd:hex_md5(lock_password).toUpperCase()  
  4. }  
  5.   
  6. $.ajax({  
  7.     url : ctx + "/unlock.do",  
  8.     type : "POST",  
  9.     data : data,  
  10.     dataType: 'json',  
  11.     success : function(result) {  
  12.         console.log(result);  
  13.     }  
  14. });  

GET + 参数字符串请求:

[javascript] view plain copy
  1. $.ajax({  
  2.     url : ctx + "/unlock.do",  
  3.     type : "GET",  
  4.     dataType: "text",   
  5.     data : "userAccount="+lock_username+"&userPasswd=" + hex_md5(lock_password).toUpperCase(),//等价于URL后面拼接参数  
  6.     success : function(result) {  
  7.         console.log(result);  
  8.     }  
  9. });  


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

  1. @RequestMapping(value = "/unlock",method = RequestMethod.POST)   
  2.    public void unlock(@ModelAttribute("user") User user,PrintWriter printWriter)  throws IOException {    
  3.     JSONObject jsonObject = new JSONObject();    
  4.       
  5.     try{  
  6.         Assert.notNull(user.getUserAccount(), "解锁账号为空");  
  7.         Assert.notNull(user.getUserPasswd(), "解锁密码为空");  
  8.           
  9.         User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER);  
  10.         Assert.notNull(currentLoginUser, "登录用户已过期,请重新登录!");  
  11.           
  12.         Assert.isTrue(StringUtils.equals(user.getUserAccount(),currentLoginUser.getUserAccount()), "解锁账号错误");  
  13.         Assert.isTrue(StringUtils.equalsIgnoreCase(user.getUserPasswd(),currentLoginUser.getUserPasswd()), "解锁密码错误");  
  14.           
  15.         jsonObject.put("message", "解锁成功");    
  16.         jsonObject.put("status", "success");  
  17.     }catch(Exception ex){  
  18.         jsonObject.put("message", ex.getMessage());    
  19.         jsonObject.put("status", "error");  
  20.     }  
  21.     printWriter.print(jsonObject.toString());  
  22.    }    


寻找问题学习过程中参考资料:




其他可以学习参考的博客:



    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多