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

filejavajspservlets

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?

Best Answer

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();