本文介绍了springMVC常用的传参方式和一些注意的事项,页面表单主要以ajax的形式提交.
本帅是个菜鸡,水平有限,若有什么讲得不对或有补充的地方欢迎各位提意见。
一、传递String类型
1.controller方法使用String对象作为参数接收
(a) controller
使用controller使用string类型接收,参数名与ajax提交参数名对应即可
@RequestMapping("test")
@ResponseBody
public RespMessage test(String a,String b){
System.out.println(a);
System.out.println(b);
return RespMessage.success();//这个是返回固定格式的响应数据,不用管
}
(b)页面提交代码
var data = {
a:"paramA",
b:"paramB"
}
$.ajax({
"type" : "post",//请求方式
"url" : "test",//请求连接
"dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
//"contentType" : "application/x-www-form-urlencoded;charset=utf-8",
//不要指定contentType,它会自动识别传参类型,设置不对反而会报400
data:data,//请求参数
success : function(data) {}
});
(c)控制台输出
paramA
paramB
2. controller使用bean作为参数接收
(a)TestBean
public class TestBean {
private String a;
private String b;
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
}
(b)controller
ajax提交的参数名需要与TestBean成员对象名对应
@RequestMapping("test")
@ResponseBody
public RespMessage test(TestBean testBean){
System.out.println(testBean.getA());
System.out.println(testBean.getB());
return RespMessage.success();
}
(c)页面提交代码同 "一. 1.(b)"
(d)控制台输出同 " 一. 1.(c)"
3.使用HttpServletRequest接收
(a)controller
@RequestMapping("test3")
@ResponseBody
public RespMessage test(HttpServletRequest request){
System.out.println(request.getParameter("a"));
System.out.println(request.getParameter("b"));
return RespMessage.success();
}
注意:Content-Type不是application/x-www-form-urlencoded的POST请求是不会读取请求体数据和进行相应的参数处理的,即不会解析表单数据来放到request parameter map中。所以通过request.getParameter(name)是获取不到的。
其他同上
二、传递数组
1.使用urlencodeed的形式
(a)页面提交代码
/*var data = {
arr:['a','b','c']
}*///这种方式是不能服务器是接收不到数据的
var data = "arr=a&arr=b&arr=c"
//或者
//var data = "arr=a,b,c";
$.ajax({
"type" : "post",//请求方式
"url" : "test5",//请求连接
"dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
data:data,
success : function(data) {}
});
(b)controller
@RequestMapping("test")
@ResponseBody
public RespMessage test(String[] arr){
for(String a:arr){
System.out.println(a);
}
return RespMessage.success();
}
a
b
c
b
c
(d)顺便一提,我们可以使用jq的serialize()方法将form序列化成
"arr=a&arr=b&arr=c"这样的格式的数据,具体如下:
html部分
<form id="form" action="">
<input type="text" name="arr" value="a">
<input type="text" name="arr" value="b">
<input type="text" name="arr" value="c">
</form>
var data = $("#form").serialize()
//data="arr=a&arr=b&arr=c"
2.利用@RequestBody接收
(a)controller
在参数上加上@RequestBody注解后就可以接收到前端传来的json格式的数据
@RequestMapping("test")
@ResponseBody
public RespMessage test(@RequestBody String[] arr){
for(String a:arr){
System.out.println(a);
}
return RespMessage.success();
}
前端这里要注意的地方有两个,一是jq封装的ajax参数的data这里要传字符串格式的数据,也就是说在传值之前需要调用JSON.stringify()方法将json对象转成字符类型,这并不代表服务器拿到的是字符串,到了服务器那边是json对象,只是前端这里传参需要的是字符串,其内部是怎么转换的还没有进行深入研究。 二是要制定contentType为"application/json"否则会报415错误。
var data = ['a','b','c'];
data = JSON.stringify(data);//这一部很重要,将json对象转成字符串格式
$.ajax({
"type" : "post",//请求方式
"url" : "test6",//请求连接
"contentType" : "application/json;charset=utf-8",//这个时候就必须加contentType
"dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
data:data,
success : function(data) {}
});
(c)控制台输出
a
b
c
b
c
3.使用@RequestParam
这个方法有个不好的地方就是如果这个参数没有传就会报异常
(a)controller
@RequestMapping("test")
@ResponseBody
public RespMessage test(@RequestParam(value = "arr[]") String[] arr){
for(String a:arr){
System.out.println(a);
}
return RespMessage.success();
}
(b)请求页面代码
var data = {
arr:['a','b','c']
}
$.ajax({
"type" : "post",//请求方式
"url" : "test4",//请求连接
"dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
data:data,
success : function(data) {}
});
4.使用formData
(a)controller
@RequestMapping("test5")
@ResponseBody
public RespMessage test2(String[] arr){
for(String a:arr){
System.out.println(a);
}
return RespMessage.success();
}
(b)请求界面代码
var data = new FormData($('#form')[0]);
$.ajax({
"type" : "post",//请求方式
"url" : "test5",//请求连接
processData:false,//必须加否则出错
contentType:false,//必须加否则出错
"dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
data:data,
success : function(data) {}
});
三、传递复杂对象
一般遇到比较复杂的对象就使用@requestBody注解比较方便
1.使用@requestBody
(a)bean
public class TestBean2 {
private String a;
private String b;
private TestBean bean;
private TestBean[] beans;
public TestBean[] getBeans() {
return beans;
}
public void setBeans(TestBean[] beans) {
this.beans = beans;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
public TestBean getBean() {
return bean;
}
public void setBean(TestBean bean) {
this.bean = bean;
}
}
@RequestMapping("test7")
@ResponseBody
public RespMessage test7(@RequestBody TestBean2 test){
return RespMessage.success();
}
(c)请求页面代码
var data = {
a:"paramA",
b:"paramB",
bean:{a:"beanA",b:"beanB"},
beans:[{a:"beansA1",b:"beadsB1"},{a:"beansA2",b:"beadsB2"}]
}
data = JSON.stringify(data);
$.ajax({
"type" : "post",//请求方式
"url" : "test7",//请求连接
"dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
"contentType" : "application/json;charset=utf-8",
data:data,
success : function(data) {}
});
(d)测试结果
2.使用form提交
(a)controller
@RequestMapping("test8")
@ResponseBody
public RespMessage test8(TestBean2 test){
return RespMessage.success();
}
(b)提交页面代码
<form id="form" action="test8" method="post">
<input type="text" name="a" value="paramA">
<input type="text" name="b" value="paramB">
<input type="text" name="bean.a" value="beanA">
<input type="text" name="bean.b" value="beanB">
<input type="text" name="beans[0].a" value="beans0A">
<input type="text" name="beans[0].b" value="beans0B">
</form>
顺便一提:这个也可以通过var data = new FormData($('#form')[0]); 获取formdata对象然后通过ajax提交,具体可以参照二.4这里就不赘述了。
四、传递文件
1.使用form提交
(a)controller
@RequestMapping("test10")
@ResponseBody
public RespMessage test10(MultipartFile file){
try {
file.transferTo(new File("E://".concat(file.getOriginalFilename())));
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return RespMessage.success();
}
(b)提交页面代码
<form id="form" action="test10" method="post" enctype="multipart/form-data">
<input type="file" name="file">
<input type="submit" value="提交">
</form>
这里顺便提供一个带进度条的文件上传方法:
//上传按钮点击
$("#uploadbtn").click(function(){
var files = $("#file")["0"].files;
var len = files.length;
for(var i=0;i<len;i++) {
UpladFile(files[i],i);
}
})
//开始上传
function UpladFile(fileObj,i) {
//bar.fadeIn();
//var fileObj = document.getElementById("file").files[0]; // js 获取文件对象
var FileController = "/cwjgpt/notice/FileUpload.do"; // 接收上传文件的后台地址
// FormData 对象---进行无刷新上传
var form = new FormData();
//form.append("author", "hooyes"); // 可以增加表单数据
form.append("file", fileObj); // 文件对象
// XMLHttpRequest 对象
var xhr = new XMLHttpRequest();
xhr.open("post", FileController, true);
xhr.onload = function() {
//alert("上传完成!");
};
//监听progress事件
xhr.upload.addEventListener("progress",
function(evt){
if (evt.lengthComputable) {
var procce = Math.round(evt.loaded / evt.total * 100);//计算进入百分比
updataprocess(i,procce);//这个是自己写的一个更新进度条的方法,这里你们自己实现然后更新界面的进度条
}
}
, false);
xhr.send(form);
}
以后有在遇到一些以上方法满足不了的情况再继续更新