随机包含JSP

时间:2012-10-13 08:51:27

标签: java jsp

我有很多jsp文件row1.jsp, row2.jsp, row3.jsp, ..., row10.jsp,我希望将其包含在主jsp页面中。

这里的诀窍是我想随机化它们的呈现方式,所以有时它们会被包括在内:

<%@include file="/index-rows/row1.jspf"%>
<%@include file="/index-rows/row2.jspf"%>
<%@include file="/index-rows/row3.jspf"%>

其他时间:

<%@include file="/index-rows/row2.jspf"%>
<%@include file="/index-rows/row1.jspf"%>
<%@include file="/index-rows/row3.jspf"%>

我尝试了以下操作但我意识到我无法在<%= %>代码中添加<%@include>

<%
HashMap<String, String> foo = ...some code...
String[] pages = { "row1.jspf", "row2.jspf", "row3.jspf" };
for (String p : pages) {
     %><%@include file="/index-rows/<%= p %>"%><%
}
%>

条件:包含的文件使用变量foo

1 个答案:

答案 0 :(得分:4)

<%@ include %>是一个静态include指令。这意味着它在编译时进行了评估,因此无法使用动态文件名。

使用dynamic include执行您想要的操作:<jsp:include page="..."/>。但是,您需要将foo存储在所包含页面的请求属性中才能使用它。

请了解如何使用JSP EL。不应再使用Scriptlet了。