简体   繁体   中英

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

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?

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

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 %> .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM