springMVC常用传参总结
本文介绍了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接收
- @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的形式
- /*var data = {
- arr:['a','b','c']
- }*///这种方式是不能服务器是接收不到数据的
- var data = "arr=a&arr=b&arr=c"
- //或者
- <span style="font-family:Arial, Helvetica, sans-serif;">//</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) {}
- });
- @RequestMapping("test")
- @ResponseBody
- public RespMessage test(String[] arr){
- for(String a:arr){
- System.out.println(a);
- }
- return RespMessage.success();
- }
(c)控制台输出
b
c
- <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>
js部分
- var data = $("#form").serialize()
- //data="arr=a&arr=b&arr=c"
2.利用@RequestBody接收
- @RequestMapping("test")
- @ResponseBody
- public RespMessage test(@RequestBody String[] arr){
- for(String a:arr){
- System.out.println(a);
- }
- return RespMessage.success();
- }
(b)页面提交代码
- 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) {}
- });
b
c
3.使用@RequestParam
- @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
- @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) {}
- });
三、传递复杂对象
1.使用@requestBody
- 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;
- }
- }
(b)controller
- @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) {}
- });
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提交
- @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>
顺便一提:文件上传同样可以使用formdata对象使用ajax进行提交,具体参考上面的步骤,这里就不赘述了。
- //上传按钮点击
- $("#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);
- }
项目中传参总结:
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常用传参总结的更多相关文章
- curl常用传参方式
1.传header参数curl --header 'Token:40d7c342c110414888cc2a0e1284c636' "127.0.0.1/api/user/baseInfo& ...
- SpringMVC POJO传参方式
有两POJO类 Address.java package com.proc; public class Address { private String province; private Strin ...
- SpringMVC常用配置(二),最简洁的配置实现文件上传
Spring.SpringMVC持续介绍中,基础配置前面已经介绍了很多,如果小伙伴们还不熟悉可以参考这几篇文章: 1.Spring基础配置 2.Spring常用配置 3.Spring常用配置(二) 4 ...
- SpringMVC页面向Controller传参
关于SpringMVC页面向Controller传参的问题,看了网上不少帖子,大多总结为以下几类: 1.直接把页面表单中相关元素的name属性对应的值作为Controller方法中的形参. 这个应该是 ...
- 关于springMVC传参问题
今天写项目,碰到一个以前灭有注意到的问题,一般情况下使用springMVC @Controller注解之后,被此注解标记的方法的参数名只需要跟页面表单的标签的name的值相同即可拿到页面的值,但是如果 ...
- ASP.NET WebAPI RC 竟然不支持最常用的json传参
壮士断腕(WCF Web API),为的是 ASP.NET Web API 的横空出世,再加上它的开放(开源),于是对之产生了一点点痴情,并写下了HttpClient + ASP.NET Web AP ...
- springMVC中controller的传参的几种案例
1.springmvc的controller方法不指定method时,默认get/post都支持 //@RequestMapping(value="test") //@Reques ...
- SpringMVC前后端分离交互传参详细教程
温故而知新,本文为一时兴起写出,如有错误还请指正 本文后台基于SpringBoot2.5.6编写,前端基于Vue2 + axios和微信小程序JS版分别编写进行联调测试,用于理解前后端分离式开发的交互 ...
- SpringMVC归纳-1(model数据模型与重定向传参技术)
要点: model是一个Map结构的数据模型,能重定向时传递数据(拼接URL),但不安全,主要用于渲染前端页面,配合Thymeleaf填充html里面里设置好的参数. @RequestParam用来获 ...
随机推荐
- MVC入门——详细页
添加Action ShowDetail using System; using System.Collections.Generic; using System.Linq; using System. ...
- 在JS中将JSON的字符串解析成JSON数据格式
使用eval函数来解析 <script> var data="{root: [{name:'1',value:'0'},{name:'6101',value:'北京市'},{na ...
- CentOS系统时间修改
1. 实体机器上安装CentOS $date -s '2015-03-03 13:34:00' 2. 虚拟机上安装的CentOS #查看系统时间和硬件时间 date hwclock --show #设 ...
- jquery ui 怎么实现tab标签切换效果
1.效果图 2.HTML 代码 <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> &l ...
- python的self
python类定义里面的self就是指的该类的对象本身.
- windowbuilder安装
windowbuilder,也就是原来的SWT Designer.Google收购了Instantiations,把它的工具也重新免费发布了.用过swt designer的人都知它是非常好用的swin ...
- Interpreter Pattern
1.Interpreter模式的目的就是提供一个一门定义语言的语法表示的解释器,然后通过这个解释器来解释语言中的句子. 2.Interpreter模式结构图 3.实现 #ifndef _CONTEXT ...
- jvm调试
https://www.usenix.org/legacy/events/jvm01/full_papers/russell/russell_html/index.html
- java HttpClient GET请求
HttpClient GET请求小实例,先简单记录下. package com.httpclientget; import java.io.IOException; import org.apache ...
- cannot find -lbz2 解决方法
sudo yum install -y bzip2* 或者sudo apt-get install bzip2* 还是报错就找到libbz2.so.1,建立连接或者复制到 /usr/lib/libbz ...