@RequestParam自定义对象

时间:2013-02-21 15:01:40

标签: spring-mvc

我在我的应用程序中使用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只允许我使用原始类型和包装器。 我可以自定义这个以传递我的对象吗?谢谢。

1 个答案:

答案 0 :(得分:4)

如果pojo直接与表单相关,请在jsp中对spring形式进行decalre(假设yourDTO有一个属性名称......

 <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>