『壹』 SpringMVC怎麼獲取前台傳來的數據
1.通過HttpServletRequest:
@RequestMapping(value="/index1")
publicStringhelloaction1(HttpServletRequestrequest){
System.out.println(request.getParameter("nnn"));//獲得前台name為nnn的元素的值
return"index";
}
2.通過參數名獲得:
@RequestMapping(value="/index1")
publicStringhelloaction1(Stringnnn){//這里名字要與前端元素名字一致才能獲得
System.out.println(nnn);
return"index";
}
3.通過@RequestParam註解獲得:
@RequestMapping(value="/index")
publicStringhelloaction(@RequestParam(value="nnn",required=false)Stringnnn1,Modelmodel){//nnn要與前端一致,在此處可以理解為參數nnn1的別名
System.out.println(nnn1);
model.addAttribute("hello","這是用action傳過來的值:"+nnn1);
return"index";
}
4.SpringMvc還能通過將vo作為參數獲得vo的各個屬性:
@RequestMapping(value="/index2")
publicStringhelloaction2(Useruser){
System.out.println(user.getAccount());
System.out.println(user.getPassword());
return"index";
}
『貳』 spring mvc 前端怎麼獲取後端數據
方式一 通過 URL 傳參
通過 URL 掛接參數,如 /auth/getUser?userid='6'
伺服器端方法可編寫為: getUser(String userid) ,也可新增其他參數如HttpSession, HttpServletRequest,HttpServletResponse,Mode,ModelAndView等。
方式二 單值傳參
前台調用如:
ajaxPost( "/base/user/exchangeSort" ,{ "id" :rid, "otherid" :otherid}, function(data,status){
xxxxxx
xxxxxx
});
伺服器端為:
public String exchangeSort(String id, String otherid)
方式三 對象傳參
前台調用如:
var org={id:id};
ajaxPost("/base/org/getOrgById", org,function(data,textStatus){
xxxx
xxxx
});
伺服器端為 :
public Org getOrgById(Org org)
方式四 對象序列化傳參
前台調用如:
var ueser={id:rowId};
var data=ajaxPost("/base/user/findById",{"userObj":JSON.stringify(user)},null);
或者
var ueser={ };// 創建對象
user["id"]=id;
user["name"]=$("#name").val();
user["dept"]={};// 外鍵對象
user["dept"]["id"]=$("#deptid").val();
ajaxPost("/base/user/addUser",{"userObj":JSON.stringify(user)},function(data){xxxx;xxxxx;});
伺服器端為:
@RequestMapping ( "/findById" )
@ResponseBody
public UserInfo findById(String userObj) {
// 使用 fastJSON
UserInfo user = JSON.parseObject (userObj, UserInfo. class );
user = (UserInfo) userService . findById (UserInfo. class , user.getId());
return user;
}
方式五 列表傳參
前台代碼如:
var objList = new Array();
grid.forEachRow( function (rId) {
var index = grid.getRowIndex(rId);
var obj = {};
obj[ "id" ] = rId;
obj[ "user" ] = {};
obj[ "user" ][ "id" ] = $( "#userId" ).val();
// 不推薦這樣的寫法
//obj["kinShip"] = grid.cells(rId, 1).getValue();
//obj["name"] = grid.cells(rId, 2).getValue();
obj["kinShip"]=grid.cells(rId,grid. getColIndexById ("columnName")).getValue();
obj["name"]=grid.cells(rId,grid.getColIndexById("name")).getValue();
if (grid.cells(rId, 3).getValue()!= null && grid.cells(rId, 3).getValue()!= "" ) {
var str = grid.cells(rId, 3).getValue().split( "-" );
var day = parseFloat(str[2]);
var month = parseFloat(str[1])-1;
var year = parseInt(str[0]);
var date= new Date();
date.setFullYear(year, month, day);
obj[ "birth" ] = date;
} else {
obj[ "birth" ] = "" ;
}
obj[ "politicalStatus" ] = grid.cells(rId, 4).getValue();
obj[ "workUnit" ] = grid.cells(rId, 5).getValue();
if (grid.cells(rId, 6).isChecked())
obj[ "isContact" ] = "1" ;
else
obj[ "isContact" ] = "0" ;
obj[ "phone" ] = grid.cells(rId, 7).getValue();
obj[ "remark" ] = grid.cells(rId, 8).getValue();
obj[ "sort" ] = index;
objList.push(obj);
});
ajaxPost( "/base/user/addUpdateUserHomeList" , {
"userHomeList" : JSON.stringify(objList),
"userId" : $( "#userId" ).val()
}, function (data, status) {
xxxxx
});
伺服器端:
@RequestMapping("/addUpdateUserHomeList")
@ResponseBody
public String addUpdateUserHomeList(String userHomeList, String userId) {
List<UserHome> userHomes = JSON
.parseArray(userHomeList, UserHome.class); //fastJSON
if (userHomes != null && userHomes.size() > 0) {
try {
userService.addUpdateUserHomeList(userHomes, userId);
} catch (Exception e) {
e.printStackTrace();
}
}
return "200";
}
附上ajaxPost代碼:
function ajaxPost(url,dataParam,callback){
var retData=null;
$.ajax({
type: "post",
url: url,
data: dataParam,
dataType: "json",
success: function (data,status) {
// alert(data);
retData=data;
if(callback!=null&&callback!=""&&callback!=undefined)
callback(data,status);
},
error: function (err,err1,err2) {
alertMsg.error("調用方法發生異常:"+JSON.stringify(err)+"err1"+ JSON.stringify(err1)+"err2:"+JSON.stringify(err2));
}
});
return retData;
}
『叄』 SpringMVC怎麼獲取前台傳來的數組
1、前端假設使用如下url進行ajax請求:假http://ip:port/ap/aa.jsp?a=1&a=2
或者,使用如下表單提交:
<form action="" method="post">
<input name="a" type="text" value="1">
<input name="a" type="text" value="2">
<form>
然後你在 Java裡面寫這樣的String[] a = arg0.getParameterValues("a")代碼 , 那麼java裡面的這個a的字元集合裡面就是[1,2]
2、後端也可以使用springmvc的如下方式獲取:
public String xxx(@RequestParam("a") String[] params){
..
}
『肆』 SpringMVC怎麼獲取前台傳來的數組
前端假設使用如下url進行ajax請求:假http://ip:port/ap/aa.jsp?a=1&a=2
或者,使用如下表單提交:
<form action="" method="post">
<input name="a" type="text" value="1">
<input name="a" type="text" value="2">
<form>
然後你在 Java裡面寫這樣的String[] a = arg0.getParameterValues("a")代碼 , 那麼java裡面的這個a的字元集合裡面就是[1,2]
2、後端也可以使用springmvc的如下方式獲取:
public String xxx(@RequestParam("a") String[] params){
..
}
2、使用springmvc 的requestBody接受ajax傳來的數組、json對象:
1)controller:
[java] view plain
public ResultMessage deleteConbineCode(@RequestBody Long[] id) {
Map queryMap = new HashMap();
queryMap.put("id", id);
try {
CombineCodeService.deleteConbineCode(queryMap);
return new ResultMessage(0, "刪除成功!");
} catch (Exception e) {
e.printStackTrace();
logger.error(e.getMessage());
return new ResultMessage(-1, "刪除失敗!");
}
}
2)前端:
[javascript] view plain
var ids = [];
for(var i=0;i<rows.length;i++){
alert(rows[i].id);
ids.push(rows[i].id);
}
$.ajax({
type : "post",
contentType : "application/json;charset=UTF-8",
url : "<%=basePath %>combineCode/deleteConbineCode",
dataType : "json",
processData : false,
data : $.toJSONString(ids),
success : function(_data) {
if(_data.status==0) {
$("#code_grid").datagrid('reload');
}
}
});
實例二:
1)java
[java] view plain
public class AjaxController {
/**
* 接收客戶端發送的JSON數據,並將其轉換為對象
* @RequestBody
* 其一,從http請求報文的請求體中獲取JSON數據,則說明必須是POST請求
* 其二,Body中為JSON,則最可能為Ajax請求,通過form進行post請求好像辦不到呢
*/
@RequestMapping(value="jsonPost", method=RequestMethod.POST, consumes="application/json")
@ResponseBody
public User jsonPost(@RequestBody User user) {
System.out.println("ajax json post");
System.out.println(user.getName());
System.out.println(user.getPassword());
user.setName("李四");
user.setPassword("100");
return user;
}
}
2)前端:
[javascript] view plain
var user = {};
user.name = $("#name").val();
user.password = $("#password").val();
var jsonStr = JSON.stringify(user);
//var json2Object = JSON.parse(jsonStr);
$.ajax({
type : "post",
contentType : "application/json;charset=UTF-8",
url : "jsonPost",
dataType : "json",
processData : false,
data : jsonStr,
success : function(msg) {
//javascript已自動將返回的json數據轉為對象了
alert("success:"+msg.name+"---"+msg.password);
},
error : function() {
alert("try again!");
}
});
『伍』 springMVC中前台表單的多表數據如何通過後台接收傳入資料庫
表單數據都保存在http的正文部分,各個表單項之間用boundary隔開。
格式類似於下面這樣:用request.getParameter是取不到數據的,這時需要通過request.getInputStream來取數據,不過取到的是個InputStream,所以無法直接獲取指定的表單項(需要自己對取到的流進行解析,才能得到表單項以及上傳的文件內容等信息)。
這種需求屬於比較共通的功能,所以有很多開源的組件可以直接利用,比如:apache的fileupload組件,smartupload等。
通過這些開源的upload組件提供的API,就可以直接從request中取得指定的表單項了。
『陸』 spring MVC 怎麼獲取前端傳遞的數組參數
spring MVC controller獲取前端傳遞的數組參數的方法是進行封裝json字元串實現的。
1、jsp頁面中的數組創建如下:
var myArray = []; 定義數組myArray
myArray .push("OU=Software,DC=example,DC=com,"); 向數組中添加第一個字元串
myArray .push("OU=IT,DC=example,DC=com,");向數組中添加第二個字元串
轉換json數組:
myArray = JSON.stringify(myArray ); 利用json的stringify方法把js對象轉換成json對象
$("#ADOus").attr("action","${ctx}/ADSetting?myOUsArray ="+ myArray );設置action參數
$("#ADOus").submit();提交action到對應的controller
2、在controller層的處理如下:
@RequestMapping(value = { "/ADSetting" }, method=RequestMethod.POST) 定義url和提交方法,規定post
public String configureOUs(HttpServletRequest request,@RequestParam("myOUsArray ") String[] myOUsArray ){
ObjectMapper mapper = new ObjectMapper(); //創建對象映射對象
String [] array = mapper.readValue(jsonString, String[].class): //從映射域中讀取數組參數,以json 字元串的方式
接下來需要把接收到的參數轉換成json對象來處理。
return 定義的頁面
}
『柒』 springmvc怎麼接收多個
SpringMVC 可以使用命令表單對象來自動設置值的。 只要你input裡面的name的值和 你實體裡面的值是一樣的, 然後再Controller上面定義一個user對象, 就可以獲取到了。