Spring MVC @RequestBody

作者:範宗雲 来源:原创 发布时间:2015-03-24 归档:springmvc

开发环境 : JDK 7 Maven 3 Tomcat 7 Spring 4.1.5 Eclipse Luna
@RequestBody 注解表明处理方法的参数的值是绑定到 Http Request Body, 处理方法执行时从 Http Request Body 中读取绑定的数据到参数。
示例代码片段 1 ( pojo )
			@Controller
			@RequestMapping("/product")
			public class ProductController {
			
				@RequestMapping(value = "/add", method = POST)
				public String addProduct(@RequestBody Product product) {
					System.out.println(product);
					return LIST_PAGE;
				}

				public static class Product {
			
					private int id;
					private String name;
					private double price;
			
					public Product() {
			
					}
			
					public Product(int id, String name, double price) {
						this.id = id;
						this.name = name;
						this.price = price;
					}
			
					// ignore getters and setters

					@Override
					public String toString() {
						return id + "  " + name + "  " + price;
					}
			
				}
			
			}
			
			<p>
		      <textarea disabled="disabled">
		        {"id":1001,"name":"戴尔-XPS-13(XPS13D-9343-1508)笔记本","price":6999.0}
		      </textarea>
		      <button>add</button>
		    </p>
		    <script type="text/javascript">
		    $(function(){
		    	$("button").click(function(){
		    		var button = $(this);
		    		$.ajax({
		    			type : "post",
		    			url  : "product/" + button.text(),
		    			data : button.parent().find("textarea").val(),
		    			contentType : "application/json",
		    			success : function() {
		    				alert("well, now you can see the execution result on the console");
		    			}
		    		});
		    	});
		    });
		    </script>
			
示例代码片段 2 ( list )
			@Controller
			@RequestMapping("/product")
			public class ProductController {
			
				@RequestMapping(value = "/addSerial", method = POST)
				public String addSerialProduct(@RequestBody List<Product> list) {
					for(Product product : list) {
						System.out.println(product);
					}
					return LIST_PAGE;
				}
			
			}
			
			<p>
		      <textarea disabled="disabled">
		        [{"id":1001,"name":"戴尔-XPS-13(XPS13D-9343-1508)笔记本","price":6999.0},
		        {"id":1002,"name":"戴尔-XPS-13(XPS13D-9343-1708)笔记本","price":8999.0}]
		      </textarea>
		      <button>addSerial</button>
		    </p>
			
示例代码片段 3 ( map )
			@Controller
			@RequestMapping("/product")
			public class ProductController {
			
				@RequestMapping(value = "/addBrand", method = POST)
				public String addBrandProduct(@RequestBody Map<String, Product> map) {
					System.out.println(map.get("dell"));
					return LIST_PAGE;
				}
			
			}
			
			<p>
		      <textarea disabled="disabled">
		        {"dell":{"id":1003,"name":"戴尔-XPS-13(XPS13D-9343-1808T)笔记本","price":13000.0}}
		      </textarea>
		      <button>addBrand</button>
		    </p>
			
不要忘记引入依赖
		    <dependency>
		      <groupId>com.fasterxml.jackson.core</groupId>
		      <artifactId>jackson-databind</artifactId>
		      <version>2.4.1</version>
		    </dependency>
		    

示例代码下载
spring-mvc-request-body.zip