溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

SpringMVC @RequestBody的使用分析

發(fā)布時間:2021-11-05 11:08:36 來源:億速云 閱讀:343 作者:iii 欄目:開發(fā)技術

這篇文章主要介紹“SpringMVC @RequestBody的使用分析”,在日常操作中,相信很多人在SpringMVC @RequestBody的使用分析問題上存在疑惑,小編查閱了各式資料,整理出簡單好用的操作方法,希望對大家解答”SpringMVC @RequestBody的使用分析”的疑惑有所幫助!接下來,請跟著小編一起來學習吧!

SpringMVC @RequestBody的使用

Spring mvc是一個非常輕量的mvc框架,注解可以大大減少配置,讓請求的攔截變得比較簡單。這次記錄下@RequestBody 注解接收參數(shù)尤其是數(shù)組參數(shù)的用法。

關于容器的配置不再多說,這里寫出spring-servlet.xml的sechme:

<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:task="http://www.springframework.org/schema/task"
 xsi:schemaLocation="http://www.springframework.org/schema/context    
          http://www.springframework.org/schema/context/spring-context-4.0.xsd    
          http://www.springframework.org/schema/beans    
          http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
          http://www.springframework.org/schema/mvc
          http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.0.xsd">
          <!-- 掃描包注解 -->
 <context:component-scan base-package="xxxx"></context:component-scan>
 <!-- mvc注解功能啟動 -->
 <mvc:annotation-driven />
</beans>

只要對應包名下面的添加注解即可掃描到對應的控制器,一般采用@Controller

RequestBody接收基本類型

@Controller
public class TestController {
 // url請求攔截
 @RequestMapping("test/test.do")
 @ResponseBody // 返回參數(shù)為JSON
 public void test(@RequestBody String name) {
  System.out.println("getParams : " + name);
 }![這里寫圖片描述](https://img-blog.csdn.net/20161114115809292)
}

@RequestBody只要接收POST請求Body里的數(shù)據(jù)。

SpringMVC @RequestBody的使用分析

這樣發(fā)送請求,即可在java控制臺中打?。?/p>

getParams : {"name":"micro"}

@RequestBody接收基本數(shù)組

然后我們接收基本類型數(shù)組:

	@RequestMapping("test/test.do")
	@ResponseBody
	public void test(@RequestBody List<String> nameList) {
		System.out.println("getParams : " + nameList);
	}

SpringMVC @RequestBody的使用分析

這樣即可獲取到參數(shù),不要body里寫成了{“nameList”:[“name1”,“name2”]}這樣會拋出異常。

@RequestBody是對應的POST請求的body,body即是獲取的參數(shù),如果想通過參數(shù)去獲取,則要使用@RequestParams 注解:

	@RequestMapping("test/test.do")
	@ResponseBody
	public void test(@RequestParam("name") String name) {
		System.out.println("getParams : " + name);
	}

SpringMVC @RequestBody的使用分析

注意是GET請求,參數(shù)直接放到URL后面,這樣就可以使用@RequestParams獲取到對應參數(shù)名的參數(shù)值。如果是復雜的對象。

@RequestBody的使用。

定義model:

class Person {
	private Long id;
	private String name;
	// setter getter
}

@RequestBody接收復雜對象

接收參數(shù)的方式

@RequestMapping("test/test.do")
	@ResponseBody
	public void test(@RequestBody Person person) {
		System.out.println("getParams : " + person.getId() + " ," + person.getName());
	}

即可獲取到參數(shù),body里的參數(shù)會自動匹配到person的屬性并賦值。

注意名字要與對象的屬性變量名一致。否則獲取不到參數(shù),例如這里就不能在body里寫成{“i”:1,“name”:“micro”},這樣獲取到person的id為null。

@RequestBody接收復雜對象數(shù)組

如果是復雜對象數(shù)組:

