angularjs$http.get and java api call - javascript

I'm trying to make an angularjs $http.get request with parameters but it's not working due to syntaxt may be. Can you please
confirm what i'm doing wrong , maybe syntax is wrong in angularjs call or in java api method
$http.get(document.requestPathPrefix + "/home/my-api",
$scope.requestParametersObject
).then(
function(response) {
$scope.output = response.data;
},
function(response) {
$scope.retrieveErrorMssg = "Failed to retrieve required data.";
});
my parameters are like in this image
parameter object for api call
And in java api call like this
#RequestMapping(value = "/my-api", method = RequestMethod.GET)
public ResponseEntity<Collection<MyObjectResponse>> getMyObjResponse(#RequestBody final MyObjectRequest request)
{
Map<Integer,MyObjectResponse> oResponse = new HashMap<>();
try {
//Manipulation and db calls
} catch (Exception e) {
log.error(e.getMessage(), e);
}
return new ResponseEntity<Collection<MyObjectResponse>>(oResponse.values(), HttpStatus.OK);
}

try ,
$http({
url: '/home/my-api',
method: "GET",
headers: {
'Content-type': 'application/json'
},
data: JSON.stringify(request)
}).success(function(data, status, headers, config) {
}).error(function(data, status, headers, config) {
return null;
});

If you are worried about syntax, take a look at this simple example and modify it to your need.
In JS, your http.get call should contain the URL and its parameters if any,
$http.get('getUserInfo',
{
params : {
'userEmail' : 'userEmail'
}
}).then(function(response) {
console.log(response);
});
If you are passing a parameter to the API call, ensure your Java controller or the service has the parameter defined to receive the same. Ideally the parameters should match between the call and the provider
For example, for the above API call, the spring controller should like below,
#RequestMapping(value = "/getUserInfo", method = RequestMethod.GET)
public #ResponseBody User getUserInfo(
#RequestParam("userEmail") String userEmail) {
// Do Something
}

Related

Ajax request doesn't redirect to view in Spring MVC

I am using Spring MVC and Spring Security for the application. We are using spring form tags to request rest calls in the application. For a particular purpose, i am using ajax calls from the jsp. It calls the controller method successfully and does processing, but, the controller method doesn't land to a view for some reason. I am not getting any error or anything in logs.
Controller:
#RequestMapping(value="/createRunOne/saveRun", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public String saveRun(#RequestBody Run run, Model model){
try{
this.runService.saveRun(run);
} catch (Exception ex){
model.addAttribute(ERROR, ex.getMessage());
ex.printStackTrace();
}
return "redirect:/run/list";
}
javascript function written in jsp:
function saveRun() {
var run = {
runName: $('#name').val(),
description: $('#description').val(),
justification: $('#justification').val(),
scheduledTime: new Date($('#scheduledTime').val()),
fromReceiptDate: new Date($('#fromdatepicker').val()),
toReceiptDate: new Date($('#todatepicker').val()),
sourceKeyString: $('#segmentSelect').val().toString(),
selectedBlocks: $('#blockList').val().toString(),
compareFilter: $('#filtercase').val(),
productsSelected: selectedList.toString()
};
headers['Content-Type'] = 'application/json';
headers['dataType'] = 'json'
$.ajax({
type: "POST",
url: "createRunOne/saveRun",
data: JSON.stringify(run),
headers: headers,
responseType: "application/json",
success: function(response, data){
if(data=='success'){
}
},
error: function (xhr, textStatus, errorThrown) {
alert(xhr.status);
}
});
}
It is not possible to redirect by this way in ajax call.
Better you return one success or failure flag and in the ajax success function do below.
#RequestMapping(value="/createRunOne/saveRun", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE)
public String saveRun(#RequestBody Run run, Model model){
try{
this.runService.saveRun(run);
} catch (Exception ex){
model.addAttribute(ERROR, ex.getMessage());
ex.printStackTrace();
}
return "success";
}
In view page use this to redirect :
success: function(response, data){
if(data=='success'){
window.location.replace('<redirect url>');
}
},

