2011-03-03 19 views

回答

0

我覺得春天做你想做的事情。

+0

燁,多數民衆贊成的接近形式一個表單庫,我可以找到可用,(http://static.springsource.org/spring-roo/reference/html/base-web.html)謝謝指出這一點。 – vinilios

+1

np。還有可以使用的spring-data項目。它可能會減少您的樣板jpa代碼。 http://static.springsource.org/spring-data/data-jpa/docs/1.0.0.M1/reference/html/。希望這有助於 – surajz

3

如果我已經正確理解了你,你是在將一個實體綁定到一個表單(並允許用戶添加/編輯實體)之後?在這種情況下,不需要另一個框架Spring已經做得很好。一個簡單的例子:

我們的控制器是這樣的:

@Controller 
@RequestMapping(value = "/addUser.html") 
public class UserController { 

    @Autowired 
    private UserAccountService service; 

    @Autowired 
    @Qualifier("userValidator") 
    private Validator userValidator; 

    @ModelAttribute("user") 
    public User getBackingObject() { 
    //This gets the object we're letting the user edit. 
    //This can be any POJO so a JPA entity should be fine. 
    //Note that we're creating an object here but we could 
    //just as easily fetch one we already have from a database/service etc 
    return new User(); 
    } 

    @RequestMapping(method = RequestMethod.GET) 
    public String showForm() { 
    //The form to present to the user 
    return "/addUser"; 
    } 

    @RequestMapping(method = RequestMethod.POST) 
    //note: here Spring has automatically bound the entries that have been input into the webform into the User param supplied here 
    protected String onSubmit(User user, Errors errors, HttpServletRequest request) { 

    userValidator.validate(user, errors); 
    if (errors.hasErrors()) { 
     //The validator showed up some errors so send the object back to let the user correct it 
     return "/addUser"; 
    } 

    //save our new user 
    service.saveUser(user); 

    //best practice is to redirect to another view to make sure the backing object is cleared 
    return "redirect:/success.html"; 
    } 

} 

然後我們可以使用Spring的表單宏在JSP中創建窗體:

<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> 
<html> 
<head> 
<title>Add a user</title> 
</head> 
<body> 

<form:form commandName="user"> 
    <label for="firstname">first name</label> 
    <form:input path="firstname" /> <form:errors cssClass="errorText" path="firstname" /> 
    <label for="lastname">last name</label> 
    <form:input path="lastname" /> <form:errors cssClass="errorText" path="lastname" /> 
    <input type="submit" value="Save" /> 
</form:form> 
</body> 
</html> 
+0

我見過類似的例子,但有沒有幫助避免爲我所有的實體實現控制器邏輯,它看起來對我來說太多的樣板代碼? – vinilios

+1

是的,正如surajz所提到的,Spring Roo是一個命令行工具,可以爲您編寫大量的膠水代碼。特別是如果你從頭開始你的項目,它值得檢查。這樣說,一旦你開始編寫控制器,你會發現這些小小的冗餘爲你提供了更多的能量來處理你的代碼。 – Sig

+1

所以爲了回答我最初的問題,沒有春天的表單框架可用。只是一堆輔助工具來創建樣板代碼。 – vinilios