本文介绍了springMVC常用的传参方式和一些注意的事项,页面表单主要以ajax的形式提交.

本帅是个菜鸡,水平有限,若有什么讲得不对或有补充的地方欢迎各位提意见。

一、传递String类型

 

1.controller方法使用String对象作为参数接收

 

(a) controller

使用controller使用string类型接收,参数名与ajax提交参数名对应即可

  1. @RequestMapping("test")
  2. @ResponseBody
  3. public RespMessage test(String a,String b){
  4. System.out.println(a);
  5. System.out.println(b);
  6. return RespMessage.success();//这个是返回固定格式的响应数据,不用管
  7. }

(b)页面提交代码

  1. var data = {
  2. a:"paramA",
  3. b:"paramB"
  4. }
  5. $.ajax({
  6. "type" : "post",//请求方式
  7. "url" : "test",//请求连接
  8. "dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
  9. //"contentType" : "application/x-www-form-urlencoded;charset=utf-8",
  10. //不要指定contentType,它会自动识别传参类型,设置不对反而会报400
  11. data:data,//请求参数
  12. success : function(data) {}
  13. });

(c)控制台输出

paramA
paramB

2. controller使用bean作为参数接收

 

(a)TestBean

  1. public class TestBean {
  2. private String a;
  3. private String b;
  4. public String getA() {
  5. return a;
  6. }
  7. public void setA(String a) {
  8. this.a = a;
  9. }
  10. public String getB() {
  11. return b;
  12. }
  13. public void setB(String b) {
  14. this.b = b;
  15. }
  16. }

(b)controller

ajax提交的参数名需要与TestBean成员对象名对应

  1. @RequestMapping("test")
  2. @ResponseBody
  3. public RespMessage test(TestBean testBean){
  4. System.out.println(testBean.getA());
  5. System.out.println(testBean.getB());
  6. return RespMessage.success();
  7. }

(c)页面提交代码同 "一. 1.(b)"

(d)控制台输出同 " 一. 1.(c)"

3.使用HttpServletRequest接收

 
(a)controller
 
  1. @RequestMapping("test3")
  2. @ResponseBody
  3. public RespMessage test(HttpServletRequest request){
  4. System.out.println(request.getParameter("a"));
  5. System.out.println(request.getParameter("b"));
  6. return RespMessage.success();
  7. }

注意:Content-Type不是application/x-www-form-urlencoded的POST请求是不会读取请求体数据和进行相应的参数处理的,即不会解析表单数据来放到request parameter map中。所以通过request.getParameter(name)是获取不到的。

 
其他同上
 
 

二、传递数组

 

1.使用urlencodeed的形式

 
(a)页面提交代码
 
  1. /*var data = {
  2. arr:['a','b','c']
  3. }*///这种方式是不能服务器是接收不到数据的
  4. var data = "arr=a&arr=b&arr=c"
  5. //或者
  6. <span style="font-family:Arial, Helvetica, sans-serif;">//</span><span style="font-family:Arial, Helvetica, sans-serif;">var data = "arr=a,b,c";</span>
  7. $.ajax({
  8. "type" : "post",//请求方式
  9. "url" : "test5",//请求连接
  10. "dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
  11. data:data,
  12. success : function(data) {}
  13. });
(b)controller
 
  1. @RequestMapping("test")
  2. @ResponseBody
  3. public RespMessage test(String[] arr){
  4. for(String a:arr){
  5. System.out.println(a);
  6. }
  7. return RespMessage.success();
  8. }
 

(c)控制台输出

a
b
c

(d)顺便一提,我们可以使用jq的serialize()方法将form序列化成"arr=a&arr=b&arr=c"这样的格式的数据,具体如下:
 
html部分
  1. <form id="form" action="">
  2. <input type="text" name="arr" value="a">
  3. <input type="text" name="arr" value="b">
  4. <input type="text" name="arr" value="c">
  5. </form>
 

js部分

  1. var data = $("#form").serialize()
  2. //data="arr=a&arr=b&arr=c"

2.利用@RequestBody接收

 
(a)controller
 
在参数上加上@RequestBody注解后就可以接收到前端传来的json格式的数据
 
  1. @RequestMapping("test")
  2. @ResponseBody
  3. public RespMessage test(@RequestBody String[] arr){
  4. for(String a:arr){
  5. System.out.println(a);
  6. }
  7. return RespMessage.success();
  8. }
 

