Home » Java » java – Spring MVC – Query param with hyphens in name in POJO-Exceptionshub

java – Spring MVC – Query param with hyphens in name in POJO-Exceptionshub

Posted by: admin February 25, 2020 Leave a comment

Questions:

My Spring Boot Application has an API – GET : /employee

And request can have query params like (ALL with dash in the variable name) – first-name, last-name, phone-number, zip-code etc.

I also have to do sanity JAVAX validation( @Size, @Pattern etc. ) on these parameters, so I am consuming these params in a EmployeeRequest POJO ex. @Valid EmployeeRequest bean.

But in have variable names are not allowed with hyphens, so its not working.

I can do this by using –
@RequestParam(value = "first-name,required = false) String firstName

But by doing so, my controller method will have tens of arguments and I have to Javax validation explicitly, so I am trying to do using Request POJO.

Please provide the advise how we handle it where we have multiple query param with hyphens in name and needs Javax validation in Spring Boot application.

How to&Answers:

Soem code would make your question a bit easier to understand however is seems that you are looking for the following:

public class EmployeeRequest{

   @JsonProperty("first-name")
   private String firstName;

   @JsonProperty("last-name")
   private String lastName;

}

https://fasterxml.github.io/jackson-annotations/javadoc/2.6/com/fasterxml/jackson/annotation/JsonProperty.html

Defines name of the logical property, i.e. JSON object field name to
use for the property.