Code logic to manage a @RequestParam with different params Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Code logic to manage a @RequestParam with different params without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am creating a service to retrieve data

@RequestMapping(value = "/{productId}/freeTrial", method = RequestMethod.GET)
@ResponseBody
public RestResponse<List<RetrieveFreeTrialResponse>> retrieveServiceFreeTrialsByProductIdWithParam(
        @PathVariable String productId,
        @RequestParam(value = "addFields", required = false) String field) {
    if("includeDeleted".equals(field)) {
        return retrieveFreeTrialsActivity.retrieveFreeTrialsByProductId(productId, true);
    } else {
        return retrieveFreeTrialsActivity.retrieveFreeTrialsByProductId(productId, false);
    }
}

I was working with either no param or with includeDeleted. Now I have to add the possibility for addFields to also accept another value: onlyActive.

Is there any way to avoid writing 4 if/else statements to return the right method depending on which params I pass to the URL? Also, I assume “String field” should be changed to String[] field right?

Valid requests would be:

/productId/freeTrial?addFields=includeDeleted,onlyActive
/productId/freeTrial?addFields=includeDeleted
/productId/freeTrial?addFields=onlyActive
/productId/freeTrial

Answer

So as far as I understand now, you can accept the following formats:

/productId/freeTrial?addFields=includeDeleted,onlyActive
/productId/freeTrial?addFields=includeDeleted
/productId/freeTrial?addFields=onlyActive
/productId/freeTrial

Get addFields as an array of String. Then calculate the value of the boolean you want to pass, and call your method with your boolean.

In the example below, I will assume that you only want to send true if includeDeleted is present and onlyActive is not. You can implement whatever algorithm you want.

  @RequestMapping(value = "/{productId}/freeTrial", method = RequestMethod.GET)
  @ResponseBody
  public String retrieveServiceFreeTrialsByProductIdWithParam(
      @PathVariable String productId,
      @RequestParam(value = "addFields", required = false) String[] addFields) {

    List<String> addFieldsList = new ArrayList<>();
    if(addFields!=null)
      addFieldsList = Arrays.asList(addFields);  

    boolean isIncludeDeleted = addFieldsList.contains("includeDeleted");
    boolean isOnlyActive = addFieldsList.contains("onlyActive");

    // here you define your algorithm
    boolean b = isIncludeDeleted && isOnlyActive;

    return retrieveFreeTrialsActivity().retrieveFreeTrialsByProductId(productId, b);
  }
We are here to answer your question about Code logic to manage a @RequestParam with different params - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji