4

我有一个映射的请求

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

并且 PostRequest 具有一些属性,例如userName (getUserName()/setUserName()),但是客户端发送的参数例如user_name=foo而不是userName=foo. 是否有注释或自定义映射拦截器可以在不放置所有这些丑陋setUser_name()方法的情况下执行此操作?

由于这种情况经常发生(我必须实现一个API,其中所有内容都使用下划线)在实现方面付出一些努力是可以接受的。

4

1 回答 1

0

为什么不使用 Spring 的表单标签库?http://static.springsource.org/spring/docs/3.1.x/spring-framework-reference/html/view.html#view-jsp-formtaglib

taglib(与您的控制器结合)自动映射您的 ModelAttribute。在对表单执行 GET 请求时,您会创建 PostRequest 的新(可能是空的)对象并将其粘贴到模型中。在发布表单后,spring 会为您提供带有表单值的 ModelAttribute。

示意图示例:

控制器:

@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>
于 2012-04-14T15:02:08.017 回答