Spring mvc表单预填充:带有首选项的列表

时间:2011-04-04 08:08:20

标签: java forms spring-mvc dto

我在数据库中有用户语言首选项的数据。我想用Spring MVC管理Web应用程序前端的信息。我通过服务检索首选项,我想显示一个带有来自用户首选项的预填充数据的公式。

我有一个列表,其中包含我在控制器中通过服务获得的所有可用语言:

@RequestMapping
public String preferences(@ModelAttribute PreferencesDto preferencesDto, ModelMap modelMap, HttpServletRequest request) {        
    final List<Language> languages = languageService.getEuropeanLanguage();
    modelMap.addAttribute("languages", languages);

    List<Language> userLanguages = preferenceService.getUserLanguages(getLoggedUser()); 
    modelMap.addAttribute("userLanguages", userLanguages);

    modelMap.addAttribute("preferencesDto", preferencesDto);

    return "preferences";
}

在我的jsp中,我遍历语言列表以显示与语言相关的复选框:

<form:form commandName="preferencesDto">
    <c:forEach items="${languages}" var="language">
       <form:checkbox path="languages" value="${language}" id="cl${language.id}"/>
       ${language.code6391}
    </c:forEach>
    <input type="submit" value="Save"/>
</form:form>

我希望用户显示带有语言首选项的预填充复选框。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

您需要为可用语言添加属性,并设置用于表单的dto语言列表。

DTO:

public class PreferencesDto implements Serializable {
    private static final long serialVersionUID = 1L;
    private List<Language> languages = new ArrayList<Language>(0);

    public List<Language> getLanguages() {return languages;}
    public void setLanguages(List<Language> languages) {this.languages = languages;}
}

控制器:

@RequestMapping
public String preferences(@ModelAttribute PreferencesDto preferencesDto, BindingResult result, ModelMap modelMap, HttpServletRequest request) {        
    modelMap.addAttribute("preferencesDto", preferencesDto);
        // Manage available data
        modelMap.addAttribute("languagesAvailable", languageService.getEuropeanLanguage());        

        // pre-filled DTO with prefered languages
        preferencesDto.setLanguages(getPreferedLanguages(request));

    return "preferences";
}

/** Manage preferences languages for user logged */
private List<Language> getPreferedLanguages(HttpServletRequest request) {
        final List<Language> languagesSelected = new ArrayList<Language>(0);
        // TODO : call a service to get the prefered language for the logged user and fill the list
        return languagesSelected;
}

JSP:

<form:form commandName="preferencesDto">
    <c:forEach items="${languagesAvailable}" var="item">
        <form:checkbox path="languages" value="${item}"/>${item.code6391}
    </c:forEach>
    <input type="submit" value="Save"/>
</form:form>

或使用标签:

<form:checkboxes path="languages" items="${languagesAvailable}"/>

答案 1 :(得分:0)

最简单的方法是使用<form:checkboxes>标记(虽然根据您对问题的描述,但不清楚应该是pathitems):

<form:form commandName="preferencesDto"> 
     <form:checkboxes path = "languages" items = "${languages} />
</form:form>

另见: