2016-07-05 95 views
0

保持干燥,我有一个简单包头段,看起来像:如何使用include标签将变量传递给JSP片段?

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" 
    pageEncoding="ISO-8859-1"%> 
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
    <head> 

    <meta charset="utf-8"> 
    <meta http-equiv="X-UA-Compatible" content="IE=edge"> 
    <meta name="viewport" content="width=device-width, initial-scale=1"> 

    <script src="${pageContext.request.contextPath}/assets/js/jquery.js"></script> 
    <title>Insert title here</title> 
</head> 
<body> 

它包含在每个页面的顶部基本HTML头我想要的。然后,对于我创建的每个JSP页面,我只需将其包含在<%@ include file="_header.jsp" %>中,并且它使我的代码更加干净整洁。

但是,这意味着我的每个页面都将具有相同的<title>属性。有没有办法将一个变量传递给_header.jsp文件并以这种方式更新标题?我知道您可以在使用<jsp:forward>操作时传递变量,但我需要使用<%@ include %>,这样它才会显示我的页面的其余部分。

我还可以在每个自定义页面的底部更新以下JavaScript标题:

<script> 
    document.title = "This is the new page title."; 
</script> 

但我想有一个更好的办法。

回答

1

尝试使用支持参数传递的jsp:include指令。

<jsp:include page="_header.jsp" > 
    <jsp:param name="title" value="This is the page title"/> 
</jsp:include> 

然后在你的标题JSP,读取参数如下:

<title>${param.title}</title> 
+0

这是否工作链接到文件一级目录呢?我尝试了'/../_ header.jsp',但是得到了'NullPointerException'。我也尝试过'$ {pageContext.request.contextPath}/_ header.jsp',但也导致了一个错误。 – nicholas79171

+0

相对路径应该工作证明这篇文章:http://stackoverflow.com/questions/18846556/how-to-include-jsps-file-from-another-folder – EJK

+0

谢谢,这工作。当它应该是'../_ header.jsp'时,我在相对文件路径上放置了一个前导'/'。 – nicholas79171