JSP includes import code after and before

I have the following structure in many pages of my web application. I would like to create a template page with a fixed code before and after the page code and then put my code for every other page. The problem is I have to cut div

in different files.

<!-- fixed jsp code 
  <header>
  <imports> ...
  <div id="some-fixes-divs-inside">
-->

   page code

<!-- fixed jsp code
  </div>
  <other>
  <footer>
 -->

      

The only way I know would be something like this, but I think it's not a good practice to shorten div

s:

<jsp:include page="fixed-jsp-code-head.jsp" />
    my page code
<jsp:include page="fixed-jsp-code-footer.jsp" />

      

Q1: Is there any directive or something in jsp or some other framework to do this?

Q2: If the first Q is not, is my decision a bad practice?

Edit: I would like to know if there is any type directive <import>mycode</import>

to have all the footers and code header in the template and not open the same one div

in the header and close it in the footer and put my code inside the template.

+3


source to share


2 answers


You can also use Apache Tiles. This is a boilerplate structure. Like this .

First of all, define a template:

<definition name="myapp.homepage" template="/layouts/classic.jsp">
  <put-attribute name="header" value="/tiles/banner.jsp" />
  <put-attribute name="menu" value="/tiles/common_menu.jsp" />
  <put-attribute name="body" value="/tiles/home_body.jsp" />
  <put-attribute name="footer" value="/tiles/credits.jsp" />
</definition>

      



And after that use it in your code:

<%@ taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<table>
  <tr>
    <td colspan="2">
      <tiles:insertAttribute name="header" />
    </td>
  </tr>
  <tr>
    <td>
      <tiles:insertAttribute name="menu" />
    </td>
    <td>
      <tiles:insertAttribute name="body" />
    </td>
  </tr>
  <tr>
    <td colspan="2">
      <tiles:insertAttribute name="footer" />
    </td>
  </tr>
</table>

      

+2


source


If the first Q is no, is my solution bad practice?

In my opinion, splitting jsps according to appropriate functionality is good practice. This makes your code loosely coupled. In the future, if you need to change your header / footer code, you will only need to change it in one place, reducing a ton of rework.

Q1: Is there any directive or something in jsp or some other framework to do this?

The standard way to include jsp in another jsp is using

<%@include file="your jsp"/>

(static include) or



<jsp:include page="fixed-jsp-code-footer.jsp" />

(dynamic inclusion)

You can also use JSTL tag

`<c:import url="http://www.example.com/foo/bar.html" />` (dynamic include)

      

It is very similar, but more powerful and flexible: unlike the other two, the URL can be from outside the web container!

+1


source







All Articles