Including JSP page into another JSP page, how to avoid multiple HEAD / BODY sections?

谁说胖子不能爱 提交于 2019-12-01 05:38:35

问题


I would like to include a JSP page into another JSP page. Let's say that I have master.jsp that is including slave.jsp.

As slave.jsp has its own <head> section for dealing with JavaScript and CSS, is there a way or maybe another method to merge the masterand slave HEADs section into a single one? Also the same should done for the BODYs section.

I have been using sitemesh recently but I think is quite impractical to setup a template for each page.


回答1:


I went for this solution by passing a parameter when including the page.

in master.jsp

<head>
  blablabla
  <c:import url="slave.jsp">
    <c:param name="sectionName" value="HEAD" />
  </c:import>
</head>
<body>
  blablabla
  <c:import url="slave.jsp">
  </c:import>
</body>

and then in slave.jsp the parameter is read and the custom part of the page is rendered.

<c:choose>
  <c:when test="${param.sectionName == 'HEAD'}">
     head section here [without the <HEAD> tags !]
  </c:when>
  <c:otherwise>
     body section here [without the <BODY> tags !]
  </c:otherwise>
</c:choose>

not too nice to see but working. In this way I am able to remove the duplication of HEAD and BODY parts.




回答2:


You cannot and should not merge two <html> documents in each other. This would produce invalid output. Better include CSS/JS conditionally with help of JSTL c:if or c:choose tags.

Basic example:

<head>
    <script type="text/javascript" src="global.js"></script>
    <c:if test="${isAdminPage}">
        <script type="text/javascript" src="admin.js"></script>
    </c:if>
</head>



回答3:


Outside of sitemesh, you're pretty much out of luck. However I would reconsider your design if you think that the setup per page is impractical. How many pages will your app have?




回答4:


You could also extend the conditional option, and make a meta.jsp (for example), which contains a Map for each of the head elements - meta tags, css hrefs, script hrefs, and use the name of the jsp as a key in that Map. Then you call request.getRequestURI(), and show whatever you have put in the map under that key. Not a very beautiful solution, but working.



来源:https://stackoverflow.com/questions/1841274/including-jsp-page-into-another-jsp-page-how-to-avoid-multiple-head-body-sect

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!