Reputation: 870
I want to trigger a method to create a ArrayList
and return
this list to a callback-URL
. This method can take a while until the data has been generated so it should be an asynchronous running method.
So I got a few questions:
callback-URL
? I assume it's the URL
the method is returning the value to?return
a value
to a callback-URL
?How to access the value after it has been returned?
@Async
@GetMapping("/createcustomer/{start}/{end}"){
public ArrayList<Customer> createCustomer(@PathVariable int start,
@PathVariable int end) {
//code to generate random data
return arrayList;
}
Upvotes: 0
Views: 670
Reputation: 696
In order to call your handler method you can use javascript code on your front-end side. Here is an example how you can do it with axios library:
axios.get('createcustomer/something/something')
.then(function (response) {
console.log(response);
// response.data will contain your json with returned list content
})
.catch(function (error) {
console.log(error);
});
You will also need to modify your hanlder method like this:
@ReponseBody
@GetMapping("createcustomer/{start}/{end}"){
public ArrayList<Customer> createCustomer(@PathVariable int start,
@PathVariable int end) {
//code to generate random data
return arrayList;
}
The @ResponseBody annotation will cause the ArrayList to be returned as json in the body of the response. Alternatively, you can change @Controller class annotation to @RestController. It will make all your handler methods in this class to return back to the client.
This way, the request will be totally asynchronous and you can access it in your front-end code as soon as it's available.
Edit:
If you want to send this list somewhere else using callback-url, you can use RestTemplate to send post request with list as body. You can use something similiar to this code inside your handler method:
String callback-URL = "http://my.server.com/customerListEndpoint";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<?> entity = new HttpEntity<>(headers);
restTemplate.exchange(callback-URL,HttpMethod.POST,entity,ArrayList.class);
You need an endpoint that can be mapped with post requests to callback-URL. Something like:
@PostMapping("/customerListEndpoint"){
public void createCustomer(@RequestBody ArrayList<Customer> arrayList) {
// do what you want with arrayList here
}
Also, be sure to configure the RestTemplate bean in some class anottated with @Configuration:
@Bean
public RestTemplate restTemplate() {
SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();
requestFactory.setOutputStreaming(false);
RestTemplate restTemplate = new RestTemplate(new BufferingClientHttpRequestFactory(requestFactory));
restTemplate.getMessageConverters()
.add(0, new StringHttpMessageConverter(Charset.forName("UTF-8")));
return restTemplate;
}
Upvotes: 1