POST request not getting mapped to Spring MVC Controller - angularjs

I am sending a POST request from Angularjs $http service . It is working fine when my promise is like below and is getting properly mapped to Spring Controller ,
service.js
reassignKsaPendingLeads : function(data,username)
{
var promise = $http({
url : "reassignPendingLeads.htm",
method : "POST",
data : mydata
})
.success(function(data, status, header, config, statusText)
{
}
}
Spring Controller
#RequestMapping({ "reassignPendingLeads.htm" })
public #ResponseBody String updateAccessStatus(#RequestBody List<KsaLead> ksaLeads)
{
log.info("Inside updateAccessStatus");
return "true";
}
The json object i pass from service.js is getting mapped properly to #RequestBody List ksaLeads.
Since the json object contains same keys as bean properties of KsaLead.
But Now i want to pass another parameter username apart from json body (data).
Then i get Request method 'POST' not supported in Spring Controller .
new service.js
reassignKsaPendingLeads : function(data,username)
{
var mydata = JSON.stringify(data) + '&username=' + username;
var promise = $http({
url : "reassignPendingLeads.htm",
method : "POST",
data : mydata
})
.success(function(data, status, header, config, statusText)
{
}
new Spring Controller
#RequestMapping({ "reassignPendingLeads.htm" })
public #ResponseBody String updateAccessStatus(#RequestBody List<KsaLead> ksaLeads,#RequestParam String username)
{
log.info("Inside updateAccessStatus");
return "true";
}
Can anyone guide me as to how should i pass data from angularJs so that it gets mapped correctly to Spring Controller

I would assume that you want to pass the username as a request parameter. In order to do this, the $http can have a params input field:
function(data,username) {
var promise = $http({
url: "reassignPendingLeads.html",
method: "POST",
data: data,
params: { username: username }
})
// continue with your promise here
}
If you want to pass it inside the request body we have to do the following steps:
We have to add the username to the mydata object.
// we assume that data is not a primitive type
function(data,username) {
var mydata;
// check if data is defined
if (data) {
// make a deep copy first, since we don't want to modify the input
mydata = angular.copy(data);
} else {
// if the data is undefined, create e new object
mydata = {};
}
// add the username to mydata
mydata.username = username;
var promise = $http({
url: "reassignPendingLeads.html",
method: "POST",
data: mydata
})
// continue with your promise here
}
On the back-end we have to make sure that we can accept this kind of data. For this it is advised to create a data class which holds the username and any other fields which may appear on your data object from the front-end.
Probably something like this:
public class MyDataClass {
private String username;
// other fields
// no args constructor
public MyDataClass() {}
// all args constructor
public MyDataClass(String username) {
this.username = username;
}
// getter and setters
}
Now we modify the controller to accept it:
#RequestMapping(value = "reassignPendingLeads.htm", method = RequestMethod.POST)
public #ResponseBody String updateAccessStatus(#RequestBody MyDataClass data)
{
log.info(data.getUsername());
return "true";
}

Related

how to send json data by $http.Post from Angular to webAPI POST method?

I am trying to pass data as JSON object by $http.Post to webAPI method. In WebAPI method, the parameter of the method is a class object.
It works fine when I test the webAPI method by Postman.But I am not able to pass the JSON object by angular $http.post method-I get null values in the webAPI parameter(in the class object).
Can someone please advise how to fix the issue.i am new to AngularJS.Kindly help.
AngularJS Code
angular.module('Test.Employer')
.controller('EmployerController', ['$scope','headerValue', '$http',
function ($scope, headerValue, $http) {
var ipEmployerDetls = {
EmployerName: "cherokee",
Company: "ABC"
};
$http({
url: "http://localhost:212122/api/Values/PostEmployeeData",
dataType: 'json',
method: 'POST',
data: JSON.stringify(ipEmployerDetls),
headers: {
"Content-Type": "application/json"
}
}).success(function (response) {
$scope.object = response.data;
})
.error(function (error) {
alert(error.Message);
});
})();
WebAPI
using System.Web.Http;
using AttributeRouting.Web.Http;
namespace webAPITestProject.Controllers
{
[Route("api/Values")]
public class ValuesController : ApiController
{
retrieveEmployeeData empData = new retrieveEmployeeData();
retrieveProductDetails prodDetls = new retrieveProductDetails();
[Route("PostEmployeeData")]
[HttpPost]
public DataTable PostEmployeeData([FromBody] Employer empDetails)
{
DataTable dataTable = new DataTable { TableName = "MyTableName" };
dataTable = empData.getEmployeeData(empDetails);
return dataTable;
}
}
}
NOTE: I get NULL value in empDetails in webAPI method,but when I test the method in Postman,it has value.
Your routing attributes don't look right for how you've specified your $http API call.
Looks like you want the class-level attribute to be:
[RoutePrefix("api/Values")]
public class ValuesController : ApiController
Which will mean that PostEmployeeData has a route of api/Values/PostEmployeeData.
You'll also need to ensure that your properties in ipEmployerDetls directly map to your Employer class (which you haven't shown), so that model binding works correctly.

Get Json object passed in $http.put request

I am a newbie to angularjs. I am trying to send a json object in $http.put request as follows:
function LoginCtrl($http){
this.login = function(){
var self = this;
self.user = {
username: this.username,
password: this.password
}
$http.put('http://localhost:8086/app/login',self.user).then(function
successCallback(response) {
}, function errorCallback(response) {
})
}
}
I just want to get this json object in Rest api, the code of which is as follows:
#Path("/app")
public class LoginResource {
public LoginResource() {
}
#PUT
#Path("/login")
#Consumes(MediaType.APPLICATION_JSON)
public Response getUserByName() {
return Response.status(Response.Status.ACCEPTED).build();
}
What parameters i need to pass to this getUserByName api?. I am using dropwizard
Also if somebody could tell how to set the index.html page as the starting page in jetty server config.
First, in your Dropwizard(Jersey) backend define your input
public Response getUserByName(User user) { ...
Then you can map your JSON to an entity like this:
public class User {
#JsonProperty("name")
private String name; }
In angularJS pass the Json object as a request payload in $http.PUT(uri,<JsonObject>)
http.put(url, JSON.stringify(self.user), function (err, response)
{
// do something here
}

Not hitting with Web API two different GET methods

Implemented webapi routing and having two different route methods for for retrieving values but it is differentiated by supplying parameter type.
Api methods are getting hit for the corresponding action methods if we simply specify "apiurl/api/contact/search/sri" and "apiurl/api/contact/get/2" in direct browser url.
But when comes to communicate with angular to webapi, api is not getting hit.
//angular service
contact.search = function (inputName) {
return $http({
method: 'GET',
url: url + 'api/contact/search',
//params: { name: inputName }
data: { name: inputName }
});
//return $http.get(url + 'api/contact/search', name);
}
//WebAPI
[HttpGet]
[Route("search/{name:alpha}")]
public IHttpActionResult GetContacts([FromBody]string name)
{
repository = new ContactRepository();
if (string.IsNullOrEmpty(name))
{
var message = new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("Search Name can not be empty")
};
throw new HttpResponseException(message);
}
return Ok(repository.GetContact(name));
}
// GET api/contact/5
[HttpGet]
[Route("get/{id:int}")]
public IHttpActionResult Get(int id)
{
repository = new ContactRepository();
if (id == 0)
{
var message = new HttpResponseMessage(HttpStatusCode.NotFound) { Content = new StringContent("Issue with Passed Id Parameter.") };
throw new HttpResponseException(message);
}
return Ok(repository.GetContact(id));
}
When you use data: { name: inputName }, it is appended to the url in the following way:
...api/contact/search?name=inputName
but what you want is this:
...api/contact/search/inputName
So, you have two options.
Either change your angular code:
return $http({
method: 'GET',
url: url + 'api/contact/search/' + inputName,
});
or change your API to accept QUERY params.
Hope it helps

Angular $resource and webApi

I am using webApi and have generated the model using entityframework the overload method of the GET(int id) I am trying to call that using the query of the $resource
I am trying to pass an optional parameter to a call using the $resource but get the error [$resource:badcfg] I have had a google and people say add
{
'get': {method: 'GET'},
'query': {method: 'GET', isArray: true}
}
into the function, so I have tried this: but still have no luck.
function minorResource($resource, appSettings) {
return $resource(appSettings.serverPath + "/api/minorworks/:id",
{
'get': {method: 'GET'},
'query': {method: 'GET', isArray: true}
});
}
Would you use 2 separate methods or can the above function be made to work?
For completness here is my Controller call
minorResource.query({id: vm.seachCriteria}, function (data) {
//console.log(data);
vm.minorWork = data;
});
Note that query is used to retrieve an array of objects and get is used to retrieve a single object. That means that with a get you usually sent the id of the object to the API.
So in your case:
var minorWorksResource = $resource(appSettings.serverPath + "/api/minorworks/:id");
// Note that query returns an array.
var works = minorWorksResource.query(function() {
var firstWork = works[0];
});
// Note that we pass an ID that will be fetched in the query string.
var singleWork = minorWorksResource.get({id: 123}, function() {
});
And the WebAPI part:
[RoutePrefix("api/minorworks")]
public class MinorWorksController : ApiController {
public IHttpActionResult Get(int id) {
var singleWork = null;
// Retrieve a single item;
return Ok(singleWork);
}
public IHttpActionResult Get() {
var workList = null;
// Retrieve the whole list.
return Ok(workList );
}
}

Angular controller doesn't pass value to web api method with $http

This is my angularjs code:
var uname = resetPasswordRequestData.email
var request = $http({
method: "post",
url: workModule.config.Config.CommonUrl + "api/ResetPasswordRequest",
data: uname
});
web api code:
public class PerformPasswordResetController : ApiController
{
public int PerformResetPassword([FromBody]string uname)
{
CrmUser contact = null;
if (ModelState.IsValid)
{
try
{
contact = new PasswordResetProvider().GetUserByName(uname);
}
catch (Exception ex)
{
return 1;
}
}
}
My problem is when I make the call from Fiddler it works, but when I run the code it nicely rout to the web api method but in web api controller "uname" argument is null. when I pass some data from fiddler it pass that data to "uname" (in web api controller uname is not null)
can anyone help me?
I strongly suggest you use a Model class to receive the data on your server.
Something like this:
public class UserModel {
public string UserName { get; set; }
}
public class PerformPasswordResetController : ApiController
{
public int PerformResetPassword([FromBody]UserModel user)
{
...Do your stuff
}
}
And on your angular code:
var model = {
userName: resetPasswordRequestData.email
};
var request = $http({
method: "post",
url: workModule.config.Config.CommonUrl + "api/ResetPasswordRequest",
data: model
});
Also, if you don´t want (or can´t) change your server code, try this please:
var uname = resetPasswordRequestData.email
var request = $http({
method: "post",
url: workModule.config.Config.CommonUrl + "api/ResetPasswordRequest",
data: {
uname: uname
}
});

Resources