Reputation: 469
I come from PHP, where declaring and using user defined function is much easier than JSP (I think). In PHP, I separate the HTML template into several parts using PHP function (in a *.php file) and call them when required, as like as follow:
require_once 'resource.php';
load_header($title);
load_navbar($title);
<!--Other content goes here-->
load_footer();
In resource.php all of the above function contains the required code.
Now in JSP, I want to do the same thing. So I write a function in JSP as like as follow:
<%
int login = 0;
if( session.getAttribute("username") != null ) {
login = 1;
} else {
login = 0;
}
%>
<%!
public static void load_navbar(String title) {
%>
<nav class="navbar navbar-inverse navbar-static-top">
<div class="container-fluid">
<!-- Brand and toggle get grouped for better mobile display -->
<div class="navbar-header">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Brand</a>
</div>
<!-- Collect the nav links, forms, and other content for toggling -->
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav navbar-left">
<li class="active left-margin"><a href="#"> <i class='fa fa-fw fa-home'></i> Home</a> </li>
</ul>
<ul class="nav navbar-nav navbar-right">
<%
if( login == 0 ) {
%>
<li><a href="#">Login</a></li>
<%
} else if( login == 1 ) {
%>
<li><a href="#">Logout</a></li>
<%
}
%>
</ul>
</div><!-- /.navbar-collapse -->
</div><!-- /.container-fluid -->
</nav>
<%!
}
%>
To include the the file in my target page, I write the following line of code:
<jsp:include page="include/navbar.jsp"></jsp:include>
But the problem is, All the code inside load_navbar() function is automatically added to my page without calling the function. I want to load the code when the function is called. i.e:
<body>
<%! load_navbar("Title goes here"); %>
</body>
Can anyone help me to fix the issue?
Thanks
Upvotes: 0
Views: 377
Reputation: 76
The jsp:include will make a request to include/navbar.jsp and append the response to the JSP using jsp:include. For your case, you want to use <%@ include file="include/navbar.jsp" %>. In this case, the content of the navbar.jsp will be added, during the translation phase, to the JSP file using the include directive.
Upvotes: 1