2

I've just started studying Spring, and I'm trying to make a web application. I have some common UI elements such as footer, header, sidebar and also want to add dynamic blocks, i.e. widgets. What widgets to include need to be chosen in Java code, not JSP template.

And that's where I'm stuck. Every controller returns it's own view - main.jsp which includes some static and dynamic blocks:

 <jsp:include page="head.jsp" />  
     <c:forEach items="${viewList}" var="viewName">
                 <jsp:include page="${viewName}.jsp" />    
    </c:forEach>
...

In controler I'm passing view list and object that will be used as widget to model:

 ...
 views.add(moduleOne.getViewName());
 views.add(moduleTwo.getViewName());
 model.addAllAttributes(moduleOne.getAttr());  
 model.addAllAttributes(moduleTwo.getAttr());  
 model.addAttribute(IModule.VIEW_LIST, views); // passing all views that will be included into main.jsp
 ...
 return "main";

But it doesn't work because when I use jsp:include page model parameters do not pass to includee. Also I can't %@include file= because in that case I won't be able to use variables and I would need to know which view to pass at compile time.

Of course if there's no solution, I'll have to hardcode all possible widget views in main.jsp and switch between them:

   switch($i) {
    case 1: 
          include file=widget1.jsp;
          break;
    case 2: 
        include file=widget2.jsp;
        break;
      ...                    
    }

Which is obviously not flexible.

So, the questions are:

  1. Is there any way to solve the problem of passing model to include views without using %@include file= and make my widgets working?
  2. Is there some better way to implement such widgets structure?

Thank you!

4

1 回答 1

0

您始终可以使用模型属性来决定要包含哪个文件

model.addAttribte("fileToInclude",IncludeFile.HEADER);

接着

<c:choose>
<c:when test="${fileToInclude == 'HEADER'}">
<%@include file="header.jsp"%>
</c:when>
<c:otherwise>
</c:otherwise>
</c:choose>

但是有一种更好更清洁的方法。使用像 SiteMesh 这样的装饰器,然后您可以将不同的装饰器应用于您的视图。试试Sitemesh

于 2013-10-13T16:39:55.420 回答