本文介绍了springMVC常用的传参方式和一些注意的事项,页面表单主要以ajax的形式提交.
本帅是个菜鸡,水平有限,若有什么讲得不对或有补充的地方欢迎各位提意见。
1.controller方法使用String对象作为参数接收
(a) controller
使用controller使用string类型接收,参数名与ajax提交参数名对应即可
[java]view plaincopy
@RequestMapping("test")
@ResponseBody
public RespMessage test(String a,String b){
System.out.println(a);
System.out.println(b);
return RespMessage.success();//这个是返回固定格式的响应数据,不用管
}
(b)页面提交代码
[java]view plaincopy
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
(a)TestBean
[java]view plaincopy
publicclass TestBean {
private String a;
private String b;
public String getA() {
return a;
}
publicvoid setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
publicvoid setB(String b) {
this.b = b;
}
}
(b)controller
ajax提交的参数名需要与TestBean成员对象名对应
[java]view plaincopy
@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)"
(a)controller
[java]view plaincopy
@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)是获取不到的。
其他同上
(a)页面提交代码
[javascript]view plaincopy
/*var data = {
arr:['a','b','c']
}*///这种方式是不能服务器是接收不到数据的
var data ="arr=a&arr=b&arr=c"
//或者
//</span><span style="font-family:Arial, Helvetica, sans-serif;">var data = "arr=a,b,c";</span>
$.ajax({
"type" :"post",//请求方式
"url" :"test5",//请求连接
"dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
data:data,
success :function(data) {}
});
(b)controller
[java]view plaincopy
@RequestMapping("test")
@ResponseBody
public RespMessage test(String[] arr){
for(String a:arr){
System.out.println(a);
}
return RespMessage.success();
}
(c)控制台输出
a
b
c
(d)顺便一提,我们可以使用jq的serialize()方法将form序列化成"arr=a&arr=b&arr=c"这样的格式的数据,具体如下:
html部分
[javascript]view plaincopy
</form>
js部分
[javascript]view plaincopy
var data = $("#form").serialize()
//data="arr=a&arr=b&arr=c"
(a)controller
在参数上加上@RequestBody注解后就可以接收到前端传来的json格式的数据
[java]view plaincopy
@RequestMapping("test")
@ResponseBody
public RespMessage test(@RequestBody String[] arr){
for(String a:arr){
System.out.println(a);
}
return RespMessage.success();
}
(b)页面提交代码
前端这里要注意的地方有两个,一是jq封装的ajax参数的data这里要传字符串格式的数据,也就是说在传值之前需要调用JSON.stringify()方法将json对象转成字符类型,这并不代表服务器拿到的是字符串,到了服务器那边是json对象,只是前端这里传参需要的是字符串,其内部是怎么转换的还没有进行深入研究。 二是要制定contentType为"application/json"否则会报415错误。
[java]view plaincopy
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
这个方法有个不好的地方就是如果这个参数没有传就会报异常
(a)controller
[java]view plaincopy
@RequestMapping("test")
@ResponseBody
public RespMessage test(@RequestParam(value ="arr[]") String[] arr){
for(String a:arr){
System.out.println(a);
}
return RespMessage.success();
}
(b)请求页面代码
[javascript]view plaincopy
var data = {
arr:['a','b','c']
}
$.ajax({
"type" :"post",//请求方式
"url" :"test4",//请求连接
"dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
data:data,
success :function(data) {}
});
(a)controller
[javascript]view plaincopy
@RequestMapping("test5")
@ResponseBody
public RespMessage test2(String[] arr){
for(String a:arr){
System.out.println(a);
}
return RespMessage.success();
}
(b)请求界面代码
[javascript]view plaincopy
var data =new FormData($('#form')[0]);
$.ajax({
"type" :"post",//请求方式
"url" :"test5",//请求连接
processData:false,//必须加否则出错
contentType:false,//必须加否则出错
"dataType":"json",//预期服务器返回格式,不设置jq也会自己判断
data:data,
success :function(data) {}
});
一般遇到比较复杂的对象就使用@requestBody注解比较方便
(a)bean
[java]view plaincopy
publicclass TestBean2 {
private String a;
private String b;
private TestBean bean;
private TestBean[] beans;
public TestBean[] getBeans() {
return beans;
}
publicvoid setBeans(TestBean[] beans) {
this.beans = beans;
}
public String getA() {
return a;
}
publicvoid setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
publicvoid setB(String b) {
this.b = b;
}
public TestBean getBean() {
return bean;
}
publicvoid setBean(TestBean bean) {
this.bean = bean;
}
}
(b)controller
[java]view plaincopy
@RequestMapping("test7")
@ResponseBody
public RespMessage test7(@RequestBody TestBean2 test){
return RespMessage.success();
}
(c)请求页面代码
[java]view plaincopy
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)测试结果
(a)controller
[java]view plaincopy
@RequestMapping("test8")
@ResponseBody
public RespMessage test8(TestBean2 test){
return RespMessage.success();
}
(b)提交页面代码
[java]view plaincopy
</form>
顺便一提:这个也可以通过var data = new FormData($('#form')[0]);获取formdata对象然后通过ajax提交,具体可以参照二.4这里就不赘述了。
(a)controller
[java]view plaincopy
@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)提交页面代码
[java]view plaincopy
</form>
顺便一提:文件上传同样可以使用formdata对象使用ajax进行提交,具体参考上面的步骤,这里就不赘述了。
这里顺便提供一个带进度条的文件上传方法:
[javascript]view plaincopy
//上传按钮点击
$("#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);
}
项目中传参总结:
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 wrapBean(Class 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 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 wrapMap(HttpServletRequest request) {
String parameterName = null;
String parameterValue = null;
Map 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 request2Map(HttpServletRequest request) {
Map result = new HashMap();
Map params = request.getParameterMap();
String key = null;
String[] value = null;
int size = false;
if(params != null) {
Iterator var7 = params.entrySet().iterator();
while(var7.hasNext()) {
Entry 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 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 wrapBeanList(Class beanClass, HttpServletRequest request) throws InstantiationException, IllegalAccessException {
List 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 wrapBeanList(Class beanClass, HttpServletRequest request, Map bean_name) throws InstantiationException, IllegalAccessException {
List 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 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 result = new HashMap();
try{
User user = UsermanageUserUtil.getCurrentUser(request);
if(StringUtil.isNotEmpty(channelAreaList) && StringUtil.isNotEmpty(spuCodes)){
String[] spuArr = spuCodes.split(",");
List 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 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 saveDft(@RequestBody JSONArray deliveryAreas,HttpServletRequest request, HttpServletResponse response){
Map resp = new HashMap();
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 areaList = new ArrayList();
for(int i=0;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 saveDft(@RequestParam(value="quaJson", required=true) String quaJson,@RequestParam(value="isRetail", required=true) Integer isRetail){
Map 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(/]*>/gi, "").replace(/<\/pre>/gi, '')
},
dataType: 'json',
success: function(data){
if( data.result == "success" ){
syncFormData(params,formid);
}else{
alertModal("保存失败");
}
}
});
(2)后台
@ResponseBody
@RequestMapping("/saveAddressDft")
public Map saveAddressDft(HttpServletRequest request, HttpServletResponse response,
@RequestParam("receiverAddressJson") String receiverAddressJson){
logger.info("saveAddressDft begin!");
Map resp = new HashMap();
try {
User user = UsermanageUserUtil.getCurrentUser(request);
List receiverAddressList = JSON.parseObject(receiverAddressJson, new TypeReference>(){});
}
以后有在遇到一些以上方法满足不了的情况再继续更新