一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - SpringMVC @ResponseBody 415錯誤處理方式

SpringMVC @ResponseBody 415錯誤處理方式

2022-03-09 00:40yixiaoping Java教程

這篇文章主要介紹了SpringMVC @ResponseBody 415錯誤處理方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教

閑話少說,剛開始用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字符串即可

這些其實都沒錯?。。?/p>

以下是我分析的解決步驟方法

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
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<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配置:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<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>

3、pom.xml添加jackson依賴

(這個要注意spring版本,3.x和4.x配置不同

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

?
1
2
3
4
5
6
7
8
9
10
11
12
<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添加如下配置

?
1
2
3
4
5
6
7
8
9
10
11
<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用的是org.codehaus.jackson的1.x版本,在maven資源庫,已經不在維護,統一遷移到com.fasterxml.jackson,版本對應為2.x

SpringMVC @ResponseBody 415錯誤處理方式

4、ajax請求要求

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

我的代碼:如下: (注意:這里只是針對POST +JSON字符串形式請求,后面我會詳細講解不同形式請求,的處理方法和案例)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    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字符串形式,如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//請求數據,登錄賬號 +密碼
     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對象形式,如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
    
    //請求數據,登錄賬號 +密碼
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請求:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//請求數據,登錄賬號 +密碼
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處理:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
    @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; 
    }

瀏覽器控制臺輸出:

SpringMVC @ResponseBody 415錯誤處理方式

5-2: 使用HttpEntity來實現輸入綁定,來ResponseEntit輸出綁定(POST + JSON字符串形式)

JS請求:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
//請求數據,登錄賬號 +密碼
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處理:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
@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處理一樣,區別在于是否加注解method ,

  • 如果不加適用GET + POST ;
  • 如果 method= RequestMethod.POST,用于POST 請求;
  • 如果method=RequestMethod.GET,用于GET請求;

POST+ JSON對象形式請求:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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 + 參數字符串請求:

?
1
2
3
4
5
6
7
8
9
$.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處理:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
@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處理一樣,區別在于是否加注解method 。

  • 如果不加適用GET + POST ;
  • 如果 method= RequestMethod.POST,用于POST 請求;
  • 如果method=RequestMethod.GET,用于GET請求;

POST+ JSON對象形式請求:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
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 + 參數字符串請求:

?
1
2
3
4
5
6
7
8
9
$.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)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
@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());
}

以上為個人經驗,希望能給大家一個參考,也希望大家多多支持服務器之家。

原文鏈接:https://blog.csdn.net/yixiaoping/article/details/45281721

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 国产精品不卡 | 日韩视频在线精品视频免费观看 | 日韩无砖2021特黄 | 狠狠久久久久综合网 | 亚洲伦理天堂 | 白丝vk丨tk失禁 | 性色AV一区二区三区V视界影院 | 国产欧美日韩精品高清二区综合区 | 四虎国产成人免费观看 | 丰满肥臀风间由美357在线 | 被黑人同学彻底征服全文小说阅读 | 精选国产AV精选一区二区三区 | 国产欧美日韩精品一区二 | 日日夜夜撸影院 | 欧美精品一区二区三区免费观看 | 无限在线观看视频大全免费高清 | 911精品国产亚洲日本美国韩国 | 久久婷婷电影网 | 情欲满载2012美国dvd | 亚洲国产韩国欧美在线不卡 | 王晶经典三级 | 日本高清免费看 | 韩国最新三级网站在线播放 | 华人在线京东热 | 日本 视频 在线 | a级在线看 | 刺客女仆 | 亚洲国产99在线精品一区二区 | 日产中文乱码卡一卡二 | 免费精品国产在线观看 | 万域之王动漫在线观看全集免费播放 | 日比免费视频 | 欧美猛男同志同性video | 狠狠撸在线影院 | 天天爽天天操 | 果冻传媒mv在线观看入口免费 | 国产精品久久久久a影院 | 小早川怜子视频在线观看 | 四虎影院新网址 | www91在线观看 | 公妇仑乱在线观看 |