2

这是一个模糊而宏大的问题,但希望我能用尽可能少的具体例子来解释它。

我们最近为我们的应用程序框架切换到 Spring MVC,但在开发过程中发现了一个(实际上只有一个)限制因素:如何将动态视图包含在适当的模型中。

例如,我们正在创建一个包含可重用片段的页面。在左侧,我们有一个“随机 q 和 a”片段,而在顶部,我们有一个共同的“导航”片段。

这些片段中的每一个都需要不同的模型。我一直在指导正在创建“导航”部分的开发人员创建一个导航模型、控制器和视图,它们完全独立于“q 和 a”模型、控制器和逻辑。这是为了鼓励可重用性,如果另一个页面布局想要“导航”而不是“q 和 a”,反之亦然。

你知道我要去哪里吗?“主页”页面包含两个片段,但不必“知道”片段需要哪个控制器/模型/视图会很好。

我一直在指导开发人员以下列方式使用 Spring MVC....

home.jsp 示例:

<body>
    <div class="top">
        <jsp:include page="/navigation"/>
    </div>
    <div class="left">
        <jsp:include page="/randomgQuestion"/>
    </div>
</html>

这个想法是在请求时,必要的其他片段将与他们需要的模型一起动态地拉入。

这是一个好主意吗?有没有更好的办法?

欢迎任何讨论,但请保持建设性。

目标是可重用性和愚蠢的观点。

我会根据要求提供任何更新或说明。谢谢你。

4

2 回答 2

4

您所描述的感觉有点像门户/portlet 功能 (JSR-286) => 即应用程序(门户)生成网页,这些网页由其他嵌入式应用程序(portlet)生成的内容组成。门户使用 INCLUDE 调度(相当于<jsp:include>)来提供 JSR-286 功能。所以从这个角度来看,使用<jsp:include>提供可重用的内容块是一个好主意,每个内容块都有自己的 MVC 生命周期(尽管共享相同的请求属性命名空间)...

另请注意,如果您只有一个简单的片段,并且希望在 JSP 之间重用它,那么简单的片段<%@include file="menu.jspf" %>可能更合适。

而且我也觉得应该提一下JSP标签功能……把可复用的内容做成JSP TAG文件(/WEB-INF/tags/[taglib-folder/]*.tag)可以提供一些高级的布局特性。对于更高级的功能,您可以实现基于 Java 的标记库。


为了说明我如何在一个项目中使用自定义 TAG 和 include 指令,下面是一个 JSP 视图:

<%@ include file="/WEB-INF/taglib.jspf" %>
<layout:admin section="test">
    <layout:admin-context />
    <layout:admin-content>
        <h1><spring:message code="test.overview.heading" /></h1>
        <h2><spring:message code="test.detail.heading" /></h2>
        <%@ include file="test-detail.jspf" %>
    </layout:admin-content>
</layout:admin>

我们没有需要 INCLUDE 调度(即<jsp:include />)的用例。

于 2014-05-13T10:19:20.633 回答
2

Well in terms of your UI, Apache Tiles and Sitemesh are things you might want to look at here.

In terms of the controller layer, Spring has the @ControllerAdvice annotation which can be used to place model attributes in scope for all controllers. If, for example, you placed the navigation model in your @ControllerAdvice, no other controller would have to worry about setting it as a model attribute.

http://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/mvc.html

@ModelAttribute methods can also be defined in an @ControllerAdvice-annotated class and such methods apply to all controllers. The @ControllerAdvice annotation is a component annotation allowing implementation classes to be autodetected through classpath scanning.

于 2014-05-12T21:38:13.627 回答