1

In my Spring web application, I have an API that accepts requests with application/x-www-form-urlencoded content type.

@RequestMapping(value = "/do-it", method = {RequestMethod.POST})
public String test(@ModelAttribute("request")RequestDTO request,HttpServletRequest
            httpServletRequest, Map<String, Object> model, RedirectAttributes redirectAttributes){

            .....
}

My RequestDTO has following fields in it.

public class RequestDTO {

    private String paramOne;

    private String paramTwo;

    // standard getters and setters

}

This implementation works fine, all the request params get mapped to the request dto as expected. However, now I have this requirement to accept the requests with the fields in following pattern.

param_one, param_two

I understand that, using @JsonProperty annotation on the fields in my request dto is not gonna work in my case since the request is not in the type of application/json.

The only way I have found to solve the issue is creating new setters like following (which looks ugly in my opinion when it comes to naming convention).

public void setParam_one(String param_one) {
        this.paramOne = param_one;
}

Can some one help me to find a better way to get this done? I cannot change the param names in original request dto.

Thank you..!

vigamage
  • 1,975
  • 7
  • 48
  • 74
  • 1
    Does https://stackoverflow.com/questions/8986593/how-to-customize-parameter-names-when-binding-spring-mvc-command-objects/9003314#9003314 answer your question? – Neetesh Bhardwaj Mar 11 '20 at 16:12
  • Well, it helped, not directly tho. I was able to find out a keyword from there which is "argument resolver". Then did a google search for it and found a way to get my work done. I will add it as the answer here – vigamage Mar 12 '20 at 08:00

1 Answers1

0

I was able to get this done. Thanks to @neetash for guiding me.

Everything I needed to have was a Custom HandlerMethodArgumentResolver to map the post request body data to the object that I wanted to get.

I followed following linked tutorial to implement it. It contains every single thing someone needs to know to create a HandlerMethodArgumentResolver.

https://www.petrikainulainen.net/programming/spring-framework/spring-from-the-trenches-creating-a-custom-handlermethodargumentresolver/

vigamage
  • 1,975
  • 7
  • 48
  • 74