本文将阐述如何将前端页面数据传递到后台java代码。
1、环境约束
win10 64位操作系统
idea2018.1.5
jdk-8u162-windows-x64
spring4.2.4
前提约束
操作步骤
基本类型传输
@RequestMapping("/user/test1")
@ResponseBody
public String userTest1(int id,String name)
{
return id+"~"+name;
}
Pojo传输【要先确认有实体类User,实体类当中有id、name】
@RequestMapping("/user/test2")
@ResponseBody
public String userTest2(User user)
{
return user.getId()+"~"+user.getName();
}
RequestParam传输
@RequestMapping("/user/test3")
@ResponseBody
public String userTest3(@RequestParam("name") String name1)
{
return name1;
}
PathVariable传输
@RequestMapping("/user/test4/{name}/{id}")
@ResponseBody
public String userTest4(@PathVariable("name") String name1,@PathVariable("id") int id1)
{
return name1+id1;
}
RequestHeader传输
@RequestMapping("/user/test5")
@ResponseBody
public String userTest5(@RequestHeader(name="age") int age )
{
return age+"ali";
}
Servletapi传输
@RequestMapping(value = "/user/test6")
@ResponseBody
public void userTest6(HttpServletRequest request,HttpServletResponse response) throws IOException {
String name = request.getParameter("name");
return name;
}
json 数组传输 创建index.html,内容如下:
Title
var data=["jiangsu","wanhe","it"];
$.ajax({
headers:{'Content-Type':'application/json'},
data:JSON.stringify(data),
dataType:"json",
type:"post",
url:"/user/test7",
success:function (data) {
alert(data);
}
});
创建接收方法,内容如下:
@RequestMapping(value = "/user/test7",method = RequestMethod.POST)
@ResponseBody
public JSONObject userTest7(@RequestBody String[] names)
{
JSONObject jsonpObject = new JSONObject();
jsonpObject.put("data",Arrays.toString(names));
return jsonpObject;
}
json List传输 创建index1.html,内容如下:
Title
var data = [{id:123,name:'ali'},{id:123,name:'ali'},{id:123,name:'ali'}]
$.ajax({
headers: {
'Content-Type': 'application/json'
},
data:JSON.stringify(data),
dataType:"json",
type:"post",
url:"/user/test8",
success:function(data)
{
alert(data)
}
});
创建接收方法,内容如下:
@RequestMapping(value = "/user/test8",method = RequestMethod.POST)
@ResponseBody
public JSONObject userTest7(@RequestBody List names)
{
JSONObject jsonpObject = new JSONObject();
jsonpObject.put("data",names);
return jsonpObject;
}
json Map传输 创建index2.html,内容如下:
Title
var data = {"3":"ze","2":"bing","1":"zhi","5":"4","4":"1"};
$.ajax({
headers: {
'Content-Type': 'application/json'
},
data:JSON.stringify(data),
dataType:"json",
type:"post",
url:"/user/test9",
success:function(data)
{
alert(data)
}
});
创建测试方法,内容如下:
@RequestMapping(value = "/user/test9",method = RequestMethod.POST)
@ResponseBody
public JSONObject userTest8(@RequestBody Map map)
{
JSONObject jsonpObject = new JSONObject();
jsonpObject.put("data",map);
return jsonpObject;
}