(b)页面提交代码

 
前端这里要注意的地方有两个,一是jq封装的ajax参数的data这里要传字符串格式的数据,也就是说在传值之前需要调用JSON.stringify()方法将json对象转成字符类型,这并不代表服务器拿到的是字符串,到了服务器那边是json对象,只是前端这里传参需要的是字符串,其内部是怎么转换的还没有进行深入研究。 二是要制定contentType为"application/json"否则会报415错误。
 
  1. var data = ['a','b','c'];
  2. data = JSON.stringify(data);//这一部很重要,将json对象转成字符串格式
  3. $.ajax({
  4. "type" : "post",//请求方式
  5. "url" : "test6",//请求连接
  6. "contentType" : "application/json;charset=utf-8",//这个时候就必须加contentType
  7. "dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
  8. data:data,
  9. success : function(data) {}
  10. });
(c)控制台输出
a
b
c
 

3.使用@RequestParam

这个方法有个不好的地方就是如果这个参数没有传就会报异常
 
(a)controller
 
  1. @RequestMapping("test")
  2. @ResponseBody
  3. public RespMessage test(@RequestParam(value = "arr[]") String[] arr){
  4. for(String a:arr){
  5. System.out.println(a);
  6. }
  7. return RespMessage.success();
  8. }

(b)请求页面代码

 
  1. var data = {
  2. arr:['a','b','c']
  3. }
  4. $.ajax({
  5. "type" : "post",//请求方式
  6. "url" : "test4",//请求连接
  7. "dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
  8. data:data,
  9. success : function(data) {}
  10. });

4.使用formData

 
(a)controller
 
  1. @RequestMapping("test5")
  2. @ResponseBody
  3. public RespMessage test2(String[] arr){
  4. for(String a:arr){
  5. System.out.println(a);
  6. }
  7. return RespMessage.success();
  8. }

(b)请求界面代码

 
  1. var data = new FormData($('#form')[0]);
  2. $.ajax({
  3. "type" : "post",//请求方式
  4. "url" : "test5",//请求连接
  5. processData:false,//必须加否则出错
  6. contentType:false,//必须加否则出错
  7. "dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
  8. data:data,
  9. success : function(data) {}
  10. });

三、传递复杂对象

 
一般遇到比较复杂的对象就使用@requestBody注解比较方便
 
 

1.使用@requestBody

 
 
(a)bean
 
 
  1. public class TestBean2 {
  2. private String a;
  3. private String b;
  4. private TestBean bean;
  5. private TestBean[] beans;
  6. public TestBean[] getBeans() {
  7. return beans;
  8. }
  9. public void setBeans(TestBean[] beans) {
  10. this.beans = beans;
  11. }
  12. public String getA() {
  13. return a;
  14. }
  15. public void setA(String a) {
  16. this.a = a;
  17. }
  18. public String getB() {
  19. return b;
  20. }
  21. public void setB(String b) {
  22. this.b = b;
  23. }
  24. public TestBean getBean() {
  25. return bean;
  26. }
  27. public void setBean(TestBean bean) {
  28. this.bean = bean;
  29. }
  30. }
 

(b)controller

 
 
  1. @RequestMapping("test7")
  2. @ResponseBody
  3. public RespMessage test7(@RequestBody TestBean2 test){
  4. return RespMessage.success();
  5. }

(c)请求页面代码

 
 
  1. var data = {
  2. a:"paramA",
  3. b:"paramB",
  4. bean:{a:"beanA",b:"beanB"},
  5. beans:[{a:"beansA1",b:"beadsB1"},{a:"beansA2",b:"beadsB2"}]
  6. }
  7. data = JSON.stringify(data);
  8. $.ajax({
  9. "type" : "post",//请求方式
  10. "url" : "test7",//请求连接
  11. "dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
  12. "contentType" : "application/json;charset=utf-8",
  13. data:data,
  14. success : function(data) {}
  15. });
 
 
(d)测试结果
 
 
 

2.使用form提交

(a)controller

  1. @RequestMapping("test8")
  2. @ResponseBody
  3. public RespMessage test8(TestBean2 test){
  4. return RespMessage.success();
  5. }

(b)提交页面代码

  1. <form id="form" action="test8" method="post">
  2. <input type="text" name="a" value="paramA">
  3. <input type="text" name="b" value="paramB">
  4. <input type="text" name="bean.a" value="beanA">
  5. <input type="text" name="bean.b" value="beanB">
  6. <input type="text" name="beans[0].a" value="beans0A">
  7. <input type="text" name="beans[0].b" value="beans0B">
  8. </form>

