我刚开始使用来自Spring MVC多年的Django,并且表单实现有点疯狂。如果您不熟悉,Django表单会以定义您的字段的表单模型类开始。Spring同样从表单支持对象开始。但是,在Spring提供用于将表单元素绑定到JSP中的后备对象的taglib的地方,Django却具有直接绑定到模型的表单小部件。有默认的小部件,您可以在其中向您的字段添加样式属性以应用CSS或将完全自定义的小部件定义为新类。所有这些都在您的python代码中。对我来说这似乎很疯狂。首先,您将有关视图的信息直接放入模型中,其次将模型绑定到特定视图。我想念什么吗?
编辑:一些示例代码按要求。
Django:
# Class defines the data associated with this form
class CommentForm(forms.Form):
# name is CharField and the argument tells Django to use a <input type="text">
# and add the CSS class "special" as an attribute. The kind of thing that should
# go in a template
name = forms.CharField(
widget=forms.TextInput(attrs={'class':'special'}))
url = forms.URLField()
# Again, comment is <input type="text" size="40" /> even though input box size
# is a visual design constraint and not tied to the data model
comment = forms.CharField(
widget=forms.TextInput(attrs={'size':'40'}))
春季MVC:
public class User {
// Form class in this case is a POJO, passed to the template in the controller
private String firstName;
private String lastName;
get/setWhatever() {}
}
<!-- JSP code references an instance of type User with custom tags -->
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!-- "user" is the name assigned to a User instance -->
<form:form commandName="user">
<table>
<tr>
<td>First Name:</td>
<!-- "path" attribute sets the name field and binds to object on backend -->
<td><form:input path="firstName" class="special" /></td>
</tr>
<tr>
<td>Last Name:</td>
<td><form:input path="lastName" size="40" /></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save Changes" />
</td>
</tr>
</table>
</form:form>