开发者

Spring MVC Enforce Required Model Attributes

开发者 https://www.devze.com 2023-04-13 05:33 出处:网络
I\'ve been working with Spring MVC and have a question that I suppose relates to MVC in general. I\'m looking for a way to enforce (or at least better document) the contract between the model and spec

I've been working with Spring MVC and have a question that I suppose relates to MVC in general. 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. 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. D开发者_如何学编程oes anyone have any thoughts or ideas?

One thing that came to mind is to have a view Enum for each module. 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())). 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.


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:

<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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号