最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringMVC @ResponseBody 415錯(cuò)誤處理方式

 更新時(shí)間:2021年11月02日 11:24:15   作者:yixiaoping  
這篇文章主要介紹了SpringMVC @ResponseBody 415錯(cuò)誤處理方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(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)JSONPOST + 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)用

    本篇文章小編為大家介紹,基于HttpServletRequest 相關(guān)常用方法的應(yīng)用,需要的朋友參考下
    2013-04-04
  • Spring事務(wù)管理下synchronized鎖失效問(wèn)題的解決方法

    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ū)別詳解

    這篇文章主要介紹了Spring中@Controller和@RestController的區(qū)別詳解,@RestController?是?@Controller?和?@ResponseBody?的結(jié)合體,單獨(dú)使用?@RestController?的效果與?@Controller?和?@ResponseBody?二者同時(shí)使用的效果相同,需要的朋友可以參考下
    2023-10-10
  • idea中l(wèi)ombok的用法

    idea中l(wèi)ombok的用法

    lombok是開(kāi)源的代碼生成庫(kù),是一款非常實(shí)用的小工具,在更改實(shí)體類時(shí)只需要修改屬性即可,減少了很多重復(fù)代碼的編寫工作,今天小編給大家介紹idea中l(wèi)ombok的用法,感興趣的朋友一起看看吧
    2021-12-12
  • 解決springboot mapper注入報(bào)紅問(wèn)題

    解決springboot mapper注入報(bào)紅問(wèn)題

    這篇文章主要介紹了解決springboot mapper注入報(bào)紅問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2021-11-11
  • Spring的事務(wù)管理你了解嗎

    Spring的事務(wù)管理你了解嗎

    這篇文章主要為大家介紹了Spring的事務(wù)管理,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來(lái)幫助
    2022-01-01
  • Java中的封裝性(包含this關(guān)鍵字,構(gòu)造器等)

    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ò)的解決方法

    這篇文章給大家聊聊springboot項(xiàng)目出現(xiàn)同名bean異常報(bào)錯(cuò)如何修復(fù),文中通過(guò)代碼示例給大家介紹解決方法非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作有一定的幫助,需要的朋友可以參考下
    2024-01-01
  • SpringBoot的ResponseEntity類返回給前端具體講解

    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í)分秒格式的示例

    這篇文章主要介紹了java整數(shù)(秒數(shù))轉(zhuǎn)換為時(shí)分秒格式的示例,需要的朋友可以參考下
    2014-04-04

最新評(píng)論

东源县| 华蓥市| 永福县| 富平县| 安塞县| 峡江县| 柯坪县| 桂阳县| 永安市| 筠连县| 二连浩特市| 阜阳市| 成都市| 凯里市| 景洪市| 江川县| 万盛区| 班戈县| 鄂伦春自治旗| 观塘区| 甘肃省| 潼南县| 旅游| 台安县| 即墨市| 福安市| 石家庄市| 手游| 板桥市| 揭西县| 区。| 岑巩县| 千阳县| 大悟县| 江津市| 黔江区| 伊金霍洛旗| 朔州市| 全州县| 木里| 曲靖市|