2012-11-09 60 views
2

我使用JSR 303來驗證發送到我的應用程序的數據。我有一個控制器如何使用Spring MVC taglibs確定某個屬性是否無效?

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

    private UserService userService; 

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

    @RequestMapping(value = "https://stackoverflow.com/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; } 

    // ... 
} 

最後一個使用Spring表單標籤庫來呈現形式users.form.jsp

<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

解決方案是使用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>