How to include an html fragment in a jsp that loads at run-time?

15,373

Solution 1

You can use .tag files for reusable content or do <jsp:include> (INCLUDE dispatch) to another JSP.

However Tomcat is able to re-compile JSPs when any of the included files got changed:

Recompile JSP when included page changes - Jasper 2 can now detect when a page included at compile time from a JSP has changed and then recompile the parent JSP.

Also note, that the common practice is to use .jspf (JSP fragment) extension for files included via <%@include %>.

Solution 2

Take a look at answers here. You can also use <c:import>:

2) The <jsp:include> standard action

<jsp:include page="header.jsp" />

Dynamic: adds the content from the value of the page attribute to the current page at request time. Was intended more for dynamic content coming from JSPs.

3) The <c:import> JSTL tag:

<c:import url=”http://www.example.com/foo/bar.html” />

Dynamic: adds the content from the value of the URL attribute to the current page, at request time. It works a lot like <jsp:include>, but it’s more powerful and flexible: unlike the other two includes, the <c:import> url can be from outside the web Container!

Regarding reading a file into string. If the file is small do it one line:

String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
Share:
15,373
Thorn
Author by

Thorn

Leon LaSpina teaches math and computer science at the high school level. I've been a fan of Java since I was introduced to the language in the late 90s. First as a client-side technology and educational tool, then as a server-side technology (Servlets, JSPs) and now my focus is back to the client side. Not everything needs to run in a browser. In late 2011, I co-founded Smart Software Solutions, a company that builds software for schools. Websites: The Proctinator Web application for math teams Bethpage Schools Teacher Page

Updated on June 04, 2022

Comments

  • Thorn
    Thorn over 1 year

    I need to include content in a JSP without using the include directive.

    It is easy to do a server-side include with with <%@include file="includeMe.htm" %> but the content of includeMe.htm gets added to the JSP before the JSP is converted into a Servlet by the container. This means that if includeMe.htm gets modified, the changes are not reflected in the generated .java Servlet file. I'm tired of going into Tomcats generated files directory to manually delete the generated java and class files or re-deploy my app every time the included file changes.

    Do I need to write a code block to just read in data from the text file line by line and then write it like this?

     <%
        while( not done reading from file ) {
            String line = scanner.nextLine();
            response.getWriter().println(line);
        }  %>
    

    Is there an easier or cleaner way?