[英]How to send username and password in Ajax call?
Here I want to send username and password to my spring mvc controller. 在这里,我想将用户名和密码发送到我的spring mvc控制器。 I am using ajax to call mvc method.And it is not reaching to controller.
我正在使用ajax来调用mvc方法,并且无法到达控制器。
angular controller:- 角度控制器:-
$scope.formSubmit=function(){
alert("submitted")
return $http({
url :'loginSubmit' ,
method : "POST",
data: { username: $scope.username, password: $scope.password }
//data: data
}).success(function(data, status, headers){
}).error(function(data, status, headers) {
console.log("login error"+status);
});
}
mvc controller MVC控制器
@RequestMapping(value="/loginSubmit",method=RequestMethod.POST)
public @ResponseBody User loadUserByUsername(@RequestParam("username") String username,@RequestParam("password") String password, HttpSession session){
System.out.println("controller");
System.out.println("name is "+username);
return null;
}
If you are using request params, you have to append to URL 如果使用请求参数,则必须附加到URL
$scope.formSubmit=function(){
alert("submitted")
return $http({
url :'loginSubmit?username='+$scope.username+'&password='+$scope.password ,
method : "POST",
}).success(function(data, status, headers){
}).error(function(data, status, headers) {
console.log("login error"+status);
});
}
Note: Dont use alert. 注意:请勿使用警报。 Use console.log
使用console.log
The best way to do this would be sending the credentials in body instead of request URL 最好的方法是在正文中发送凭据,而不是请求URL
** Retain your old JS code of sending data as body and Change the JAVA code to** **保留将主体作为数据发送的旧JS代码,并将JAVA代码更改为**
@RequestMapping(value="/loginSubmit",method=RequestMethod.POST)
public @ResponseBody User loadUserByUsername(@RequestBody Map<String,Object> credentials, HttpSession session){
String username = credentials.get("username");
String password = credentials.get("password");
System.out.println("controller");
System.out.println("name is "+username);
return null;
}
Try this 尝试这个
$scope.formSubmit=function(){
alert("submitted")
var uname = $scope.username,pswd=$scope.password;
return $http({
url :'loginSubmit',
method : "POST",
params : {username:uname,password:pswd}
}).success(function(data, status, headers){
}).error(function(data, status, headers) {
console.log("login error"+status);
});
}
return $http({
url :'/loginSubmit',
method : "POST",
data: { username: $scope.username, password: $scope.password }
//data: data
}).success(function(data, status, headers){
}).error(function(data, status, headers) {
console.log("login error"+status);
});
}
@RequestMapping(value="/loginSubmit",method=RequestMethod.POST)
public @ResponseBody User loadUserByUsername(@RequestParam("username") String username,@RequestParam("password") String password, HttpSession session){
System.out.println("controller");
System.out.println("name is "+username);
return null;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.