Angularjs Post method can not get the parameter in Spring MVC - angularjs

I'm trying to use Angularjs to send a Post request to My Spring Mvc Controller to login User.But I can't get the Parameter from the request.
this is my Angular js code:
$scope.submit = function () {
$http({
url: serviceURL.LoginUrl,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
phone: $scope.userName,
password: $scope.userPsw,
}
}).success(function (data) {
if (!data.state) {
alert(data.errorMsg);
} else {
alert('success');
}
console.log(data);
}).error(function (data) {
console.log('服务器错误!');
});
}
and this is the Spring MVC Controller code:
#RequestMapping(value = "/login", method = RequestMethod.POST)
#ResponseBody
public Object loginUser(Model model,User user, HttpSession session, HttpServletRequest request) {
String phone = request.getParameter("phone");
String password = request.getParameter("password");
System.out.println(phone+","+password);
System.out.println(user.getPhone()+","+user.getPassword());
UserDTO u = userService.loginUser(phone, password);
session.setAttribute("loginUser",u.getUser());
return u;
}
I have searched many resource,they said I should change the header and I have set the header:
#Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,content-type");
return true;
}
Actually,I can't request the login url,but after I setHeader,I can request the url,but the parameter is null.
Forgive my poor English, I am newbie in StackOverFlow.
I didn't konw is it have the same question in here ,but I can find the same question. Thank you for your view.

There are two points to fix. At first, data should be converted to a URL-encoded string. You can convert data object with $.param() method or set params property instad of data so it will look like this:
$scope.submit = function () {
$http({
url: serviceURL.LoginUrl,
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
params: {
phone: $scope.userName,
password: $scope.userPsw,
}
}).success(function (data) {
if (!data.state) {
alert(data.errorMsg);
} else {
alert('success');
}
console.log(data);
}).error(function (data) {
console.log('服务器错误!');
});
}
The second point is server-side controller method. Here you have to annotate method's arguments appropriately. Consider using #RequestParam annotation.
#RequestMapping(value = "/login", method = RequestMethod.POST)
#ResponseBody
public Object loginUser(
#RequestParam String phone,
#RequestParam String password,
HttpSession session,
HttpServletRequest request
) {
System.out.println(phone + ", " + password);
UserDTO u = userService.loginUser(phone, password);
session.setAttribute("loginUser", u.getUser());
return u;
}

<!--In your script-->
var app = angular.module("myApp", [])
.controller("myController", function($http){
var vm= this;
Posting = function(name)
{
var data = 'name=' + name;
var url="example.htm";
$http.post(url, data).then(function (response) {
vm.msg = response.data;
alert(vm.msg);
});
}
});
// Above is same as using GET, but here below is important
//Dont forget to add this config ortherwise http bad request 400 error
app.config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded; charset=UTF-8';
}]);
//In spring controller same as of GET Method
#RequestMapping(value="example.htm", method = RequestMethod.POST)
#ModelAttribute("msg")
public String doingPost(#RequestParam(value="name") String name){
System.out.println(name);
return "successfully Posted";
}

Related

Calling method using $http Post in AngularJS

I am trying to call the method ProcessCriteria in AngularJS below but for some reason I am keep getting error message:
VM18010:1 POST http://example.com/api/TalentPool/ProcessCriteria 404
(Not Found)
Below is my Calling code:
var param = { 'Item': item.Key, 'SolrLabel': SolrLabel };
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: param
//headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
//}
}).then(function (response) {
// success
console.log('Facet Data Posted');
return response;
},
function (response) { // optional
// failed
console.log('facet post error occured!');
});
And my Server side method:
[System.Web.Http.HttpPost]
public IHttpActionResult ProcessCriteria(string Item, string SolrLabel)
{
var itm = Item;
var solr = SolrLabel;
return Ok();
}
Any suggestions please?
ASP.net cannot match your request in its Route Table because you have 2 parameters in your action and the router doesn't understand it.
it expects a data object that your parameters warp to this.
First of all, make a Model like it:
public class Criteria
{
public string Item { get; set; }
public string SolrLabel { get; set; }
}
then change your action:
[System.Web.Http.HttpPost]
public IHttpActionResult ProcessCriteria(Criteria criteria)
{
var itm = criteria.Item;
var solr = criteria.SolrLabel;
return Ok();
}
Update
and update your javaScript part with JSON.stringify:
var param = { 'Item': item.Key, 'SolrLabel': SolrLabel };
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(param)
//headers: {
// 'Content-Type': 'application/x-www-form-urlencoded'
//}
}).then(function (response) {
// success
console.log('Facet Data Posted');
return response;
},
function (response) { // optional
// failed
console.log('facet post error occured!');
});
You can create a class as said by in above answer and you can pass data in http post like this
var obj = {
url: url,
async: true,
method: 'POST',
headers: {
"content-type": "application/json; charset=utf-8",
}
};
if (typeof data != 'undefined' || typeof data != null) {
obj.data = data;
}
$http(obj).then(function(response){
},function(error){
});
I got i working, below is the code for others if they get stuck on it.
var pvarrData = new Array();
pvarrData[0] = JSON.stringify(item.Key);
pvarrData[1] = JSON.stringify(SolrLabel);
pvarrData[2] = JSON.stringify($localStorage.message);
$http({
method: 'POST',
url: '/api/TalentPool/ProcessCriteria',
data: JSON.stringify(pvarrData),
headers: { 'Content-Type': 'application/json' }
}).then(function (response) {
// success
console.log('Facet Data Posted');
return response;
},
function (response) {
// failed
console.log('facet post error occured!');
});

