Mapping angular Scope object to Java RestController - java

I am having a scope Object in Angular Controller.
When I try to pass it onto Spring Rest Controller , the control is passed to Spring rest controller. But when I try to print the value its getting printed as null.
Scenario:
AngularController :
file.upload = Upload.upload({
url : '/uploadTemplate',
data : {
multipartFile : file,
am : appMaster
}
});
RestController.java
#RequestMapping(value = "/uploadTemplate", produces = "application/json")
#ResponseBody
public StringResponse uploadFiles(MultipartFile multipartFile,ApplicationMaster am) {
System.out.println("Inside");
System.out.println(am.getAbbreviation());
System.out.println(am.getAppId());
System.out.println(am.getName());
}
The first System.out.println Inside is getting printed in console , but next the values of am object are printed as null.
If I alert the values in AngularController , the desired values are alerted.

Related

How to encode empty space in the request parameter in URL and get it in Spring Rest Controller?

I need to get data from DB using next endpoint
#GetMapping(path = "/path", produces = MediaType.APPLICATION_JSON_VALUE)
public ResultDto getResult(#RequestParam String value,
#RequestParam String secondParam )
{
returm service.getByvalueAndSecondParam(value, secondParam );
}
The problem is that the value in DB contains two empty tabs like "First second "
So, my request URL looks like
https://localhost:8080/path?value=First%20second%20&secondParam=second
I am using %20 to encode the empty space, but it doesn't work for some reason and I get "First second" without the last space in my controller method.
How to fix it? Thanks for any help!

how process comma separated parameter passed by angular in spring boot API

I am using angular 6 as front end. Using front end input I want to know the status of tracking id 3,5,6. How to process this. Below is my code:
Angular service code:
getConsignmentByTrackingid(trackingid): Observable<any> {
console.log(trackingid);
//tracking ids are : 3,5,6
return this.http.get(`${this.baseUrl}/trackingid/${trackingid}`);
}
Spring boot controller code:
#GetMapping(value = "/tracking_history/trackingid/{trackingid}")
public ResponseEntity<List<Tracking>> findByTrackingId(#PathVariable String trackingid){
try{
List<Tracking> trackings = trackingRepository.findByTrackingId(trackingid);
if (trackings.isEmpty())
{
return new ResponseEntity<List<Tracking>>(HttpStatus.NO_CONTENT);
//return new ResponseEntity<>(trackings, HttpStatus.NO_CONTENT);
}
//System.out.println(trackings);
//output of system.out.println is : 3,5,6.
//How can I return these numbers one by one
return new ResponseEntity<>(trackings, HttpStatus.OK);
}
}
IMO if you need to send data in the form of array or object then you should not use query parmas or params in the HTTP.
In this case Request type should be POST/PUT and you should pass the data in the body part like below -
http.post(url, {body: setOfIds})

Unexpected JSon response from Spring Rest API Controller

I have a method in my Spring controller, in which I am returning an object containing a spring attribute with a value "\HelloWorld". To store it into Java String object I have to put escape character, then the string becomes "\\HelloWorld". When I print, that works totally fine and prints "\HelloWorld". but when I return it in JSon response, it's returning "\\HelloWorld".
But I want it to return "\HelloWorld".
Bellow is the snippet:
#RequestMapping("")
#ResponseBody
public MyDataObject greeting() {
MyDataObject f = new MyDataObject();
f.setMessage("\\HelloWorld");
return f;
}
It's Json response is "message":"\\HelloWorld", but I want it "\HelloWorld".
Note: I don't want to unescape manually specific to that string.
You can use a library such as Jakson and it will internally handle such complexities.
MyDataObject f = new MyDataObject();
f.setMessage("\\HelloWorld");
String payload = new ObjectMapper().writeValueAsString(params);

Spring MVC - Ajax call returns JSON with Unterminated string

I'm very new to this, like really, really new.
I'm using Spring MVC (5.0) and am making an ajax call, as shown below.
This all works fine.
#RestController
public class AjaxController
{
#RequestMapping(value="/search/users", method=RequestMethod.GET)
public Person getUsers(#RequestParam("username") String username)
{
persons = personService.findPersonByUsername(username);
return persons.size() == 0 ? null : persons.get(0);
}
}
The method gets the person from the database and returns it.
According to the Spring Restful guide,
"The XXX object must be converted to JSON.Thanks to Spring’s HTTP message converter support, you don’t need to do this conversion manually. Because Jackson 2 is on the classpath, Spring’s MappingJackson2HttpMessageConverter is automatically chosen to convert the XXX instance to JSON."
So, Spring is automatically generating the JSON which will be returned to the client. The problem is, I get an error message in my client javascript:
SyntaxError: JSON.parse: unterminated string literal at line 1 column 103911 of the JSON data
My client javascript is equally simple, consisting of only:
function ajax_get_users(input_box)
{
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "users?username=" + username, true); // url of server-side ajax script, specify synchronous ajax call
// get asynchronous response
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var person = JSON.parse(this.responseText); // this is where the unterminated String error occurs
}
};
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // set http header
xhttp.send(); // send the ajax request to the web server
}
Since Spring is constructing the JSON, how do I even fix the problem?

AngularJS $http get return null status 0

I'm trying to create $http get request to fetch some json data generated by my web service, but it returns null error. However, the $http request works fine when I use this sample url instead (it returns json string too)
This is my angular code :
angular.module('ionicApp', ['ionic'])
.controller('ListCtrl', function ($scope, $http) {
$http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";
$http.get("http://localhost:8080/InventoryCtrl_Service/webresources/IVC_Service/GetUserList")
.then(function(response) {
console.log("success ");
},
function(response) {
console.log("Error : " + response.data + " Status : " + response.status);
}
});
This is my web service code :
#GET
#Path("/GetUserList")
#Produces("application/json")
public Response GetUserList() throws SQLException {
net.sf.json.JSONObject json = new net.sf.json.JSONObject();
JSONObject obj1 = new JSONObject();
JSONObject obj2 = new JSONObject();
JSONObject outerObject = new JSONObject();
JSONArray arr = new JSONArray();
obj1.put("Name", "Sara");
obj2.put("Name","David");
arr.add(obj1);
arr.add(obj2);
outerObject.put("records", arr);
return Response.status(200).entity(outerObject.toString()).build();
}
When I run the above code, it returns json string like this :
{"records":[{"Name":"Sara"},{"Name":"David"}]}
The console log returns this :
Error : null Status : 0
What is the meaning of the null error? Or is there anything wrong with how I return the json string?
Try using JSON_STRINGIFY, this will convert your incoming data into String format.
console.log(JSON_STRINGIFY(response.data));
TO verify what data your web service is returning, you can always check it by hitting your web service via postman.
I managed to solve this by adding CORS (Access-Control-Allow-Origin) to the response header, based on another SO answer. There's no problem with my angular code, it's just that I need to modify my web service code to enable the CORS. So I just modified the part where it returns data to become like this :
return Response.status(200).entity(outerObject.toString()).header("Access-Control-Allow-Origin", "*").build();

Categories