FredoAF
FredoAF

Reputation: 504

JSP including: templating with jsp's so repeated code is included on every page

I'm new to jsp's and have therefore started coding my project with static repeated code on every page. For example in my head section of every page I check if there is a current user logged in, if there is then i use their name in the body section, if not i redirect to the login page.

So on my page i want the following:

<%@ page language="java" 
         import="com.ptm.UserBean"
 %> 
<!DOCTYPE html>
<html lang="en">
<head>
<title> this is my title </title>
<jsp:include page="head-section.jsp" >
</head>
<body >
<jsp:include page="header.jsp" >
</body>
</html>

in the head-section.jsp I have some html which imports jquery and my css sheet, then a jsp code block that relys on the UserBean import on the index page above then some javascript

The header.jsp include uses a jsp variable set in the head-section.jsp code block.

So my question is, these seperate jsp's that i'm including don't work on their own, but when included should work with the page, which cuts down on the ammount of repeated code i have. Is this the best way to do this? i heard about tag files, but im not sure how do implement that.

Thanks in advance for your help!

Upvotes: 2

Views: 2541

Answers (2)

fvu
fvu

Reputation: 32953

Tag files are definitely a nice alternative, and they're quite easy to use. What's nice is that you can send them parameters to improve reusability.

Here's the basic steps (from the tutorial): suppose you store your tags in /WEB-INF/tags (as .tag files), you need to include the following line in your jsp

<%@ taglib tagdir="/WEB-INF/tags" prefix="h" %>

the tagfile (let's call it response.tag) could look like

<%@ attribute name="name" required="true" %>
<h2>Hello, ${name}!</h2> 

This means that it requires one parameter called name. After that, you call it as

<h:response name="world"/>

Which will expand to

<h2>Hello, world!</h2>

in the output.

Upvotes: 2

Azodious
Azodious

Reputation: 13872

You can use include directive:

<jsp:include page="..." />

For static resource, you should use:

<%@ include file="filename" %>

Upvotes: 1

Related Questions