本文介绍了springMVC常用的传参方式和一些注意的事项,页面表单主要以ajax的形式提交.
本帅是个菜鸡,水平有限,若有什么讲得不对或有补充的地方欢迎各位提意见。
一、传递String类型
1.controller方法使用String对象作为参数接收
(a) controller
使用controller使用string类型接收,参数名与ajax提交参数名对应即可
[java] view plain copy
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)页面提交代码
[java] view plain copy
1. var data = {
2. "paramA",
3. "paramB"
4. }
5.
6. $.ajax({
7. "type" : "post",//请求方式
8. "url" : "test",//请求连接
9. "dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
10. //"contentType" : "application/x-www-form-urlencoded;charset=utf-8",
11. //不要指定contentType,它会自动识别传参类型,设置不对反而会报400
12. //请求参数
13. success : function(data) {}
14. });
(c)控制台输出
paramA
paramB
2. controller使用bean作为参数接收
(a)TestBean
[java] view plain copy
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成员对象名对应
[java] view plain copy
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
[java] view plain copy
1. @RequestMapping("test3")
2. @ResponseBody
3. public RespMessage test(HttpServletRequest request){
4. "a"));
5. "b"));
6. return RespMessage.success();
7. }
注意:Content-Type不是application/x-www-form-urlencoded的POST请求是不会读取请求体数据和进行相应的参数处理的,即不会解析表单数据来放到request parameter map中。所以通过request.getParameter(name)是获取不到的。
其他同上
二、传递数组
1.使用urlencodeed的形式
(a)页面提交代码
[javascript] view plain copy
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. function(data) {}
13. });
(b)controller
[java] view plain copy
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. }
a
b
c
(d)顺便一提,我们可以使用jq的serialize()方法将form序列化成"arr=a&arr=b&arr=c"这样的格式的数据,具体如下:
html部分
[javascript] view plain copy
1. <form id="form" action="">
2. "text" name="arr" value="a">
3. "text" name="arr" value="b">
4. "text" name="arr" value="c">
5. </form>
[javascript] view plain copy
1. var data = $("#form").serialize()
2. //data="arr=a&arr=b&arr=c"
2.利用@RequestBody接收
(a)controller
在参数上加上@RequestBody注解后就可以接收到前端传来的json格式的数据
[java] view plain copy
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. }
前端这里要注意的地方有两个,一是jq封装的ajax参数的data这里要传字符串格式的数据,也就是说在传值之前需要调用JSON.stringify()方法将json对象转成字符类型,这并不代表服务器拿到的是字符串,到了服务器那边是json对象,只是前端这里传参需要的是字符串,其内部是怎么转换的还没有进行深入研究。 二是要制定contentType为"application/json"否则会报415错误。
[java] view plain copy
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
[java] view plain copy
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)请求页面代码
[javascript] view plain copy
1. var data = {
2. 'a','b','c']
3. }
4. $.ajax({
5. "type" : "post",//请求方式
6. "url" : "test4",//请求连接
7. "dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
8. data:data,
9. function(data) {}
10. });
4.使用formData
(a)controller
[javascript] view plain copy
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)请求界面代码
[javascript] view plain copy
1. var data = new FormData($('#form')[0]);
2. $.ajax({
3. "type" : "post",//请求方式
4. "url" : "test5",//请求连接
5. false,//必须加否则出错
6. false,//必须加否则出错
7. "dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
8. data:data,
9. function(data) {}
10. });
三、传递复杂对象
一般遇到比较复杂的对象就使用@requestBody注解比较方便
1.使用@requestBody
(a)bean
[java] view plain copy
1. public class TestBean2 {
2.
3. private String a;
4.
5. private String b;
6.
7. private TestBean bean;
8.
9. private TestBean[] beans;
10.
11. public TestBean[] getBeans() {
12. return beans;
13. }
14. public void setBeans(TestBean[] beans) {
15. this.beans = beans;
16. }
17.
18. public String getA() {
19. return a;
20. }
21.
22. public void setA(String a) {
23. this.a = a;
24. }
25.
26. public String getB() {
27. return b;
28. }
29.
30. public void setB(String b) {
31. this.b = b;
32. }
33. public TestBean getBean() {
34. return bean;
35. }
36. public void setBean(TestBean bean) {
37. this.bean = bean;
38. }
39.
40. }
[java] view plain copy
1. @RequestMapping("test7")
2. @ResponseBody
3. public RespMessage test7(@RequestBody TestBean2 test){
4.
5. return RespMessage.success();
6. }
(c)请求页面代码
[java] view plain copy
1. var data = {
2. "paramA",
3. "paramB",
4. "beanA",b:"beanB"},
5. "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
[java] view plain copy
1. @RequestMapping("test8")
2. @ResponseBody
3. public RespMessage test8(TestBean2 test){
4.
5. return RespMessage.success();
6. }
(b)提交页面代码
[java] view plain copy
1. <form id="form" action="test8" method="post">
2. "text" name="a" value="paramA">
3. "text" name="b" value="paramB">
4. "text" name="bean.a" value="beanA">
5. "text" name="bean.b" value="beanB">
6. "text" name="beans[0].a" value="beans0A">
7. "text" name="beans[0].b" value="beans0B">
8. </form>
顺便一提:这个也可以通过var data = new FormData($('#form')[0]);获取formdata对象然后通过ajax提交,具体可以参照二.4这里就不赘述了。
四、传递文件
1.使用form提交
(a)controller
[java] view plain copy
1. @RequestMapping("test10")
2. @ResponseBody
3. public RespMessage test10(MultipartFile file){
4. try {
5. 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)提交页面代码
[java] view plain copy
1. <form id="form" action="test10" method="post" enctype="multipart/form-data">
2. "file" name="file">
3. "submit" value="提交">
4. </form>
这里顺便提供一个带进度条的文件上传方法:
[javascript] view plain copy
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.
11. //开始上传
12. function UpladFile(fileObj,i) {
13. //bar.fadeIn();
14. //var fileObj = document.getElementById("file").files[0]; // js 获取文件对象
15. var FileController = "/cwjgpt/notice/FileUpload.do"; // 接收上传文件的后台地址
16. // FormData 对象---进行无刷新上传
17. var form = new FormData();
18. //form.append("author", "hooyes"); // 可以增加表单数据
19. "file", fileObj); // 文件对象
20. // XMLHttpRequest 对象
21. var xhr = new XMLHttpRequest();
22. "post", FileController, true);
23. function() {
24. //alert("上传完成!");
25. };
26. //监听progress事件
27. "progress",
28. function(evt){
29. if (evt.lengthComputable) {
30. var procce = Math.round(evt.loaded / evt.total * 100);//计算进入百分比
31. //这个是自己写的一个更新进度条的方法,这里你们自己实现然后更新界面的进度条
32. }
33. }
34. false);
35. xhr.send(form);
36. }
项目中传参总结:
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>>(){});
}
以后有在遇到一些以上方法满足不了的情况再继续更新