Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert underscore style query string into camel style property in a JavaBean in Spring MVC?

For example, here's a Get request:

get: /search?product_category=1&user_name=obama

I want to define a SearchRequest to accept the query string, so I can use JSR 303 bean validation annotations to validate parameters, like below:

public class SearchRequest {
    @NotEmpty(message="product category is empty")
    private int productCategory;
    @NotEmpty(message="user name is empty")
    private int userName;
}

So, is there something like @JsonProperty in jackson to convert underscore style to camel style?

like image 475
pat.inside Avatar asked Nov 09 '22 13:11

pat.inside


1 Answers

You only have two options;

First. Have your SearchRequest pojo with annotated values for validation but have a controller POST method receive the pojo as request body as a JSON/XML format.

public class SearchRequest {
    @NotEmpty(message="product category is empty")
    private int productCategory;
    @NotEmpty(message="user name is empty")
    private int userName;
}

public String search(@RequestBody @Valid SearchRequest search) {
    ...
}

Second. Have validations in the Controller method signature itself eliminating validations in the pojo but you can still use the pojo if you want.

public class SearchRequest {

    private int productCategory;

    private int userName;
}

public String search(@RequestParam("product_category") @NotEmpty(message="product category is empty") String productCategory, @RequestParam("user_name") @NotEmpty(message="user name is empty") String username) {
    ... // Code to set the productCategory and username to SearchRequest pojo.
}
like image 173
shazin Avatar answered Nov 15 '22 05:11

shazin