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})
Related
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);
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?
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.
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();
I have a real problem but simple,really , i have an edit form that edits a record of a table, i have a value in it that it has to be unique ex:username,i using jquery validation plugin to validate, so i use the remote method like so:-
companyName: {
required: $("input#companyRequired").val(),
remote: "validator/checkCompanyName"
}
and it enters a method from the server that checks the value from the database,here's the method to check:-
#RequestMapping(value = "/checkCompanyName", params = "companyName")
public #ResponseBody
String checkCompanyName(#RequestParam String companyName) {
logger.debug("checking company : " + companyName);
if(leadService.checkCompany(companyName)==true){
return "false";
}
else{
return "true";
}
}
the problem is that i want to use remote only if the user has changed the input,so what should i do?,any help would appreciated,i'am using spring mvc as a server side
If you want to trigger validation only when user changes input value try that approach:
$("input#companyRequired").change(function(){
$("input#companyRequired").validate(
// rules here
)
});
If you want to validate several elements add class "remote-check" (or come up with your name) to that fields:
$("input.remote-check").change(function(){
$(this).validate(
// rules here
)
});