	@RequestMapping("test/test.do")
	@ResponseBody
	public void test(@RequestBody List<Person> personList) {
		for (Person p : personList) {
			System.out.println(p.getId() + " ," + p.getName());
		}
	}

請求方式如下,注意body里的格式是[]數(shù)組。

SpringMVC @RequestBody的使用分析

控制臺打印:

1 ,micro

2 ,micro2

即完成了@RequestBody接收各種類型的參數(shù)。

@RequestBody使用的一些注意事項

眾所周知,springmvc中@RequestBody的注解是一個很實用的功能,它能幫我們解析客戶端(移動設備、瀏覽器等)發(fā)送過來的json數(shù)據(jù),并封裝到實體類中。

但我今天要說的不是它的原理,而是記錄一些工作中使用@RequestBody注解遇到的一些問題,也提醒廣大java開發(fā)者避免類似的問題。

最近有個需求,接收客戶的設備發(fā)送過來的json數(shù)據(jù),客戶的設備里面只能修改ip,然后通過http協(xié)議的post方式發(fā)送數(shù)據(jù)過來。我很自然地想到在登錄頁那里處理,在toLogin方法中增加@RequestBody Kehu kehu參數(shù),用戶解析并封裝json數(shù)據(jù)。

廢話不多說,上代碼,如下所示:

@RequestMapping(value = "/toLogin")
	public ModelAndView toLogin(HttpServletRequest request, @RequestBody Kehu kehu) throws Exception {
		// 接收客戶設備發(fā)送過來的json數(shù)據(jù)
		if (kehu != null && !StringUtil.isEmpty(kehu.cmd)) {
			uploadData(kehu);
		}
		ModelAndView mv = new ModelAndView();
		PageData pageData = this.getPageData(request);
		pageData.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); // 讀取系統(tǒng)名稱
		mv.setViewName("base/login");
		mv.addObject("pd", pageData);
		return mv;
	}

一切看似很完美,在瀏覽器上測試一下,輸入localhost(我的項目已經(jīng)設置為了缺省項目,端口號也改為了80)

我傻眼了,報了400錯誤。如下圖所示:

SpringMVC @RequestBody的使用分析

The request sent by the client was syntactically incorrect.

翻譯過來就是:客戶端發(fā)送的請求在語法上是不正確的。

沒加@RequestBody Kehu kehu之前是正常的,問題肯定出在了這里。我一看RequestBody的源碼:

package org.springframework.web.bind.annotation; 
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target; 
import org.springframework.http.converter.HttpMessageConverter;
 
/**
 * Annotation indicating a method parameter should be bound to the body of the web request.
 * The body of the request is passed through an {@link HttpMessageConverter} to resolve the
 * method argument depending on the content type of the request. Optionally, automatic
 * validation can be applied by annotating the argument with {@code @Valid}.
 *
 * <p>Supported for annotated handler methods in Servlet environments.
 *
 * @author Arjen Poutsma
 * @since 3.0
 * @see RequestHeader
 * @see ResponseBody
 * @see org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
 * @see org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter
 */
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestBody {
 
	/**
	 * Whether body content is required.
	 * <p>Default is {@code true}, leading to an exception thrown in case
	 * there is no body content. Switch this to {@code false} if you prefer
	 * {@code null} to be passed when the body content is {@code null}.
	 * @since 3.2
	 */
	boolean required() default true;
 
}

required方法默認返回值是true。

這樣問題就明朗了,我請求localhost的時候,沒有傳json過去,所以就會報400錯誤,因為客戶端發(fā)送的請求在語法上是不正確的。

解決方法:在@RequestBody后面加上(required=false)就可以了。表示kehu對象可以不傳入。

/**
	 * 訪問登錄頁
	 * @RequestBody(required=false)	表示kehu對象可以不傳入。
	 * 一定要加上required=false,否則登錄的時候會報400錯誤。錯誤代碼:
	 * The request sent by the client was syntactically incorrect.
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/toLogin")
	public ModelAndView toLogin(HttpServletRequest request, @RequestBody(required=false) Kehu kehu) throws Exception {
		// 接收硬幣機發(fā)送過來的json數(shù)據(jù)
		if (kehu != null && !StringUtil.isEmpty(kehu.cmd)) {
			uploadData(kehu);
		}
		ModelAndView mv = new ModelAndView();
		PageData pageData = this.getPageData(request);
		pageData.put("SYSNAME", Tools.readTxtFile(Const.SYSNAME)); // 讀取系統(tǒng)名稱
		mv.setViewName("base/login");
		mv.addObject("pd", pageData);
		return mv;
	}

到此,關于“SpringMVC @RequestBody的使用分析”的學習就結(jié)束了,希望能夠解決大家的疑惑。理論與實踐的搭配能更好的幫助大家學習,快去試試吧!若想繼續(xù)學習更多相關知識,請繼續(xù)關注億速云網(wǎng)站,小編會繼續(xù)努力為大家?guī)砀鄬嵱玫奈恼拢?/p>

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI