简体   繁体   English

Spring MVC强制执行必需的模型属性

[英]Spring MVC Enforce Required Model Attributes

I've been working with Spring MVC and have a question that I suppose relates to MVC in general. 我一直在使用Spring MVC,并且我想有一个通常与MVC有关的问题。 I'm looking for a way to enforce (or at least better document) the contract between the model and specific views. 我正在寻找一种执行(或至少更好地记录)模型与特定视图之间的契约的方法。 Ie, each view has a set of required model attributes, but to find these out, the person writing the controller has to read/understand the entire JSP (in addition to any tags or other JSP's included) so that they can populate the model appropriately before returning this view. 即,每个视图都有一组必需的模型属性,但是要找出这些属性,编写控制器的人必须阅读/理解整个JSP(除了包括任何标签或其他JSP之外),以便它们可以适当地填充模型返回此视图之前。 Or you can look at other places where this view is returned and work backwards, trying to figure out which attributes are required and which are optional. 或者,您可以查看返回此视图并向后工作的其他位置,以尝试找出哪些属性是必需的,哪些是可选的。 Neither of these is particularly appealing to me. 这些都不对我特别有吸引力。

Is the answer to just overpopulate the model? 只是过度填充模型的答案吗? I don't particularly like this idea. 我不太喜欢这个主意。 What I would like is a way to programatically document (or better yet, enforce) these required attributes on a per-view basis. 我想要的是一种基于每个视图以编程方式记录(或更好地实施)这些必需属性的方法。 I couldn't find anything in the Spring documentation that addressed this. 我在Spring文档中找不到任何解决此问题的方法。 Does anyone have any thoughts or ideas? 有没有人有任何想法或想法?

One thing that came to mind is to have a view Enum for each module. 我想到的一件事是每个模块都有一个Enum视图。 Each constant in the Enum would have the view name and a set of required model attributes (possibly a separate set of optional attributes as well). 枚举中的每个常量将具有视图名称和一组必需的模型属性(也可能是一组单独的可选属性)。 Controller methods would then return a member of this Enum, at which time the model could be validated (using something like model.keySet().containsAll(viewEnum.requiredAttributes())). 然后,控制器方法将返回此Enum的成员,这时可以验证模型(使用诸如model.keySet()。containsAll(viewEnum.requiredAttributes())之类的东西)。 It would still be a run-time error, but at least programmers could look at this Enum and see very clearly what model attributes are required for each view. 这仍然是一个运行时错误,但是至少程序员可以查看此Enum并非常清楚地看到每个视图需要哪些模型属性。

There is on facet of the problem that you have not considered yet: Data Dependend Constraints. 您还没有考虑到这个问题的一个方面:数据依赖约束。

For example if you have a simple if in your jsp, then this can make the whole stuff more complictated: 例如,如果您在jsp中有一个简单的if ,那么这会使整个过程更加复杂:

<c:if test="${formated}" >
   <c:out value="${prefix}">
</c:if>
<c:out value="${value}">
<c:if test="${formated}" >
   <c:out value="${postfix}">
</c:if>

So in general I believe there is no easy even no complex solution (mybe there is a very complex solution.) 因此,总的来说,我认为没有简单甚至没有复杂的解决方案(也许有一个非常复杂的解决方案。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM