2

我使用 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 表单标记库来呈现表单的程序。

<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 表单标记库吗?如何确定 bean 的属性在视图中是否无效?

4

1 回答 1

1

解决方案是使用 Springbind标签。可以通过 访问绑定状态${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>
于 2012-11-10T11:55:10.367 回答