Spring @RequestBody 传递 List/Map 参数

时间:2022-05-03
本文章向大家介绍Spring @RequestBody 传递 List/Map 参数,主要内容包括本文节选自电子书《Netkiller Java 手札》、6.1.4. @RequestBody、6.1.4.2. 传递 Map 数据、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

本文节选自电子书《Netkiller Java 手札》

6.1.4. @RequestBody

处理 raw 原始数据,例如提交的时 application/json, application/xml等

		@RequestMapping(value = "/something", method = RequestMethod.PUT)  
public void handle(@RequestBody String body, Writer writer) throws IOException {  
	writer.write(body);  
} 

6.1.4.1. @RequestBody 传递 List

			package cn.netkiller.api.restful;

import java.util.List;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class TestRestController {

	@RequestMapping(value = "/test/list/{siteId}", method = RequestMethod.POST)
	public List<String> ping(@PathVariable("siteId") int siteId, @RequestBody List<String> tags) {
		System.out.println(String.format("%d, %s", siteId, tags));
		return (tags);
	}

}			
			$ curl -H "Content-Type: application/json" -X POST -d '["Neo","Netkiller"]' http://localhost:8440/test/list/22.json 

["Neo","Netkiller"]	

6.1.4.2. 传递 Map 数据

	@PostMapping("/finance/list")
	public String financeList(@RequestBody Map<String,String> map) {
		return financeService.financeList(map);
	}			
			% curl -H "Content-Type: application/json" -X POST -d '{"date":"2017-11-08"}' http://localhost:8440/finance/list.json