sending HashMap by angularjs $http.get in spring mvc - angularjs

I want to send and retrieve HashMap through angularjs and receive it in springmvc controller. I have successfully send and received List but unable to send HashMap.
My code is.
$scope.addskill = function(skills){
// $scope.list = [];
// $scope.list.push(skills.skillName, skills.expMonth, skills.expYear, skills.experties);
var map = {};
map['name'] = skills.skillName;
map['month'] = skills.expMonth;
map['year'] = skills.expYear;
map['experties'] = skills.experties;
alert(map['name']);
var response = $http.get('/JobSearch/user/addskill/?map=' +map);
// var response = $http.get('/JobSearch/user/addskill/?list=' +$scope.list);
response.success(function(data, status, headers, config){
$scope.skills = null;
$timeout($scope.refreshskill,1000);
});
response.error(function(data, status, headers, config) {
alert( "Exception details: " + JSON.stringify({data: data}));
});
};
My mvc Controller is :
#RequestMapping(value = "/addskill", method = RequestMethod.GET)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void addStudentSkill(#RequestBody HashMap<String,String> map){
System.out.println(map.get("name"));
/*
* public void addStudentSkill(#RequestParam("list") List list){
try{
StudentSkills skills = new StudentSkills();
skills.setSkillName(list[0]);
skills.setExpMonth(Integer.parseInt(list[1]));
skills.setExpYear(Integer.parseInt(list[2]));
skills.setExperties(list[3]);
skills.setStudent(studentService.getStudent(getStudentName()));
studentService.addStudentSkill(skills);
}catch(Exception e){};
*/
}
Commented code works when i send and receive List. I want to use key to retrieve data. If there is any better way please suggest.
The error is cannot convert java.lang.string to hashmap

You're sending the map as a request parameter. And you're trying to read it in the request body. That can't possibly work. And GET requests don't have a body anyway.
Here's how you should do it:
var parameters = {};
parameters.name = skills.skillName;
parameters.month = skills.expMonth;
parameters.year = skills.expYear;
parameters.experties = skills.experties;
var promise = $http.get('/JobSearch/user/addskill', {
params: parameters
});
And in the Spring controller:
#RequestMapping(value = "/addskill", method = RequestMethod.GET)
#ResponseStatus(value = HttpStatus.NO_CONTENT)
public void addStudentSkill(#RequestParam("name") String name,
#RequestParam("name") String month,
#RequestParam("name") String year,
#RequestParam("name") String experties) {
...
}
That said, given the name of the method addStudentSkill, and the fact that it doesn't return anything, it seems this method is not used to get data from the server, but instead to create data on the server. So this method should be mapped to a POST request, and the data should be sent as the body:
var data = {};
data.name = skills.skillName;
data.month = skills.expMonth;
data.year = skills.expYear;
data.experties = skills.experties;
var promise = $http.post('/JobSearch/user/addskill', params);
and in the controller:
#RequestMapping(value = "/addskill", method = RequestMethod.POST)
#ResponseStatus(value = HttpStatus.CREATED)
public void addStudentSkill(#RequestBody Map<String, String> data) {
...
}

Related

Convert Json string to object List in angular controller MVC web application

