Java Ninja Chronicles By Norris Shelton

Things I learned in the pursuit of code

We had a need to know who was calling various web services. That is fairly easy to do when you have a standard URL. One solution is to simply grep your code repository for the URL (e.g. /my/service/). This becomes much more difficult when there is a path variable involved. An example URL with path variables is

@RequestMapping(value = "/mvc/customer/getState/{account}/more/url", method = RequestMethod.GET)

Lots of times, the URL is composed of multiple calls. A common way that this code will be found is below:

String url = String.format("/mvc/customer/getState/%s/more/url", accountNumber);
return restTemplate.getForObject(url, String.class);

This works, but makes it very difficult to determine who uses this web service call. You can grep for /mvc/customer/getState/ and that will work just fine if there aren’t multiple calls that use that same part of the URL in them. If there are other similar URLs, then effort will have to be expended to determine which are true hits and which are false hits.

There is another way to solve this problem if you are using the Spring’s RestTemplate. The RestTemplate can use the exact same URL pattern that is used by the web service URL pattern. This is accomplished by supplying a Map of data containing the path variable name and it’s corresponding value. An example is below:

Map<String, Object> params = new HashMap<>();
params.put("account", accountNumber);
return restTemplate.getForObject("/mvc/customer/getState/{account}/more/url", String.class, params);

August 5th, 2017

Posted In: Spring, Spring MVC, Spring RestTemplate

Leave a Comment

WP to LinkedIn Auto Publish Powered By :