How to map ModelAttribute properties?

I have a query displayed as

@RequestMapping(value = "/path", method = RequestMethod.POST) public ModelAndView createNewItem(@ModelAttribute PostRequest request) 

PostRequest has some properties, for example, for example. userName (getUserName()/setUserName()) , but the client sends parameters such as user_name=foo instead of userName=foo . Is there an annotation or a custom mapping interceptor to do this without putting all these ugly setUser_name() methods in setUser_name() ?

Since this happens very often (I have to implement an API where everything uses underscores), some implementation efforts are acceptable.

+4
source share
1 answer

Why not use the Spring Form Tag Library? http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/view.html#view-jsp-formtaglib

Taglib (in conjunction with your controller) automatically displays your ModelAttribute. When you execute a GET request for a form, you create a new (possibly empty) object of your PostRequest and insert it into the model. After POSTing, the Spring form exposes the form values ​​for the ModelAttribute parameter.

Example circuit:

Controller:

 @RequestMapping(value="/path", method = RequestMethod.GET) public String initForm(ModelMap model) { PostRequest pr = new PostRequest(); model.addAttribute("command", pr); return "[viewname]"; } @RequestMapping(value="/path", method = RequestMethod.POST) public ModelAndView postForm( @ModelAttribute("command") PostRequest postRequest) { // postRequest should now contain the form values logger.debug("username: " + postRequest.getUsername()); return "[viewname]"; } 

jsp:

 <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <form:form method="post" enctype="utf8"> Username: <form:input path="username" /> <br/> <%-- ... --%> <input type="submit" value="Submit"/> </form:form> 
0
source

Source: https://habr.com/ru/post/1401754/


All Articles