How to POST data from AngularJS to Struts 2 using REST

I need to get the value from client side to server side. I am using AngularJS and Struts2 REST.
My controller doesn't get the value passed or am I wrong in passing or using RESTful controller?
Here is my code:
angularcontroller.js:
app.controller('saveAddCatCtrl', function($scope, $http){
$scope.save = function(newAddCat){
$http({
method: "POST",
url: "api/additionalcategory",
data: $scope.additionalCategory.addCatName
}).success(function(data, status, header, config){
//success
}).error(function(data, status, header, config){
//error
});
}
});
Here is my REST controller:
public class AdditionalcategoryController extends ActionSupport implements ModelDriven<Object>{
private AdditionalCategoryRepository additionalCategoryRepository =
(AdditionalCategoryRepository)ServletActionContext.getServletContext()
.getAttribute("additionalCategoryRepository");
private List<AdditionalCategory> additionalCategories;
public AdditionalCategory additionalCategory = new AdditionalCategory();
private int id;
public HttpHeaders index(){
setAdditionalCategories(additionalCategoryRepository.findAllAdditionalCategory());
System.out.println("GET api/additionalCategory");
return new DefaultHttpHeaders("index").disableCaching();
}
public HttpHeaders create(){
additionalCategoryRepository.createAdditionalCategory(additionalCategory);
return new DefaultHttpHeaders("create").disableCaching();
}
public void setAdditionalCategories(List<AdditionalCategory> additionalCategories){
this.additionalCategories = additionalCategories;
}
#Override
public Object getModel() {
if (additionalCategories == null){
return additionalCategory;
}else{
return additionalCategories;
}
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public List<AdditionalCategory> getAdditionalCategories() {
return additionalCategories;
}
public AdditionalCategory getAdditionalCategory() {
return additionalCategory;
}
public void setAdditionalCategory(AdditionalCategory additionalCategory) {
this.additionalCategory = additionalCategory;
}
}
Since angular service http sends JSON, you can send a JSON object using data property. The JSON object will be deserialized to your model class properties because you are using ModelDriven or Action class properties otherwise.
Struts2 REST plugin is made to handle JSON content from the request. It's possible due ContentTypeInterceptor, which is called rest, be able to find JSON handler for the request. The JSON handler is guessed from the Content-Type header or .json extension to the file in the URL. You can use either ways, but second is easier.
Note:
URLs without a file extension the Struts2 REST plugin defaulting to handle xhtml content. So you can modify your code
$http({
method: "POST",
url: "api/additionalcategory.json",
data: {}
}).success(function(data, status, header, config){
//success
}).error(function(data, status, header, config){
//error
});

WebApi 404's with Parameters - calling via javascript GET

WebApi Method within LocationsController:
public async Task<IHttpActionResult> GetLocations(int id, long start, long end)
{
return Ok();
}
Calls I have tried to make (GET):
https://api.com/Locations/GetLocations/34934/1/1
https://api.com/Locations/GetLocations?34934&start=1&end=1
As such:
factHttp.httpRequest('/locations/GetLocations', 'GET', vm.ID + '/' + start.getTime() + '/' + now.getTime()).then(function (_result) {
vm.plots = angular.fromJson(_result.data);
});
var _httpRequest = function requestCall(requestPartURL, requestType, requestPayload) {
var _resultHttp = $http({
url: apiURL + requestPartURL,
method: requestType,
data: requestPayload,
headers: {
'Authorization': 'Bearer ' + localStorage.getItem('ACCESS_TOKEN')
}
}).success(function (response) {
console.log("HTTP CALL SUCCESS");
return {
result: 'SUCCESS',
resultObj: response,
errorCode: '',
errorDesc: ''
}
}).error(function (response) {
console.log("HTTP CALL FAIL");
console.log(response);
return getErrorObj(response);
});
return _resultHttp;
}
Routing:
config.Routes.MapHttpRoute(
"IdentWithRange",
"{controller}/{action}/{id}/{start}/{end}"
);
If I change the web api method to just take (int id) and call GetLocation/34934 it works just fine. What have I done wrong here?
I continually get a 404 error. Some of this was not written by myself (namely the JS stuff as I am bad at it), but it's the first time working with any sort of api for me, where I control both ends, I'm a bit stuck.
The routing record you created would be looking for the following route
/api/controller/id/start/end
but you are trying to pass in parameters, not specify a route. You dont need a special routing record to handling multiple parameters. Using a 'standard' routing record will suffice.
config.Routes.MapHttpRoute("DefaultApi", "api/{controller}/{id}", new
{
id = RouteParameter.Optional, action = "DefaultAction"
});
Currently you need to add "api" to your route.
https://api.com/api/Locations/GetLocations/34934/1/1
Recommended:
https://api.com/api/locations/34934/1/1
[HttpGet, Route("locations/{id:int:min(1)}/{start:long}/{end:long}")]
public async Task<IHttpActionResult> GetLocations(int id, long start, long end)
{
return Ok();
}

AngularJs Posting to a WebApi method with dynamic properties

My webApi controller code looks like this:
[HttpPost]
public int ValidateUser([FromBody]dynamic credentials)
{
try
{
string username = credentials.username;
string password = credentials.password;
//do stuff
}
}
catch (Exception ex)
{
throw ex;
return -1;
}
return -1; // not valid user
}
My angular Service looks like this:
getAuthorizationStatus: function () {
var deferred = $q.defer();
$http({
method: "POST",
url: url,
data: {
'username': applicationConstants.userName,
'password': applicationConstants.userPass
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
}
}).success(deferred.resolve)
.error(deferred.reject);
return deferred.promise;
},
I am able to reach the webApi method but no matter how I do this, it always returns an error like this:
{"'object' does not contain a definition for 'username'"}
Any idea what I am doing wrong ?
I don't know ASP.net, but it seems that you are sending JSON data through a "x-www-form-urlencoded;" request.
You should either change 'data: ...' to 'username=,password=', or if you want to use JSON, use
'Content-Type': 'application/json'
If the web server is decent, it should detect you content type and interpret it as JSON instead of looking for "form" data.
Also consider using tools such as curl (or any webservice allowing you to send arbitrary HTTP requests) to test and understand what is going on.

