SpringMVC @ResponseBody 415錯(cuò)誤處理方式
閑話少說(shuō),剛開(kāi)始用SpringMVC, 頁(yè)面要使用jquery的ajax請(qǐng)求Controller。 但總是失敗,
主要表現(xiàn)為以下兩個(gè)異常為:
異常一:java.lang.ClassNotFoundException: org.springframework.http.converter.json.MappingJacksonHttpMessageConverter
異常二:SpringMVC @ResponseBody 415錯(cuò)誤處理
網(wǎng)上分析原因很多,但找了很久都沒(méi)解決,基本是以下幾類:
- springmvc添加配置、注解;
- pom.xml添加jackson包引用;
- Ajax請(qǐng)求時(shí)沒(méi)有設(shè)置Content-Type為application/json
- 發(fā)送的請(qǐng)求內(nèi)容不要轉(zhuǎn)成JSON對(duì)象,直接發(fā)送JSON字符串即可
這些其實(shí)都沒(méi)錯(cuò)?。?!
以下是我分析的解決步驟方法
1、springMVC配置文件開(kāi)啟注解
<!-- 開(kāi)啟注解-->
<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>
這里要說(shuō)明一下,spring3.x用的是org.codehaus.jackson的1.x版本,在maven資源庫(kù),已經(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來(lái)設(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, "登錄用戶已過(guò)期,請(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來(lái)實(shí)現(xiàn)輸入綁定,來(lái)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, "登錄用戶已過(guò)期,請(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, "登錄用戶已過(guò)期,請(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, "登錄用戶已過(guò)期,請(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)文章
基于HttpServletRequest 相關(guān)常用方法的應(yīng)用
本篇文章小編為大家介紹,基于HttpServletRequest 相關(guān)常用方法的應(yīng)用,需要的朋友參考下2013-04-04
Spring事務(wù)管理下synchronized鎖失效問(wèn)題的解決方法
這篇文章主要給大家介紹了關(guān)于Spring事務(wù)管理下synchronized鎖失效問(wèn)題的解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用Spring具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2022-03-03
Spring中@Controller和@RestController的區(qū)別詳解
這篇文章主要介紹了Spring中@Controller和@RestController的區(qū)別詳解,@RestController?是?@Controller?和?@ResponseBody?的結(jié)合體,單獨(dú)使用?@RestController?的效果與?@Controller?和?@ResponseBody?二者同時(shí)使用的效果相同,需要的朋友可以參考下2023-10-10
解決springboot mapper注入報(bào)紅問(wèn)題
這篇文章主要介紹了解決springboot mapper注入報(bào)紅問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
Java中的封裝性(包含this關(guān)鍵字,構(gòu)造器等)
這篇文章主要介紹了Java中的封裝性(包含this關(guān)鍵字,構(gòu)造器等)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2024-03-03
springboot項(xiàng)目中出現(xiàn)同名bean異常報(bào)錯(cuò)的解決方法
這篇文章給大家聊聊springboot項(xiàng)目出現(xiàn)同名bean異常報(bào)錯(cuò)如何修復(fù),文中通過(guò)代碼示例給大家介紹解決方法非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下2024-01-01
SpringBoot的ResponseEntity類返回給前端具體講解
這篇文章主要給大家介紹了關(guān)于SpringBoot的ResponseEntity類返回給前端的相關(guān)資料,ResponseEntity是Spring框架中用于封裝HTTP響應(yīng)的類,可以自定義狀態(tài)碼、響應(yīng)頭和響應(yīng)體,常用于控制器方法中返回特定數(shù)據(jù)的HTTP響應(yīng),需要的朋友可以參考下2024-11-11
java整數(shù)(秒數(shù))轉(zhuǎn)換為時(shí)分秒格式的示例
這篇文章主要介紹了java整數(shù)(秒數(shù))轉(zhuǎn)換為時(shí)分秒格式的示例,需要的朋友可以參考下2014-04-04

