2016-08-28 36 views
1

enter code here我有一個控制器,下面兩個url映射爲名爲Member的業務對象的GET和POST。在jsp中使用JSTL查看未正確綁定<form:select> jsp中的標籤

控制器:

@RequestMapping(value = "/usr/updateMember", method = RequestMethod.GET) 
public ModelAndView findForEdit(@RequestParam("id") Integer id) { 
    ModelAndView modelAndView = new ModelAndView("registration"); 
    try { 
     List<City> cities = getGenericDao().getAllItems(City.class); 
     List<Chapter> chapters = getGenericDao().getAllItems(Chapter.class); 
     modelAndView.getModel().put("cities", cities); 
     modelAndView.getModel().put("chapters", chapters); 

     Member member = getGenericDao().getItem(Member.class, id); 
     modelAndView.getModel().put("edit", true); 
     modelAndView.getModel().put("loggedinuser", getPrincipal()); 
     modelAndView.getModel().put("roles", userRoleService.findAll()); 

     modelAndView.getModel().put("member", member); 
    } catch (Exception e) { 
     System.out.println(e.getMessage()); 
    } 
    return modelAndView; 
} 

@RequestMapping(value = "/usr/updateMember", method = RequestMethod.POST) 
public String update(@ModelAttribute("member") Member member, BindingResult result, SessionStatus status) { 
    getGenericDao().update(member); 
    status.setComplete(); 
    return "redirect:/list.do"; 
} 

我的看法如下:

<form:form method="POST" modelAttribute="member" 
      class="horizForm"> 
    <div class="row"> 
     <div class="form-group col-md-"> 
      <label class="col-md-3" for="name">Member 
       Name</label> 
      <div class="col-md"> 
       <form:input type="text" path="name" id="name" 
        class="form-control input-sm" /> 
       <div class="has-error"> 
        <form:errors path="name" class="help" /> 
       </div> 
      </div> 
     </div> 
    </div> 
    ... 
    <div class="row"> 
     <div class="form-group col-md-12"> 
      <label class="col-md-3" for="userRoles">Roles</label> 
      <div class="col-md"> 
       <form:select path="userRoles" items="${roles}" multiple="true" 
        itemValue="memberId" itemLabel="role" 
        class="form-control input-sm" /> 
       <div class="has-error"> 
        <form:errors path="userRoles" class="help" /> 
       </div> 
      </div> 
     </div> 
    </div> 

    <div class="row"> 
    <div class="form-group col-md-"> 
     <label class="col-md-3 control-labl" for="chapter">Chapter</label> 
     <div class="col-md-7"> 
      <%-- <form:select path="chapter.id" items="${chapters}" itemValue="id" 
       itemLabel="name" class="form-control input-sm"> --%> 
      <%-- <option value="-1">Select a Chapter</option> 
       <c:forEach var="chp" items="${chapters}"> 
        <option value="${chp.id}">${chp.name}</option> 
       </c:forEach> --%> 
      <%-- </form:select> --%> 

      <form:select path="chapter" class="form-control input-sm"> 
       <!-- <option value="-1">Select a Chapter</option> --> 
       <c:forEach var="chp" items="${chapters}"> 
        <option value="${chp}">${chp.name}</option> 
       </c:forEach> 
      </form:select> 

      <div class="has-error"> 
       <%-- <form:errors path="chapter.id" class="help-inline" /> --%> 
       <form:errors path="chapter" class="help-inline" /> 
      </div> 
     </div> 
    </div> 
</div> 

GET正在按預期和看法是填充的字符串,列表和預期值章類型的對象。

GET Method working fine

當我嘗試更新的會員通過POST它不會綁定到列表和章對象和BindingResult低於值的值。

org.springframework.validation.BeanPropertyBindingResult: 3 errors 
Field error in object 'member' on field 'chapter': rejected value [Chapter [chapterId=1, chapterName=SUPER]]; codes [typeMismatch.member.chapter,typeMismatch.chapter,typeMismatch.com.codex.survey.beans.Chapter,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [member.chapter,chapter]; arguments []; default message [chapter]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'com.codex.survey.beans.Chapter' for property 'chapter'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.codex.survey.beans.Chapter] for property 'chapter': no matching editors or conversion strategy found] 
Field error in object 'member' on field 'userRoles': rejected value [2]; codes [typeMismatch.member.userRoles,typeMismatch.userRoles,typeMismatch.java.util.List,typeMismatch]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [member.userRoles,userRoles]; arguments []; default message [userRoles]]; default message [Failed to convert property value of type 'java.lang.String' to required type 'java.util.List' for property 'userRoles'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [java.lang.String] to required type [com.codex.survey.beans.UserRole] for property 'userRoles[0]': no matching editors or conversion strategy found] 

我無法確定這裏出現什麼問題,請幫我解決這個問題。

感謝您的期待。

回答

0

與有狀態的基於組件的框架(例如JSF)不同,Spring MVC不能自動將原始HTTP參數轉換爲相應的對象類型。

因此,您需要註冊一個轉換器來處理這個問題並將其註冊到Spring上下文中。這樣做有一個但是實施的各種方式會是什麼樣子:

@Component 
public class StringToChapterConverter implements Converter<String, Chapter> { 

    @Autowired 
    private ChaperService service; 

    /** 
    *chapterId is the HTTP post param passed in by the framework 
    */ 
    public Chapter convert(String chapterId) { 
     return service.findChapter(Integer.parseInt(chapterId)); 
    } 
} 

你如何去註冊這個要看你的配置。但是假設Java代碼的配置,則:

@Configuration 
@EnableWebMvc 
@ComponentScan(basePackages = { "..." }) 
public class MvcConfiguration extends WebMvcConfigurerAdapter{ 

    //other configuration 

    @Override 
    public void addFormatters(FormatterRegistry formatterRegistry) { 
     formatterRegistry.addConverter(getChapterConverter()); 
    } 

    @Bean 
    public StringToChapterConverter getChapterConverter(){ 
     return new StringToChapterConverter(); 
    } 
} 

所以,現在上述到位時,如果有合適的轉換器已經爲章規定的要求由被綁定到章對象框架會看看,看看然後調用相應的convert(String source),它使您可以從數據庫或任何地方返回實例。

另見:

http://docs.spring.io/spring/docs/current/spring-framework-reference/html/validation.html#core-convert

+0

感謝艾倫的提示,我錯過了轉換器部分,將檢查,我希望它會奏效。 –

+0

艾倫的建議解決了我的問題。 –