3

我在我的应用程序中使用 Spring MVC 3.1。假设我在控制器中有一个方法如下:

@RequestMapping(value = "/assignUser", method = RequestMethod.GET)
public String assignUserToCompany(ModelMap map){
    List<CompanyDetails> companies = //companies list from DAO
    List<UserDetails> users = //users list from DAO
    map.addAttribute("companiesList",companies);
    map.addAttribute("usersList",users);
    return "someView";
}

@RequestMapping(value = "/assignUser", method = RequestMethod.POST)
    public String assignUserToCompany(@RequestParam("user")UserDetails user,
                                      @RequestParam("company")CompanyDetails company){

    if(user!=null && company!=null){
      // some operations with entities
    }

    return "someView";
    }

我在视图方面有一个表格:

<form method="post" action="assignUser.html">
        <label for="select-users"><spring:message code="assignUser.label.users"/> </label>
        <select id="select-users" name="user">
            <c:forEach items="${usersList}" var="user">
                <option value="${user}">${user.firstName} ${user.legalName}</option>
            </c:forEach>
        </select>
        <label for="select-companies"><spring:message code="assignUser.label.companies"/> </label>
        <select id="select-companies" name="company">
            <c:forEach items="${companiesList}" var="company">
                <option value="${company}">${company.name}</option>
            </c:forEach>
        </select>
        <input type="submit" value="<spring:message code="assignUser.label.submit"/>"/>
    </form>

我想将我在输入中选择的对象作为请求参数传递并使用它们执行一些操作,但标准 @RequestParam 只允许我们知道原始类型和包装器。我可以自定义它以传递我的对象吗?谢谢你。

4

1 回答 1

4

如果 pojo 直接与表单相关,请在您的 jsp 中声明一个 spring 表单(假设您的 DTO 有一个属性名称......

 <form:form id="yourForm" commandName="yourDTO" action="Save" method="POST">
 <form:input path="name" maxlength="90" cssStyle="width: 650px;" id="name"/>

和你的控制器:

@RequestMapping(value = "/Save", method = RequestMethod.POST)
public ModelAndView save(final yourDTO yourDTO) {

或者,如果将一个字段转换为复杂的类,您将必须提供转换服务:

@Component
public class FooConverter implements Converter<String, Foo> {
    @Override public Foo convert(String source) {
        //do covnersion from string to Foo
        Foo foo = new Foo(source)
        return Foo;
    }
}

并注册

<bean id="conversionService"
          class="org.springframework.context.support.ConversionServiceFactoryBean">
        <property name="converters">
            <set>
                <bean class="com.yourcompany.controller.converters.FooConverter"/>
            </set>
        </property>
    </bean>
于 2013-02-21T15:04:58.760 回答