包含另一个 JSP 文件 [英] Include another JSP file
问题描述
我目前正在尝试学习 JSP.我的问题是,目前我曾经使用以下方法包含页面的页眉和页脚:
I am currently trying to learn JSP. My question is, at present I used to include the header and footer of the page using:
<%@include file="includes/header.jsp" %>
和
<%@include file="includes/footer.jsp" %>
但是现在,我也分离了页面内容.因此,如果用户点击一个页面,比如产品,它必须加载位于以下位置的 JSP 文件:includes/pages/products.jsp
因此,指向用户的链接类似于:<a href="index.jsp?p=products">Products</a>
.
But now, I have separated the page content also. So, if user clicks on a page, say products, it has to load the JSP file which is situated in: includes/pages/products.jsp
So, the link to the user is like: <a href="index.jsp?p=products">Products</a>
.
因此,我必须获取 p 值并根据它显示页面.
So, I have to get the p value and display the page based on it.
以下是我目前所做的.
<%
if(request.getParameter("p")!=null)
{
String p = request.getParameter("p");
%>
<%@include file="includes/page_name.jsp" %>
<%
}
%>
那么,如何将变量p"的值放在page_name"的位置?
So, how do I place the value of variable "p" in position of "page_name" ?
或者,我可以使用其他任何方法吗?
Or, is there any other method that I could use ?
在 PHP 中,我们可以使用 include()
或 include_once()
.我有点卡在这个 JSP 中.:(
In PHP, we could use the include()
or include_once()
. I am bit stuck in this JSP. :(
推荐答案
您所做的是静态包含.静态包含在编译时解析,因此可能不使用仅在执行时已知的参数值.
What you're doing is a static include. A static include is resolved at compile time, and may thus not use a parameter value, which is only known at execution time.
您需要的是动态包含:
<jsp:include page="..." />
请注意,您应该使用 JSP EL 而不是 scriptlet.您似乎还使用 index.jsp 实现了一个中央控制器.您应该改用 servlet 来执行此操作,并从该 servlet 分派到适当的 JSP.或者更好的是,使用现有的 MVC 框架,如 Stripes 或 Spring MVC.
Note that you should use the JSP EL rather than scriptlets. It also seems that you're implementing a central controller with index.jsp. You should use a servlet to do that instead, and dispatch to the appropriate JSP from this servlet. Or better, use an existing MVC framework like Stripes or Spring MVC.
这篇关于包含另一个 JSP 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!