Guys I'm stuck with something. I have to convert a Json string to an object list.
I am working on a MVC project and I'm in the middle of an API integration.
Here's the data of the problem. I managed to get data list(has a tree structure) object from a cloud api and converted it to a Json string in MY WEBAPI.
This is the query
var textvar = (from avbH in avb_Hotels
join catRs in cat_Rs on avbH.categoryCode equals catRs.code
join rep in hotelRepList on avbH.code equals rep.code
select new
{
code= avbH.code,
destinationCode = avbH.destinationCode,
description = rep.description,
hotelstar = catRs.simpleCode,
checkIn = hotelBooking.DepartureDate,
checkOut = hotelBooking.ReturnDate,
name = avbH.name,
address = rep.address,
accommodationTypeCode = rep.accommodationTypeCode,
minRate = (int)Math.Round(Convert.ToDecimal(avbH.minRate) * rates),
images = "http://photos.hotelbeds.com/giata/" + rep.imagepath,
rooms = avbH.rooms,
ratecomment = avbH.ratecomment,
});
This is the converting part and I returned it as a string to the webUI.
result = JsonConvert.SerializeObject(textvar2, Newtonsoft.Json.Formatting.None);// then returns result
I need to convert this again to a object tree in the angular controller of my webUI.
I tried angular.fromJson but it doesn't work
app.service("APIService", function($http) {
this.hotelavailability = function(sub) {
return $http({
method: "post",
data: sub,
contentType: "application/json; charset=utf-8;text/plain",
timeout:30000,
url: "/api/HotelBooking/Availability"
});
}
app.controller("APIController", function ($scope, $window, $http, filterFilter, APIService, States) {
var getAll = "";
getAll = APIService.hotelavailability(sub);
getAll.then(function (d) { // d has the returning Json string
console.log("Succss");
$scope.hotels = angular.fromJson(d.data); //deserialization<-- This doesnt work
console.log($scope.hotels);
$scope.respData = angular.fromJson(d.data);
}
This is d(returning Json string from the webAPI)
getAll.then(function (d) { // d has the returning Json string
console.log("Succss");
$scope.hotels = angular.fromJson(d.data);
$scope.hotellist = angular.fromJson($scope.hotels);
}
I think this will work.

Angularjs $http get not working

I am trying to access REST web service from angularjs. I am not able to call it successfully.
AngularJs Code
var singleOrderUrl = "/singleOrder/retrieve";
function getSingleOrderDetails(userName,singleOrderUrl,$http,$q) {
var fd = new FormData();
var deffered = $q.defer();
fd.append('USERNAME', 'test123');
//fd.append();
//fd.append();
console.log("inside service"+userName+"singleOrderUrl:::"+singleOrderUrl);
return $http.get(singleOrderUrl, fd, {
withCredentials : false,
transformRequest : angular.identity,
headers : {
'Content-Type' : undefined,
}
}).success(function(response) {
console.log(response);
responseData = response.data.toString();;
deffered.resolve(response);
return responseData;
}).error(function(error) {
alert("error");
deffered.reject(error);
return "failed";
});
};
Rest Service code
#RestController
public class SingleOrderHistoryController {
private static final Logger logger = LoggerFactory.getLogger(SingleOrderHistoryController.class.getName());
#RequestMapping(value = "/singleOrder/retrieve", method=RequestMethod.GET, produces="application/json")
public List<SingleHistoryRecord> getSingleOrderDetails(#RequestParam(value = Constants.USER_NAME, required = true) String userName, HttpServletRequest request,HttpServletResponse response) throws Exception {
logger.debug("inside SingleOrderHistoryController ");
List<SingleHistoryRecord> singleOrderHistoryList = new ArrayList<SingleHistoryRecord>();
SingleHistoryRecord record1 = new SingleHistoryRecord();
SingleHistoryRecord record2 = new SingleHistoryRecord();
record1.setClientIdentifier(userName);
record1.setSubmitDate("01/05/2017");
record1.setStatus("Complete");
record1.setReferenceID("1234555");
record1.setOrderID("test123");
record2.setClientIdentifier(userName);
record2.setSubmitDate("01/05/2017");
record2.setStatus("Complete");
record2.setReferenceID("1234555");
record2.setOrderID("test123");
singleOrderHistoryList.add(record1);
singleOrderHistoryList.add(record2);
return singleOrderHistoryList;
}
Can anyone please advise what I am doing wrong here, It is getting the source code of the page in response instead of getting the list.

Not able to expose the custom headers from WebAPI to client

I have written a program to download the pdf, word or txt file returned by web api and it's working fine. On server side I have used WebApi and client side AngularJs. Now the problem is, I also need the file name from api as well and for that I need to read the headers returned by api. But reponse.headers doesn't contains all the headers info. Below is my code:
[HttpGet]
[Authorize]
public HttpResponseMessage GetTranscript(string key, int format)
{
var badRequest = Request.CreateResponse(HttpStatusCode.OK, "Not a valid input."); //ResponseMessage(Request.CreateResponse(HttpStatusCode.BadRequest, "Not a valid input."));
if (string.IsNullOrWhiteSpace(jiraTaskKey))
{
return badRequest;
}
string transcript = _mediaCaptionService.GetTranscript(UserId, key);
string fileName = "transcript";
var response = new HttpResponseMessage(HttpStatusCode.OK);
if (format == (int)TranscriptFormat.PDF)
{
byte[] byteInfo = GeneratePDFTranscript(transcript);
response.Content = new ByteArrayContent(byteInfo);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
fileName = fileName + ".pdf";
}
else if (format == (int)TranscriptFormat.TXT)
{
response.Content = new StringContent(transcript, System.Text.Encoding.UTF8, "text/plain");
fileName = fileName + ".txt";
}
else if (format == (int)TranscriptFormat.WORD)
{
string transcriptFontName = "Arial";
byte[] byteInfo = GenerateWordTranscript(transcript, transcriptFontName);
response.Content = new ByteArrayContent(byteInfo);
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
fileName = fileName + ".doc";
}
else
{
return badRequest;
}
response.Content.Headers.Add("x-filename", fileName);
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment") {
FileName = fileName
};
//response.Content.Headers.ContentDisposition.FileName = fileName;
return response; //ResponseMessage(response);
}
and in client side
function getTranscriptResult(method, apiUrl, data) {
var deferred = $q.defer();
$http({
method: method,
url: apiUrl,
data: data,
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
debugger;
var results = [];
results.data = data;
results.headers = headers();
results.status = status;
results.config = config;
deferred.resolve(results);
}).error(function (error, status, headers, config) {
deferred.reject(error);
});
return deferred.promise;
}
But when I put the break point in above code, I get this:
Can you please tell me where is the problem in my code that I am not able to get the file name? Also please let me know if you need more information.
After adding below lines has solved my problem.
// Add a custom header for filename and expose it to be consumed by JavaScript.
response.Content.Headers.Add("Filename", zipFileName);
response.Content.Headers.Add("Access-Control-Expose-Headers", "Filename");
So basically adding Access-Control-Expose-Headers helped me to expose the custom headers to client. For more information on this please follow this link

How to send a string value to a function (ng-click)

I've got a very simple questions;
Here's my HTML;
<button ng-click="projectTypeController.deleteProjectType(pt.Code)">X</button>
And my function in my controller:
self.deleteProjectType = function (projectTypeCode) {
$http.post('http://localhost:49165/Service1.svc/projecttypes/delete/', projectTypeCode)
.then(getProjectTypes)
.then(function (response) {
});
};
Code in my webservice:
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "ProjectTypes/Delete/", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
void DeleteProjectType(string projectTypeCode);
This works perfectly fine as long as 'pt.Code' is numeric, but as soon as it's a string it results in a HTTP 400 Bad Request. So I think i'm doing something wrong with the deleteProjectType(pt.Code) Part.
I tried to look for examples where they pass a string into a method, but i cannot find anything...
the pt.Code = a scope variable by the way, also adding data in the form of object inside a form element works fine, so passing strings in an object is not a problem, just passing a single string, instead of an integer to a method doesn't seem to work
You need to format the parameter as a valid json.
To do that you can use JSON.stringify().
To implementet this in the method
self.deleteProjectType = function (projectTypeCode) {
$http.post('http://localhost:49165/Service1.svc/projecttypes/delete/', JSON.stringify(projectTypeCode))
.then(getProjectTypes)
.then(function (response) {
});
};
I prefere to use objects instead of just sending a value as a string.
If you at any time need to extend the body then you only need to add more fields to the objects and not modify the function call or the service method.
Here's an example of how you could do that
self.deleteProjectType = function (projectTypeCode) {
var data = { code: projectTypeCode};
$http.post('http://localhost:49165/Service1.svc/projecttypes/delete/', JSON.stringify(data))
.then(getProjectTypes)
.then(function (response) {
});
};
Create the class server side
Public class ProjectTypeDTO
{
public string code { get; set; }
}
Add the class as the parameter in the service method and you are gtg
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "ProjectTypes/Delete/", RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
void DeleteProjectType(ProjectTypeDTO pt);

Error 500 in Angularjs $http.post and webservice asmx

I try to make a validatión with a webservice and $http from angular, the problem is an error 500 when i try to send data, if i call webservice without data works perfectly, the code:
Angularjs
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.post('/CloudMobile/gpvdata.asmx/validausuario', {username: username, password: password}).success(function(data, status, headers, config) {
$rootScope.datos = data[0];
console.log($rootScope.datos.grupo);
callback({success: true});
}).error(function(data, status, headers, config) {
console.log('Falla la validación en el asmx');
});
Webservice
[WebMethod]
public void validausuario(string usuario, string password)
{
TGlobalOpClases g = miGlobal(usuario, password);
t1ValidacionSistema val = new t1ValidacionSistema(g);
Resultado_BD ResBD = val.Valida("SYSTEM_GPV", "DEMO", DateTime.Now);
g.idUsuarioConsola = val.Datos.idUsuario;
if (ResBD.ok)
{
t1Usuario user = new t1Usuario(g);
Entrada_OPBD x = new Entrada_OPBD();
x.PonLanzarEx();
user.FichaCarga(x,g.idUsuarioConsola);
user.GruposPertenece_Carga(x);
string jsn = Json.Encode(user.GruposPertenece);
HttpContext.Current.Response.Write(jsn);
}
else {
HttpContext.Current.Response.Write("Fallo la conexión");
}
}
public TGlobalOpClases miGlobal(string usuario, string password)
//public TGlobalOpClases miGlobal()
{
ExEngine_Client.TGlobalOpClases global = new TGlobalOpClases();
global.miParIniOP.password = password;
global.miParIniOP.Usuario = usuario;
global.Server = "192.168.0.16\\sql";
global.DataBase = "Desarrollo";
global.Conecta();
return global;
}
Thanks.

Resources