顺便一提:这个也可以通过var data = new FormData($('#form')[0]);获取formdata对象然后通过ajax提交,具体可以参照二.4这里就不赘述了。

四、传递文件

 

1.使用form提交

 
(a)controller
 
 
  1. @RequestMapping("test10")
  2. @ResponseBody
  3. public RespMessage test10(MultipartFile file){
  4. try {
  5. file.transferTo(new File("E://".concat(file.getOriginalFilename())));
  6. } catch (IllegalStateException e) {
  7. e.printStackTrace();
  8. } catch (IOException e) {
  9. e.printStackTrace();
  10. }
  11. return RespMessage.success();
  12. }

(b)提交页面代码

 
  1. <form id="form" action="test10" method="post" enctype="multipart/form-data">
  2. <input type="file" name="file">
  3. <input type="submit" value="提交">
  4. </form>
 

顺便一提:文件上传同样可以使用formdata对象使用ajax进行提交,具体参考上面的步骤,这里就不赘述了。

 
这里顺便提供一个带进度条的文件上传方法:
 
  1. //上传按钮点击
  2. $("#uploadbtn").click(function(){
  3. var files = $("#file")["0"].files;
  4. var len = files.length;
  5. for(var i=0;i<len;i++) {
  6. UpladFile(files[i],i);
  7. }
  8. })
  9. //开始上传
  10. function UpladFile(fileObj,i) {
  11. //bar.fadeIn();
  12. //var fileObj = document.getElementById("file").files[0]; // js 获取文件对象
  13. var FileController = "/cwjgpt/notice/FileUpload.do"; // 接收上传文件的后台地址
  14. // FormData 对象---进行无刷新上传
  15. var form = new FormData();
  16. //form.append("author", "hooyes"); // 可以增加表单数据
  17. form.append("file", fileObj); // 文件对象
  18. // XMLHttpRequest 对象
  19. var xhr = new XMLHttpRequest();
  20. xhr.open("post", FileController, true);
  21. xhr.onload = function() {
  22. //alert("上传完成!");
  23. };
  24. //监听progress事件
  25. xhr.upload.addEventListener("progress",
  26. function(evt){
  27. if (evt.lengthComputable) {
  28. var procce = Math.round(evt.loaded / evt.total * 100);//计算进入百分比
  29. updataprocess(i,procce);//这个是自己写的一个更新进度条的方法,这里你们自己实现然后更新界面的进度条
  30. }
  31. }
  32. , false);
  33. xhr.send(form);
  34. }

项目中传参总结:

