springmvc中的RequestBody自動注入List, Map, String資料結構的資料
阿新 • • 發佈:2019-02-09
不說廢話,直接上程式碼:
1. JS:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="application/javascript" src="//cdn.bootcss.com/jquery/3.0.0-beta1/jquery.js"></script> <script type="application/javascript"> $(function(){ var user = {} var arr = new Array(); arr.push(1); arr.push(2); var map = {a: 123, b:898}; user.name = "張三"; user.map = map; user.list = arr;var data = JSON.stringify(user); console.log(data); $.ajax({ type:'POST', url:'/bb/aj', data:data, contentType: 'application/json', success:function(data){ alert(data) } }) }) </script> </head> <body class="showmenu"> travel-web1 </body> </html>
2. User-Bean
package com.bilibili.travel.model; import com.bilibili.base.BaseEntity; import java.util.List; import java.util.Map; /** * Created by bls on 16-4-30. */ public class User extends BaseEntity { private String name = null; private Map<String, Object> map = null; private List<String> list = null; public String getName() { return name; } public void setName(String name) { this.name = name; } public Map<String, Object> getMap() { return map; } public void setMap(Map<String, Object> map) { this.map = map; } public List<String> getList() { return list; } public void setList(List<String> list) { this.list = list; } @Override public String toString() { return "User{" + "name='" + name + '\'' + ", map=" + map + ", list=" + list + '}'; } }
3. Controller
import com.bilibili.travel.model.User; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * Created by bls on 16-4-30. */ @Controller @RequestMapping(value = "/bb") public class BBController extends BaseSpringController { @ResponseBody @RequestMapping(value = "/aj") public User addJson(@RequestBody User user){ System.out.println(user); return user; } }
以上,如果對你有幫助。請為我點贊,謝謝。