SpringMVC @ResponseBody 415錯(cuò)誤處理方式
閑話少說,剛開始用SpringMVC, 頁面要使用jquery的ajax請(qǐng)求Controller。 但總是失敗,
主要表現(xiàn)為以下兩個(gè)異常為:
異常一:java.lang.ClassNotFoundException: org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
異常二:SpringMVC @ResponseBody 415錯(cuò)誤處理
網(wǎng)上分析原因很多,但找了很久都沒解決,基本是以下幾類:
- springmvc添加配置、注解;
- pom.xml添加jackson包引用;
- Ajax請(qǐng)求時(shí)沒有設(shè)置Content-Type為application/json
- 發(fā)送的請(qǐng)求內(nèi)容不要轉(zhuǎn)成JSON對(duì)象,直接發(fā)送JSON字符串即可
這些其實(shí)都沒錯(cuò)?。?!
以下是我分析的解決步驟方法
1、springMVC配置文件開啟注解
<!-- 開啟注解--> <mvc:annotation-driven />
2、添加springMVC需要添加如下配置
(這個(gè)要注意spring版本,3.x和4.x配置不同)
spring3.x是org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
spring4.x是org.springframework.http.converter.json.MappingJackson2HttpMessageConverter
具體可以查看spring-web的jar確認(rèn),哪個(gè)存在用哪個(gè)!
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>
3、pom.xml添加jackson依賴
(這個(gè)要注意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用的是org.codehaus.jackson的1.x版本,在maven資源庫,已經(jīng)不在維護(hù),統(tǒng)一遷移到com.fasterxml.jackson,版本對(duì)應(yīng)為2.x
4、ajax請(qǐng)求要求
- dataType 為 json
- contentType 為 'application/json;charse=UTF-8'
- data 轉(zhuǎn)JSON字符串
我的代碼:如下: (注意:這里只是針對(duì)POST +JSON字符串形式請(qǐng)求,后面我會(huì)詳細(xì)講解不同形式請(qǐng)求,的處理方法和案例)
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 接收響應(yīng)JSON
以上配置OK,Controller中使用JSON方式有多種。這里簡(jiǎn)單介紹幾種。
這個(gè)關(guān)鍵在于ajax請(qǐng)求是將數(shù)據(jù)以什么形式傳遞到后臺(tái),這里我總結(jié)了三種形式
- POST + JSON字符串形式
- POST + JSON對(duì)象形式
- GET + 參數(shù)字符串
方式一: POST + JSON字符串形式,如下:
//請(qǐng)求數(shù)據(jù),登錄賬號(hào) +密碼 var data = { userAccount: lock_username, userPasswd:hex_md5(lock_password).toUpperCase() } $.ajax({ url : ctx + "/unlock.do", type : "POST", data : JSON.stringify(data), //轉(zhuǎn)JSON字符串 dataType: 'json', contentType:'application/json;charset=UTF-8', //contentType很重要 success : function(result) { console.log(result); } });
方式二: POST + JSON對(duì)象形式,如下:
//請(qǐng)求數(shù)據(jù),登錄賬號(hào) +密碼 var data = { userAccount: lock_username, userPasswd:hex_md5(lock_password).toUpperCase() } $.ajax({ url : ctx + "/unlock.do", type : "POST", data : data, //直接用JSON對(duì)象 dataType: 'json', success : function(result) { console.log(result); } });
代碼案例:
5-1: 使用@RequestBody來設(shè)置輸入 ,@ResponseBody設(shè)置輸出 (POST + JSON字符串形式)
JS請(qǐng)求:
//請(qǐng)求數(shù)據(jù),登錄賬號(hào) +密碼 var data = { userAccount: lock_username, userPasswd:hex_md5(lock_password).toUpperCase() } $.ajax({ url : ctx + "/unlock.do", type : "POST", data : JSON.stringify(data), //轉(zhuǎn)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(), "解鎖賬號(hào)為空"); Assert.notNull(user.getUserPasswd(), "解鎖密碼為空"); User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER); Assert.notNull(currentLoginUser, "登錄用戶已過期,請(qǐng)重新登錄!"); Assert.isTrue(StringUtils.equals(user.getUserAccount(),currentLoginUser.getUserAccount()), "解鎖賬號(hào)錯(cuò)誤"); Assert.isTrue(StringUtils.equalsIgnoreCase(user.getUserPasswd(),currentLoginUser.getUserPasswd()), "解鎖密碼錯(cuò)誤"); jsonObject.put("message", "解鎖成功"); jsonObject.put("status", "success"); }catch(Exception ex){ jsonObject.put("message", ex.getMessage()); jsonObject.put("status", "error"); } return jsonObject; }
瀏覽器控制臺(tái)輸出:
5-2: 使用HttpEntity來實(shí)現(xiàn)輸入綁定,來ResponseEntit輸出綁定(POST + JSON字符串形式)
JS請(qǐng)求:
//請(qǐng)求數(shù)據(jù),登錄賬號(hào) +密碼 var data = { userAccount: lock_username, userPasswd:hex_md5(lock_password).toUpperCase() } $.ajax({ url : ctx + "/unlock.do", type : "POST", data : JSON.stringify(data), //轉(zhuǎn)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(), "解鎖賬號(hào)為空"); Assert.notNull(user.getBody().getUserPasswd(), "解鎖密碼為空"); User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER); Assert.notNull(currentLoginUser, "登錄用戶已過期,請(qǐng)重新登錄!"); Assert.isTrue(StringUtils.equals(user.getBody().getUserAccount(),currentLoginUser.getUserAccount()), "解鎖賬號(hào)錯(cuò)誤"); Assert.isTrue(StringUtils.equalsIgnoreCase(user.getBody().getUserPasswd(),currentLoginUser.getUserPasswd()), "解鎖密碼錯(cuò)誤"); 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獲取請(qǐng)求參數(shù),響應(yīng)JSON(POST + JSON對(duì)象形式) 和(GET + 參數(shù)字符串),Controller處理一樣,區(qū)別在于是否加注解method ,
- 如果不加適用GET + POST ;
- 如果 method= RequestMethod.POST,用于POST 請(qǐng)求;
- 如果method=RequestMethod.GET,用于GET請(qǐng)求;
POST+ JSON對(duì)象形式請(qǐng)求:
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 + 參數(shù)字符串請(qǐng)求:
$.ajax({ url : ctx + "/unlock.do", type : "GET", dataType: "text", data : "userAccount="+lock_username+"&userPasswd=" + hex_md5(lock_password).toUpperCase(),//等價(jià)于URL后面拼接參數(shù) 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, "解鎖賬號(hào)為空"); Assert.notNull(userPasswd, "解鎖密碼為空"); User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER); Assert.notNull(currentLoginUser, "登錄用戶已過期,請(qǐng)重新登錄!"); Assert.isTrue(StringUtils.equals(userAccount,currentLoginUser.getUserAccount()), "解鎖賬號(hào)錯(cuò)誤"); Assert.isTrue(StringUtils.equalsIgnoreCase(userPasswd,currentLoginUser.getUserPasswd()), "解鎖密碼錯(cuò)誤"); 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將參數(shù)封裝對(duì)象,響應(yīng)JSON(POST + JSON對(duì)象形式) 和(GET + 參數(shù)字符串),Controller處理一樣,區(qū)別在于是否加注解method 。
- 如果不加適用GET + POST ;
- 如果 method= RequestMethod.POST,用于POST 請(qǐng)求;
- 如果method=RequestMethod.GET,用于GET請(qǐng)求;
POST+ JSON對(duì)象形式請(qǐng)求:
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 + 參數(shù)字符串請(qǐng)求:
$.ajax({ url : ctx + "/unlock.do", type : "GET", dataType: "text", data : "userAccount="+lock_username+"&userPasswd=" + hex_md5(lock_password).toUpperCase(),//等價(jià)于URL后面拼接參數(shù) success : function(result) { console.log(result); } });
Controller處理:(這個(gè)案例只支持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(), "解鎖賬號(hào)為空"); Assert.notNull(user.getUserPasswd(), "解鎖密碼為空"); User currentLoginUser = (User) MvcUtils.getSessionAttribute(Constants.LOGIN_USER); Assert.notNull(currentLoginUser, "登錄用戶已過期,請(qǐng)重新登錄!"); Assert.isTrue(StringUtils.equals(user.getUserAccount(),currentLoginUser.getUserAccount()), "解鎖賬號(hào)錯(cuò)誤"); Assert.isTrue(StringUtils.equalsIgnoreCase(user.getUserPasswd(),currentLoginUser.getUserPasswd()), "解鎖密碼錯(cuò)誤"); jsonObject.put("message", "解鎖成功"); jsonObject.put("status", "success"); }catch(Exception ex){ jsonObject.put("message", ex.getMessage()); jsonObject.put("status", "error"); } printWriter.print(jsonObject.toString()); }
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
Eclipse中創(chuàng)建Web項(xiàng)目最新方法(2023年)
在Java開發(fā)人員中,最常用的開發(fā)工具應(yīng)該就是Eclipse,下面這篇文章主要給大家介紹了關(guān)于Eclipse中創(chuàng)建Web項(xiàng)目2023年最新的方法,需要的朋友可以參考下2023-09-09java web在高并發(fā)和分布式下實(shí)現(xiàn)訂單號(hào)生成唯一的解決方案
這篇文章主要介紹了java web在高并發(fā)和分布式下實(shí)現(xiàn)訂單號(hào)生成唯一的解決方案,需要的朋友可以參考下2017-11-11Dwr3.0純注解(純Java Code配置)配置與應(yīng)用淺析一之零配置文件化
Dwr對(duì)我來說最重要的功能點(diǎn)就是反向Ajax調(diào)用,通俗來將就是后端可以直接調(diào)用前端的JS方法(只要在所能訪問的范圍內(nèi)),這也就是Dwr的真正來由,當(dāng)然它也有最基本的前端直接調(diào)用后端的特性,省去了我們經(jīng)常的一般Ajax調(diào)用2016-04-04MyBatis中的表關(guān)聯(lián)查詢實(shí)現(xiàn)示例
這篇文章主要介紹了MyBatis中的表關(guān)聯(lián)查詢實(shí)現(xiàn)示例,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-01-01解讀jdk動(dòng)態(tài)代理為什么必須實(shí)現(xiàn)接口
這篇文章主要介紹了解讀jdk動(dòng)態(tài)代理為什么必須實(shí)現(xiàn)接口問題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-02-02Eclipse中實(shí)現(xiàn)JS代碼提示功能(圖文教程)
本文通過圖文并茂的形式給大家介紹了Eclipse中實(shí)現(xiàn)JS代碼提示功能,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友參考下吧2017-11-11