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

依然范特西╮ 提交于 2021-01-27 13:40:23

问题


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?


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




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


来源:https://stackoverflow.com/questions/20030773/how-to-include-an-html-fragment-in-a-jsp-that-loads-at-run-time

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