2013-02-21 119 views
3

我在我的應用程序中使用Spring MVC 3.1。說我有在控制器中的方法如下:@RequestParam自定義對象

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

我想通過對象我在輸入作爲請求參數選擇和執行某些操作與他們,但standart @RequestParam允許我只有原始類型和包裝,如我們所知。 我可以自定義這個以傳遞我的對象嗎?謝謝。

+0

是這些字段的json對象的值? – 2013-02-21 15:03:19

+0

不,它不是json對象 – sidlejinks 2013-02-21 15:16:44

回答

4

如果POJO直接涉及一種形式,在你的JSP 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> 
+0

也許你需要表單支持對象?每個輸入與類的屬性相關? – NimChimpsky 2013-02-21 15:21:42

+0

但我只有兩個選擇輸入映射到只有兩個自定義對象,而不是字段... – sidlejinks 2013-02-21 15:24:54