1、后台Controller通过request转对象
(1)前台ajax请求:
var param = {
"receiver_name": $("#receiver_name").val().trim(),
"province_code": $("#i_province").find("option:selected").val(),
"city_code": $("#i_cityCode").find("option:selected").val(),
"district_code": $("#i_areaCode").find("option:selected").val(),
"province_name": $("#i_province").find("option:selected").text(),
"city_name": $("#i_cityCode").find("option:selected").text(),
"district_name": $("#i_areaCode").find("option:selected").text(),
"address": $("#address").val().trim(),
"print_address":$("#print_address").val().trim(),
"contact_phone": $("#contact_phone").val(),
"default_address": $("#default_address").is(":checked")?1:0,
"purchaser":$("#purchaser").val().trim(),
"purchaser_phone":$("#purchaser_phone").val().trim()
};
$.ajax({
url: ctx + "/address/saveAddress",
data: param,
type: 'post',
dataType: 'json',
success: function(data) {
if(data.state == "success"){
doQuery();
$('#main-content').hideLoading();
}else if(data.state == "many"){
$('#main-content').hideLoading();
alertModal("保存失败,收货地址最多为10个!");
}else{
$('#main-content').hideLoading();
alertModal("保存异常,请联系管理员!");
}
}
});
(2)后台接受并处理请求
UsermanageReceiverAddress receAddress = Request2MapUtil.wrapBean(UsermanageReceiverAddress.class, request);
Map params = Request2MapUtil.wrapMap(request);
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
// package com.yaoex.framework.core.util; import java.beans.PropertyDescriptor;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl; public class Request2MapUtil {
public Request2MapUtil() {
} private static Object convertType(String classType, String value) {
if(value == null) {
return null;
} else {
try {
if(classType.equals("java.lang.String")) {
return value.trim();
} else if(classType.equals("java.lang.Integer")) {
return Integer.valueOf(value);
} else if(classType.equals("java.lang.Long")) {
return Long.valueOf(value);
} else if(classType.equals("java.lang.Float")) {
return Float.valueOf(value);
} else if(classType.equals("java.lang.Double")) {
return Double.valueOf(value);
} else if(classType.equals("java.math.BigDecimal")) {
return new BigDecimal(value);
} else {
SimpleDateFormat formatter;
if(classType.equals("java.util.Date")) {
if(value.length() == 10) {
formatter = new SimpleDateFormat("yyyy-MM-dd");
} else if(value.length() == 16) {
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
} else if(value.length() == 19) {
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
} else {
formatter = new SimpleDateFormat("yyyy-MM-dd");
} formatter.setLenient(false);
return formatter.parse(value);
} else if(classType.equals("java.sql.Date")) {
if(value.length() == 10) {
formatter = new SimpleDateFormat("yyyy-MM-dd");
} else if(value.length() == 16) {
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
} else if(value.length() == 19) {
formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
} else {
formatter = new SimpleDateFormat("yyyy-MM-dd");
} formatter.setLenient(false);
Date date = formatter.parse(value);
return new java.sql.Date(date.getTime());
} else {
return classType.equals("java.lang.Boolean")?Boolean.valueOf(value):(classType.equals("java.lang.Byte")?Byte.valueOf(value):(classType.equals("java.lang.Short")?Short.valueOf(value):(classType.equals("java.lang.Object")?value:null)));
}
}
} catch (NumberFormatException var4) {
return null;
} catch (ParseException var5) {
return null;
}
}
} public static <T> T wrapBean(Class<T> beanClass, HttpServletRequest request) throws InstantiationException, IllegalAccessException {
T objInstance = beanClass.newInstance();
BeanWrapper beanWrapper = new BeanWrapperImpl(objInstance);
PropertyDescriptor[] var7;
int var6 = (var7 = beanWrapper.getPropertyDescriptors()).length; for(int var5 = 0; var5 < var6; ++var5) {
PropertyDescriptor descriptor = var7[var5];
String name = descriptor.getName();
String type = descriptor.getPropertyType().getName();
if(beanWrapper.isWritableProperty(name)) {
Object value = convertType(type, request.getParameter(name));
if(value != null) {
beanWrapper.setPropertyValue(name, value);
}
}
} return objInstance;
} public static Object wrapBean(Class beanClass, HttpServletRequest request, Map<String, String> bean_name) throws InstantiationException, IllegalAccessException {
Object objInstance = beanClass.newInstance();
BeanWrapper beanWrapper = new BeanWrapperImpl(objInstance);
PropertyDescriptor[] var8;
int var7 = (var8 = beanWrapper.getPropertyDescriptors()).length; for(int var6 = 0; var6 < var7; ++var6) {
PropertyDescriptor descriptor = var8[var6];
String name = descriptor.getName();
String type = descriptor.getPropertyType().getName();
if(beanWrapper.isWritableProperty(name)) {
Object value = convertType(type, request.getParameter(bean_name.get(name) == null?name:(String)bean_name.get(name)));
if(value != null) {
beanWrapper.setPropertyValue(name, value);
}
}
} return objInstance;
} public static Map<String, String> wrapMap(HttpServletRequest request) {
String parameterName = null;
String parameterValue = null;
Map<String, String> params = new HashMap();
Enumeration e = request.getParameterNames(); while(e.hasMoreElements()) {
parameterName = (String)e.nextElement();
parameterValue = request.getParameter(parameterName);
if(parameterValue != null && !"".equals(parameterValue.trim())) {
params.put(parameterName, parameterValue);
}
} return params;
} public static Map<String, Object> request2Map(HttpServletRequest request) {
Map<String, Object> result = new HashMap();
Map<String, String[]> params = request.getParameterMap();
String key = null;
String[] value = null;
int size = false;
if(params != null) {
Iterator var7 = params.entrySet().iterator(); while(var7.hasNext()) {
Entry<String, String[]> entry = (Entry)var7.next();
key = (String)entry.getKey();
value = (String[])entry.getValue();
int size = value.length;
if(value != null && size > 0) {
if(size == 1) {
result.put(key, value[0]);
} else {
result.put(key, value);
}
}
}
} return result;
} public static Map wrapMap(Class beanClass, HttpServletRequest request) throws InstantiationException, IllegalAccessException {
Map map = new HashMap();
Object objInstance = beanClass.newInstance();
BeanWrapper beanWrapper = new BeanWrapperImpl(objInstance);
PropertyDescriptor[] var8;
int var7 = (var8 = beanWrapper.getPropertyDescriptors()).length; for(int var6 = 0; var6 < var7; ++var6) {
PropertyDescriptor descriptor = var8[var6];
String name = descriptor.getName();
if(beanWrapper.isWritableProperty(name) && request.getParameter(name) != null) {
map.put(name, request.getParameter(name).trim());
}
} return map;
} public static void wrapObject(Object obj, String[] keys, Map<String, String> bean_name, HttpServletRequest request, int index) {
BeanWrapper beanWrapper = new BeanWrapperImpl(obj);
String[] var9 = keys;
int var8 = keys.length; for(int var7 = 0; var7 < var8; ++var7) {
String key = var9[var7];
if(beanWrapper.isWritableProperty(key)) {
String[] values = request.getParameterValues(bean_name.get(key) == null?key:(String)bean_name.get(key));
if(values != null && values[index] != null) {
beanWrapper.setPropertyValue(key, values[index].trim());
}
}
} } public static Map wrapMap(String[] keys, HttpServletRequest request) throws InstantiationException, IllegalAccessException {
Map map = new HashMap();
String[] var6 = keys;
int var5 = keys.length; for(int var4 = 0; var4 < var5; ++var4) {
String key = var6[var4];
map.put(key, request.getParameter(key));
} return map;
} public static Map wrapMap(Class beanClass, String[] keys, HttpServletRequest request) throws InstantiationException, IllegalAccessException {
Map map = wrapMap(beanClass, request);
String[] var7 = keys;
int var6 = keys.length; for(int var5 = 0; var5 < var6; ++var5) {
String key = var7[var5];
map.put(key, request.getParameter(key));
} return map;
} public static Object wrapBean(String className, HttpServletRequest request) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
return wrapBean(Class.forName(className), request);
} public static List<Object> wrapBeanList(Class beanClass, HttpServletRequest request) throws InstantiationException, IllegalAccessException {
List<Object> result = new ArrayList();
BeanWrapperImpl beanWrapper = new BeanWrapperImpl(beanClass);
BeanWrapperImpl wrapper = new BeanWrapperImpl();
PropertyDescriptor[] var8;
int var7 = (var8 = beanWrapper.getPropertyDescriptors()).length; for(int var6 = 0; var6 < var7; ++var6) {
PropertyDescriptor descriptor = var8[var6];
String name = descriptor.getName();
String type = descriptor.getPropertyType().getName();
if(beanWrapper.isWritableProperty(name)) {
String[] values = request.getParameterValues(name);
if(values != null) {
for(int i = 0; i < values.length; ++i) {
Object value = convertType(type, values[i]);
if(value != null) {
Object objInstance;
if(i < result.size()) {
objInstance = result.get(i);
wrapper.setWrappedInstance(objInstance);
wrapper.setPropertyValue(name, value);
result.set(i, objInstance);
} else {
objInstance = beanClass.newInstance();
wrapper.setWrappedInstance(objInstance);
wrapper.setPropertyValue(name, value);
result.add(objInstance);
}
}
}
}
}
} return result;
} public static List<Object> wrapBeanList(Class beanClass, HttpServletRequest request, Map<String, String> bean_name) throws InstantiationException, IllegalAccessException {
List<Object> result = new ArrayList();
BeanWrapperImpl beanWrapper = new BeanWrapperImpl(beanClass);
BeanWrapperImpl wrapper = new BeanWrapperImpl();
PropertyDescriptor[] var9;
int var8 = (var9 = beanWrapper.getPropertyDescriptors()).length; for(int var7 = 0; var7 < var8; ++var7) {
PropertyDescriptor descriptor = var9[var7];
String name = descriptor.getName();
String type = descriptor.getPropertyType().getName();
if(beanWrapper.isWritableProperty(name)) {
String[] values = request.getParameterValues(bean_name.get(name) == null?name:(String)bean_name.get(name));
if(values != null) {
for(int i = 0; i < values.length; ++i) {
Object value = convertType(type, values[i]);
if(value != null) {
Object objInstance;
if(i < result.size()) {
objInstance = result.get(i);
wrapper.setWrappedInstance(objInstance);
wrapper.setPropertyValue(name, value);
result.set(i, objInstance);
} else {
objInstance = beanClass.newInstance();
wrapper.setWrappedInstance(objInstance);
wrapper.setPropertyValue(name, value);
result.add(objInstance);
}
}
}
}
}
} return result;
} public static List<Object> wrapBeanList(String className, HttpServletRequest request) throws ClassNotFoundException, InstantiationException, IllegalAccessException {
return wrapBeanList(Class.forName(className), request);
}
} 2.后台接受数组
(1)前台ajax请求
var delAdviser = [];
$("input[name='adviserBox']").each(function(){
if($(this).prop("checked") == true){
delAdviser.push($(this).val());
}
});
if(delAdviser.length == 0){
alertModalb("请选择要删除的记录!");
return false;
}
var url = ctx + "/adviser/deleteAdviser";
alertModal("确定要删除选择的记录?",function(){
$.ajax({
url : url,
type : "post",
dataType:'json',
contentType:"application/json",
data : JSON.stringify(delAdviser),
success : function(data){
if(typeof(data) == "object" && !data.length){
if(data.state == "success"){
alertModalb("删除成功!",function(){
listAdviserInfo(null);
});
}else{
alertModalb(data.mess);
}
}
} });
}); (2)后台使用@RequestBody注解
@RequestMapping(value="deleteAdviser",method=RequestMethod.POST)
@ResponseBody
public String deleteAdviser(@RequestBody Integer[] idArr,HttpServletRequest request, HttpServletResponse response){}
3.数组和其他参数混合
(1)、前台
var arr = [];
var condition = {selectValList:arr,channelId:channel_id,channelType:channel_type};
$.ajax({
url: ctx + "/mp/channel/changeChannelCustomerStatus",
data:condition,
type:'post',
dataType:'json',
success:function(data){
}); (2)后台
String[] selectValList = request.getParameterValues("selectValList[]");
String channelId = request.getParameter("channelId");
String channelType = request.getParameter("channelType"); 4.数组字符串和其他参数组合
(1)前台
var groupIds = "";
var custIds = "";
groupIds = objInput[i].value +","+groupIds;
custIds = objInput[i].value +","+custIds;
groupIds = groupIds.substring(0,groupIds.length-1);
custIds = custIds.substring(0,custIds.length-1);
$.ajax({
url:ctx+"/mp/channel/saveChannel",
data:{channel_type_val:channel_type, groupIds:obj.groupIds, custIds:obj.custIds},
type:'post',
dataType:'json',
success:function(data){
alertModalb(data.retMsg, function(){
if (data.retCode == 0) {
window.location.href = ctx+"/mp/channel/queryChannelList";
}
});
},
error:function(){
alertModalb("系统异常!")
}
});
(2)后台
String groupIds = request.getParameter("groupIds");
String custIds = request.getParameter("custIds");
String[] str = productIds.split(",");
for (String productid : str) {
}
5.传list对象
(1)前台
var channelAreaList = [];
var proObj = {};
proObj.province = area;
proObj.province_name = $("#selectArea").find("option:selected").text();
obj.city = city;
obj.city_name = item.infoName;
channelAreaList.push(proObj);
$.ajax({
url : requestUrl,
type : 'post',
data : {"channelAreaList":JSON.stringify(channelAreaList),"spuCodes":productIds},
dataType:'json',
success : function(data) {
tipRemove();
if(data.status == 0){
window.location.href = ctx+"/channel/queryChannelList";
}else{
alertModalb(data.msg);
}
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
tipRemove();
alertModalb("保存信息异常,请联系管理员!");
}
}); (2)后台
@ResponseBody
@RequestMapping(value = "/saveAreaData", method = RequestMethod.POST)
public String saveAreaData(HttpServletRequest request, HttpServletResponse response,
@RequestParam(value = "spuCodes",required=true) String spuCodes,@RequestParam(value="channelAreaList", required=true) String channelAreaList){
Map<String, Object> result = new HashMap<String, Object>();
try{
User user = UsermanageUserUtil.getCurrentUser(request);
if(StringUtil.isNotEmpty(channelAreaList) && StringUtil.isNotEmpty(spuCodes)){
String[] spuArr = spuCodes.split(",");
List<ChannelArea> areaList = JSONObject.parseArray(channelAreaList, ChannelArea.class);
}
6.后台使用JSONObject对象接受
(1)前台

var params = {
"enterpriseId": $("#i_enterpriseId").val(),
"type": $(v).attr("type"),
"isRetail": $(v).attr("isRetail")
};
$.ajax({
type: "post",
url: ctx + "/auditDetailDubbo/findAuditDetail",
data: JSON.stringify(params),
dataType: "json",
contentType:"application/json",
success: function(resp){
} (2)后台
@ResponseBody
@RequestMapping(value = "/findAuditDetail", method = RequestMethod.POST)
public Map<String, Object> findAuditDetailByEnterpriseIdAndType(HttpServletRequest request, HttpServletResponse response,
@RequestBody JSONObject jsonObj){
int type = jsonObj.getIntValue("type");
int enterpriseId = jsonObj.getIntValue("enterpriseId");
Integer isRetail = jsonObj.getInteger("isRetail"); 7.后台使用JSONArray接受
(1)前台
var diliveryAreas = [];
$.each($("#deliveryEditDiv a"),function(i,v){
var item = {};
item.enterpriseId = $("#i_enterpriseId").val();
item.province = $(v).attr("data-prov");
item.city = $(v).attr("data-city");
item.district = $(v).attr("data-area");
var o = getAreaName(item.province, item.city, item.district);
item.provinceName = o.provName;
item.cityName = o.cityName;
item.districtName = o.areaName;
diliveryAreas.push(item);
});
$.ajax({
url: ctx + "/deliveryAreaDubbo/saveDft",
data: JSON.stringify(diliveryAreas),
type: 'post',
dataType: "json",
contentType:"application/json",
success: function(data){
if(data.result != "success"){
alertModal("保存失败");
}
}
});
(2)后台
@ResponseBody
@RequestMapping(value = "/saveDft", method = RequestMethod.POST)
public Map<String, Object> saveDft(@RequestBody JSONArray deliveryAreas,HttpServletRequest request, HttpServletResponse response){
Map<String, Object> resp = new HashMap<String, Object>();
try {
User currentUser = UsermanageUserUtil.getCurrentUser(request);
String operate = currentUser.getUsername();
String enterpriseId = null;
if (deliveryAreas!=null && !deliveryAreas.isEmpty()) {
JSONObject jsonObject = deliveryAreas.getJSONObject(0);
enterpriseId = jsonObject.getString("enterpriseId");
}
List<UsermanageDeliveryAreaDft> areaList = new ArrayList<UsermanageDeliveryAreaDft>();
for(int i=0;i<deliveryAreas.size();i++){
JSONObject item = deliveryAreas.getJSONObject(i);
UsermanageDeliveryAreaDft deliveryArea = new UsermanageDeliveryAreaDft();
deliveryArea.setEnterpriseId(enterpriseId);
  }
} 7.后台使用jsonstring字符串接受
(1)前台
var param = {
quaJson:JSON.stringify(params),
isRetail:isRetail
};
$.ajax({
type: "post",
url: ctx + "/qualificationDubbo/saveDft",
data: param,
dataType: "json",
success: function(resp){
if(resp.status=="success"){
initQualificationData();// 刷新数据
}
}
});
(2)后台
@ResponseBody
@RequestMapping(value = "/saveDft", method = RequestMethod.POST)
public Map<String, Object> saveDft(@RequestParam(value="quaJson", required=true) String quaJson,@RequestParam(value="isRetail", required=true) Integer isRetail){
Map<String, Object> result = new HashedMap(); JSONObject jsonObject=JSONObject.parseObject(quaJson);
  QualificationRetailDft quaJava = JSONObject.parseObject(quaJson.toJSONString(), QualificationRetailDft.class);
}

8.
后台使用jsonstring字符串接受

(1)前台
$.ajax({
type: "POST",
url: ctx + '/receiverAdressDubbo/saveAddressDft',
data: {
receiverAddressJson: JSON.stringify(params).replace(/<pre[^>]*>/gi, "").replace(/<\/pre>/gi, '')
},
dataType: 'json',
success: function(data){
if( data.result == "success" ){
syncFormData(params,formid);
}else{
alertModal("保存失败");
}
}
});
(2)后台
@ResponseBody
@RequestMapping("/saveAddressDft")
public Map<String, Object> saveAddressDft(HttpServletRequest request, HttpServletResponse response,
@RequestParam("receiverAddressJson") String receiverAddressJson){
logger.info("saveAddressDft begin!");
Map<String, Object> resp = new HashMap<String, Object>(); try {
User user = UsermanageUserUtil.getCurrentUser(request);
List<UsermanageReceiverAddress> receiverAddressList = JSON.parseObject(receiverAddressJson, new TypeReference<List<UsermanageReceiverAddress>>(){});
}

以后有在遇到一些以上方法满足不了的情况再继续更新

springMVC常用传参总结的更多相关文章

  1. curl常用传参方式

    1.传header参数curl --header 'Token:40d7c342c110414888cc2a0e1284c636' "127.0.0.1/api/user/baseInfo& ...

  2. SpringMVC POJO传参方式

    有两POJO类 Address.java package com.proc; public class Address { private String province; private Strin ...

  3. SpringMVC常用配置(二),最简洁的配置实现文件上传

    Spring.SpringMVC持续介绍中,基础配置前面已经介绍了很多,如果小伙伴们还不熟悉可以参考这几篇文章: 1.Spring基础配置 2.Spring常用配置 3.Spring常用配置(二) 4 ...

  4. SpringMVC页面向Controller传参

    关于SpringMVC页面向Controller传参的问题,看了网上不少帖子,大多总结为以下几类: 1.直接把页面表单中相关元素的name属性对应的值作为Controller方法中的形参. 这个应该是 ...

  5. 关于springMVC传参问题

    今天写项目,碰到一个以前灭有注意到的问题,一般情况下使用springMVC @Controller注解之后,被此注解标记的方法的参数名只需要跟页面表单的标签的name的值相同即可拿到页面的值,但是如果 ...

  6. ASP.NET WebAPI RC 竟然不支持最常用的json传参

    壮士断腕(WCF Web API),为的是 ASP.NET Web API 的横空出世,再加上它的开放(开源),于是对之产生了一点点痴情,并写下了HttpClient + ASP.NET Web AP ...

  7. springMVC中controller的传参的几种案例

    1.springmvc的controller方法不指定method时,默认get/post都支持 //@RequestMapping(value="test") //@Reques ...

  8. SpringMVC前后端分离交互传参详细教程

    温故而知新,本文为一时兴起写出,如有错误还请指正 本文后台基于SpringBoot2.5.6编写,前端基于Vue2 + axios和微信小程序JS版分别编写进行联调测试,用于理解前后端分离式开发的交互 ...

  9. SpringMVC归纳-1(model数据模型与重定向传参技术)

    要点: model是一个Map结构的数据模型,能重定向时传递数据(拼接URL),但不安全,主要用于渲染前端页面,配合Thymeleaf填充html里面里设置好的参数. @RequestParam用来获 ...

随机推荐

  1. android-async-http框架

    android-async-http 简单介绍:An asynchronous, callback-based Http client for Android built on top of Apac ...

  2. TCP协议和socket API 学习笔记

    本文转载至 http://blog.chinaunix.net/uid-16979052-id-3350958.html 分类:  原文地址:TCP协议和socket API 学习笔记 作者:gilb ...

  3. 2809: [Apio2012]dispatching

    2809: [Apio2012]dispatching Time Limit: 10 Sec  Memory Limit: 128 MB Submit: 3102  Solved: 1641 [Sub ...

  4. EasyDarwin开源流媒体服务器提供的TS切片/HLS直播打包库

    EasyHLS  Github:https://github.com/EasyDarwin/EasyHLS EasyHLS是什么? EasyHLS是EasyDarwin开源流媒体社区开发的一款HLS打 ...

  5. 九度OJ 1138:进制转换 (进制转换)

    时间限制:1 秒 内存限制:32 兆 特殊判题:否 提交:2388 解决:935 题目描述: 将一个长度最多为30位数字的十进制非负整数转换为二进制数输出. 输入: 多组数据,每行为一个长度不超过30 ...

  6. java XML-RPC

    1.XML-RPC简介 xml rpc是使用http协议做为传输协议的rpc机制,使用xml文本的方式传输命令和数据.一个rpc系统,必然包括2个部分:1.rpc client,用来向rpc serv ...

  7. Algorithm: Euler function

    欧拉函数. phi(n)表示比n小的与n互质的数的个数,比如 phi(1) = 1; phi(2) = 1; phi(3) = 2; phi(4) = 2; phi(5) = 4; 性质: 1. 如果 ...

  8. ROM的分类

    转载自:http://www.ic37.com/htm_tech/2012-5/82774_23811.htm ROM(只读存储器)按其内容写入方式,一般分为3种:固定内容ROM:可一次编程PROM: ...

  9. HihoCoder 1638 : 小Hi的天平 (2-sat+并查集)

    描述 小Hi给小Ho邮寄了一个天平.收到天平后,小Ho想知道天平在运输过程中是否损坏,为此它准备了A类物品和B类物品共n个(可能只有A类物品,也可能只有B类物品),但无法确定一个物品是哪一类.A类物品 ...

  10. [CROATIAN2009] OTOCI

    [题目链接] https://www.lydsy.com/JudgeOnline/problem.php?id=1180 [算法] 动态树维护森林连通性 时间复杂度 : O(NlogN ^ 2) [代 ...