如何使用Spring MVC taglib确定某个属性是否无效?

时间:2012-11-09 19:28:44

标签: spring spring-mvc jsp-tags bean-validation

我使用JSR 303来验证发送到我的应用程序的数据。我有一个控制器

@Controller
@RequestMapping("/users")
public class UserController {

    private UserService userService;

    @RequestMapping(value = "/users", method = GET)
    public String index(Model model) {
        // ...
        return "users.index";
    }

    @RequestMapping(value = "/users/create", method = POST)
    public String create(@Valid @ModelAttribute("userForm") UserForm userForm, BindingResult bindingResult, Model model) {
        if (bindingResult.hasErrors()) {
            return "users.form";
        }
        userService.addUser(userForm);
        return "redirect:users";
    }   
}

UserForm

public class UserForm {   
    private String email;

    // ...

    @Email
    public String getEmail() { return email; }

    // ...
}

最后一个users.form.jsp使用Spring表单taglib来呈现表单。

<form:form action="users" method="post" commandName="userForm">
    <fieldset>
        <legend>Create User</legend>

        <div class="control-group">
            <form:label path="email">Email</form:label>
            <div class="controls">
                <form:input path="email"/>
                <form:errors path="email" cssClass="help-inline" />
            </div>
        </div>

        <%-- More Fields, Buttons --%>
    </fieldset>
</form:form>

我想将一个CSS类添加到div.control-group。这可能是使用Spring MVC表单taglib吗?如何确定bean的属性在视图中是否无效?

1 个答案:

答案 0 :(得分:1)

解决方案是使用Spring bind标记。您可以通过${status}访问绑定状态,并可以通过${status.error}查询是否存在错误。这会产生以下代码段:

<form:form action="users" method="post" commandName="userForm">
    <fieldset>
        <legend>Create User</legend>

        <spring:bind path="email">
            <c:if test="${status.error}"><c:set var="classes">error</c:set></c:if>
            <div class="control-group ${classes}">
                <form:label path="email">Email</form:label>
                <div class="controls">
                    <form:input path="email"/>
                    <form:errors path="email" cssClass="help-inline" />
                </div>
            </div>
        </spring:bind>

        <%-- More Fields, Buttons --%>
    </fieldset>
</form:form>