Pass Json data from angular JS to spring REST API and handling it

I'm learning AngularJS and Spring MVC. I'm stuck in a situation where I have an angularjs controller from which I do a REST API call to a spring service. I would like to know how to accept those JSON values inside the controller and map to the Model (getters and setters).
I'm doing some validations on the spring side before doing an insert in the database. I would also like to know how to return those error messages to angula JS and populate them on the screen.
This is my AngularJS controller:
var myapp = angular.module("app");
myapp.controller("RedisplayController",function($scope,$localStorage,$http, $location,$window,) {
$scope.addconfig = function() {
var dataobj = {
escfirstname : $scope.escfirstname ,esclastname:$scope.esclastname,escage:$scope.escage
}
$http({
url: "http://localhost:8080/services/AddConfig",
method: "POST",
data: dataobj,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
}
});
}
});
This is my Spring service:
#Controller
public class TestController {
#RequestMapping(value = "/AddConfig", method = RequestMethod.POST)
public #ResponseBody String PostService(#RequestBody Config person) {
System.out.println("came insidee");
return null;
}
}
I'm able to print the sysout. Now I would like to know how to proceed with this.
enter link description here
like this.
var myapp = angular.module("app");
myapp.controller("RedisplayController",function($scope,$localStorage,$http, $location,$window,) {
$scope.addconfig = function() {
var dataObject = {
escfirstname : $scope.escfirstname,
esclastname : $scope.esclastname,
escage : $scope.escage
};
$http({
method: 'POST',
url: 'http://localhost/jsonURL',
data: dataObject,
headers: {'Content-Type': 'application/json; charset=utf-8'}
}).success(function(data, status, headers, config) {
if( data ) {
}
else {
}
}).error(function(data, status, headers, config) {
console.log(status);
});
}
});
#Controller
public class TestController {
#RequestMapping(value = "/AddConfig", method = RequestMethod.POST)
public #ResponseBody String PostService(#RequestBody Config person) {
// System.out.println("person" + person.);
return null;
}
}

Spring & AngularJS : Undefined status for PUT method

i am returning a string on updation of a record and want to show the same string on UI(updated successfully)
Here is my code :
#RequestMapping(method = RequestMethod.PUT, value = "/update")
public #ResponseBody String update(#RequestParam("id") int id, #RequestParam("name") String name) {
employeeService.update(id, name);
return "updated successfully";
front end code :
$scope.update = function(Employee) {
$http({
method : 'PUT',
url : '/Employee/update',
params : {
id : Employee.id,
name : Employee.name
}
}).success(function(data, status, headers, config) {
$scope.updatedText = data;
$scope.updatedFlag = true;
}).error(function(data, status, headers, config) {
console.log("data.token " + data.token);
});
};
Here are two interesting screen shots
here status is undefined
again
here status is 200
please let me know what is the reason behind that and yes i can see that there is a change in the hibernate table
Please help
Well i'll leave you an example how i handle calls to the API with $http and promises $q
i use it inside a service, that can be injected on my controllers.
this.update = function (Employee) {
var datosRecu = null;
var deferred = $q.defer();
var token = $cookies.getObject('token');
$http({
url: '/Employee/update',
method: 'PUT',
params: {
id: Employee.id,
name: Employee.name
},
headers: {
'Authorization': 'Bearer ' + token,
'Content-type': 'application/json'
}
}).then(function successCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
}, function errorCallback(response) {
datosRecu = response;
deferred.resolve(datosRecu);
});
return deferred.promise;
};
now when i inject it on my controller i can read the promise deferred.promise with all the data of response.
i hope it help you.

How to make Spring REST service to accept multipart file data sent by the Angular Controller?

I'm trying to post a file from Angular controller to the backend. But Spring REST controller is receiving null.
JS
myApp.controller('myCtrl', ['$scope', '$http', function($scope, $http){
$scope.uploadFile = function(){
var formData=new FormData();
formData.append("file", $scope.myFile);
alert("Hi");
$http({
method: 'POST',
url: 'upload',
headers: {'Content-Type': undefined},
data: formData,
transformRequest: function(data, headersGetterFunction) {
return data;
}
}).success(function(data, status) {
console.log('file is ' );
console.dir(data);
})
.error(function(data, status) {
});
}
}]);
Spring-REST Controller
#RequestMapping(value="/upload", method=RequestMethod.POST)
public #ResponseBody String upload(#RequestBody MultipartFile file) {
System.out.println(file);
}
I also tried with public #ResponseBody void uploadFile(MultipartHttpServletRequest request, HttpServletResponse response) but it's of no use. I have declared multipartResolver in the configuaration file too. Any Idea on this? I'm desperately looking for a solution.
Here is a piece of code that works for me:
Spring-REST Controller
#RequestMapping(value = "/api/users/{id}/image", method = RequestMethod.POST)
#ResponseBody
public boolean uploadUserImage( #PathVariable("id") Long id, #RequestParam("file") MultipartFile file ) {
return userService.saveUserImage(id, file);
}
and on the front-end you could do something like this
Angular Controller
//the image
$scope.uploadme;
$scope.uploadImage = function() {
var fd = new FormData();
var imgBlob = dataURItoBlob($scope.uploadme);
fd.append('file', imgBlob);
$http.post(
'/upload',
fd, {
transformRequest: angular.identity,
headers: {
'Content-Type': undefined
}
}
)
.success(function(response) {
console.log('success', response);
})
.error(function(response) {
console.log('error', response);
});
}
//you need this function to convert the dataURI
function dataURItoBlob(dataURI) {
var binary = atob(dataURI.split(',')[1]);
var mimeString = dataURI.split(',')[0].split(':')[1].split(';')[0];
var array = [];
for (var i = 0; i < binary.length; i++) {
array.push(binary.charCodeAt(i));
}
return new Blob([new Uint8Array(array)], {
type: mimeString
});
}
Assuming that the http request is correct the problem must be at the Spring controller. I think you have to change upload(#RequestBody MultipartFile file) to upload(#RequestParam("file") MultipartFile file). So it will be like this:
#RequestMapping(value="/upload", method=RequestMethod.POST)
#ResponseBody
public void upload(#RequestParam("file") MultipartFile file) {
System.out.println(file);
}
Also in your function you have it return String but you are not returning one. So i assume you are doing something else and you removed the code in order to post the question and missed the return, otherwise it wouldn't even build.
Lastly you could check this answer that i gave to a similar problem.

DTO for Spring and AnjularJS

I wand to process the request from AngularJS. So I have DTO-class:
public class LoginDTO {
private String login;
private RoleEnum role;
//setters and getters
}
Controller on backend:
#Controller
#RequestMapping("/EmployeeService/user")
public class UserController {
#RequestMapping(method = RequestMethod.GET, value = "/userInfo")
#ResponseBody
public LoginDTO currentUserInfo(){
LoginDTO loginDTO = new LoginDTO(RoleEnum.ROLE_ADMIN, "test");
return loginDTO;
}
}
And controller on frontend:
app.controller("test", function($scope, $http){
var response = $http({
method: "get",
url: "/EmployeeService/user/userInfo"
});
response.success(function (data) {
alert("ok");
});
response.error(function(data){
alert("failed");
});
});
And at the frontend I see failed. If I change controller on backend:
#Controller
#RequestMapping("/EmployeeService/user")
public class UserController {
#RequestMapping(method = RequestMethod.GET, value = "/userInfo")
#ResponseBody
public String currentUserInfo(){
return "test";
}
}
I see OK. How to use DTO class?
On brawser error the server responded with a status of 406 (Not Acceptable)
and
The resource identified by this request is only capable of generating responses with
characteristics not acceptable according to the request "accept" headers.
Let's add:
app.controller("test", function($scope, $http){
var response = $http({
method: "get",
url: "/EmployeeService/user/userInfo",
<!--ADD--!>
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json'
<!--END--!>
});
response.success(function (data) {
alert("ok");
});
response.error(function(data){
alert("failed");
});
});

Resources