Web service Spring ajax call

I'm trying to call a web service with ajax. The service is up, and it can shows the result on the RestClient on firefox, but, in mi application call, gives me Status error "Pending".
This is my simple web service.
#Controller
#RequestMapping("/hello")
public class HelloWs {
#RequestMapping(value= "/helloWorld", method = RequestMethod.GET, headers = "Accept=application/xml, application/json")
public #ResponseBody String HelloWorld() {
return "Hello Worldssss¡¡";
}
And this is my ajax call.
function hellowsfunction() {
$.ajax({
type: "GET",
url:"http://localhost:8080/ehCS-ui/rest/hello/helloWorld",
crossDomain: true,
dataType: "JSON",
headers : {Accept : "applicationjson","Access-Control-Allow-Origin" : "*"},
success: function(msg) {
var returnedData = jQuery.parseJSON(msg);
$("#lblResult")
.text(result)
.slideUp("hide", function() { $(this).slideDown("slow") });
},
error: function (e) {
$("#lblResult").removeClass("loading");
alert('failed:'+e);
console.log(e);
}
});
what is wrong? Ideas?¿ please help.
Thanks
Your #RequestMapping is wrong... you should not map based on Accept header like this. Instead you should use produces parameter.
#RequestMapping(value="/helloWorld", method=RequestMethod.GET,
produces={"application/xml", "application/json"})
Also your header in the JS is incorrect. Just remove their specification completely.

Categories

Resources