本文介紹了springMVC經常使用的傳參方式和一些注意的事項,頁面表單主要以ajax的形式提交.javascript
本帥是個菜雞,水平有限,如有什麼講得不對或有補充的地方歡迎各位提意見。html
(a) controller前端
使用controller使用string類型接收,參數名與ajax提交參數名對應便可java
(b)頁面提交代碼ajax
(c)控制檯輸出spring
paramA
paramBsql
(a)TestBeanjson
(b)controller數組
ajax提交的參數名須要與TestBean成員對象名對應服務器
(c)頁面提交代碼同 "一. 1.(b)"
(d)控制檯輸出同 " 一. 1.(c)"
(a)controller
(b)提交頁面代碼
順便一提:這個也能夠經過var data = new FormData($('#form')[0]);獲取formdata對象而後經過ajax提交,具體能夠參照二.4這裏就不贅述了。
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>>(){});
}