Hello friend, today I am going to show you how to user a String[] array as an input parameter of a request. This is useful when you want to receive a series of values and then use them for any purpose.
So, let’s get started. Imagine you are creating a controller to read all pages of a CMS given the parent page, but these pages have states as integer values, so you would like to have a method that receives a list of integers (states) and then make a query to the database to get all pages that have the states in the input array.
1) In your controller class you will need to create a method -I would recommend to use Spring annotations-.
@RequestMapping( value = "/pages/get-by-parent/{parentUuid}", // The {parentUuid} is a PathVariable method = RequestMethod.GET, // This request is only valid when the request was done by GET method produces=MediaType.APPLICATION_JSON_VALUE) // Result will be returned in JSON public ResponseEntity<List<WikiPage>> getWikiPagesList( @PathVariable("parentUuid") String parentUuid, // This matches with the path variable {parentUuid} @RequestParam(value="includeStates[]", defaultValue="1,2,3") String[] includeStates // List of states to include ){ // Do something here! }
Please, pay attention to the line, because that is the one that contains an array of String as input.
@RequestParam(value="includeStates[]", defaultValue="1,2,3") String[] includeStates // List of states to include
In this case, I am setting some default values: “1,2,3” in order to return pages with states 1, 2 or 3 in case the parameter includeStates[] is not present in the request. Of course, you can personalize this method to receive any other parameters.
I hope you find this tip useful for your development.
See you next time and remember, be happy with your code!
How to use array of #String as input parameters in a request for a #Java application using #SpringMVC annotations: http://t.co/6FKO36aOAO