SpringMVC使用Map或MultiValueMap接收前端提交的Form Data或Query String

在SpringMVC中,可以使用Map或MultiValueMap接收前端提交的Form Data或Query String,省去定义一大堆不同的VO类。直接上代码:


测试中需要依赖到的包:

<dependency>
		<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>4.1.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>4.1.2.RELEASE</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.2.3</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.2.3</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.2.3</version>
		</dependency>


测试代码:

/**
 * 测试用Map接收参数
 * @author Xu
 *
 */
@RestController
@RequestMapping(value = "/mapParameter/")
public class MapParameter {
	
	/**
	 * 用Map接收前端提交的Form Data或Query String,如果有相同的参数名,只接收第一个
	 * @author XuJijun
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "map")
	public Map<String, Object> test1(@RequestParam Map<String, Object> params) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap = params;
		return resultMap;
	}
	
	/**
	 * 用MultiValueMap接收前端提交的Form Data或Query String,可以接收相同的参数名的值到同一个list中
	 * @author XuJijun
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "multiValueMap")
	public Map<String, List<Object>> test2(@RequestParam MultiValueMap<String, Object> params) {
		Map<String, List<Object>> resultMap = new HashMap<>();
		resultMap = params;
		return resultMap;
	}
	
	/**
	 * 用Map接收前端提交的json格式的Request Payload,如果有相同的参数名,只接收最后一个
	 * @author XuJijun
	 * @param params
	 * @return
	 */
	@RequestMapping(value = "jsonParams")
	public Map<String, Object> test3(@RequestBody Map<String, Object> params) {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		resultMap = params;
		return resultMap;
	}
}

测试结果:

SpringMVC使用Map或MultiValueMap接收前端提交的Form Data或Query String_第1张图片



你可能感兴趣的:(java,Web,springMVC)