java webcontroller訪問時報415錯誤

閒話少說,剛開始用SpringMVC, 頁面要使用jquery的ajax請求Controller。 但老是失敗,主要表現爲如下兩個異常爲:javascript

異常一:java.lang.ClassNotFoundException: org.springframework.http.converter.json.MappingJacksonHttpMessageConverterhtml

異常二:SpringMVC @ResponseBody 415錯誤處理java

 

網上分析緣由不少,但找了好久都沒解決,基本是如下幾類:jquery

  • springmvc添加配置、註解;
  • pom.xml添加jackson包引用;
  • Ajax請求時沒有設置Content-Type爲application/json
  •  發送的請求內容不要轉成JSON對象,直接發送JSON字符串便可

這些其實都沒錯!!!web

如下是我分析的解決步驟方法:ajax

(1)springMVC配置文件開啓註解spring

[html]  view plain  copy
 
  1. <!-- 開啓註解-->  
  2.  <mvc:annotation-driven />  

 

(2)添加springMVC須要添加以下配置。 (這個要注意spring版本,3.x和4.x配置不一樣)json

spring3.x是org.springframework.http.converter.json.MappingJacksonHttpMessageConverter瀏覽器

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

 

具體能夠查看spring-web的jar確認,哪一個存在用哪一個!

 

spring3.x配置:

 

[html]  view plain  copy
 
  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配置:

 

[html]  view plain  copy
 
  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添加以下配置

 

 

[html]  view plain  copy
 
  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添加以下配置

 

[html]  view plain  copy
 
  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字符串形式請求,後面我會詳細講解不一樣形式請求,的處理方法和案例)

 

[html]  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 : 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處理:

[java]  view plain  copy
 
  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.     }    

 

[html]  view plain  copy
 
  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處理:

[java]  view plain  copy
 
  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獲取請求參數,響應JSON(POST + 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處理:

 

 

[java]  view plain  copy
 
  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將參數封裝對象,響應JSON(POST + 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)

 

[java]  view plain  copy
 
    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.    }    
相關文章
相關標籤/搜索