8

How should I include an HTML file into another HTML file, using JSP?

<jsp:include page="/include.html"></jsp:include>
Dirk Diggler
  • 863
  • 1
  • 10
  • 22

2 Answers2

9

You have a couple of options. The first is <jsp:include>. The second is <c:import>. The c: tags are JSTL, the JavaServer Pages Standard Tag Library.

What's the difference? Primarily <jsp:include> inserts the contents of another JSP page within the same JAR relative to the current page whereas <c:import> can read in an absolute or relative URL and display those contents on the page, retrieve a Reader or store the contents in a variable.

The syntax for both is XML-like so:

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

or

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

Note: both can take parameters.

cletus
  • 616,129
  • 168
  • 910
  • 942
  • 1
    +1. Looking at the docs, it does appear that will do what the OP is asking for; however, it does not appear to be completely analogous to PHP's include(). Notably, the included file does not share the same global scope; functions/classes created by the included file won't become available in the including script, etc. Instead, it executes the included script, and returns the output. – Frank Farmer Jan 13 '10 at 04:23
  • Where's your vote, Frank? I did the first upvote, but I don't see a second one :) – BalusC Jan 13 '10 at 11:15
  • Thanks, so the example I have above is the proper syntax? – Dirk Diggler Jan 13 '10 at 23:56
  • @devils-avacado: yes. @cletus' edit: the actual difference between `jsp:include` and `c:import` is that the first includes the *source* and that the second includes the *output* (apart from having the possiblity to get it from an external URL). – BalusC Jan 14 '10 at 02:03
  • @cletus or @BalucC, can I include .html, .shtml, .js, or .css using either method? Excuse my ignorance, I'm completely new to JSP. – Dirk Diggler Jan 14 '10 at 15:59
  • 1
    The included document is arbitrary so it could be CSS, Javascript or HTML ie what you could normally have in an HTML document. – cletus Jan 14 '10 at 16:18
1

For those who want the same behavior as PHP include() or <!--#include file="header.jsp"-->, with shared the global scope in JSP, use the following command:

<%@include file="header.jsp"%>

Reference: Here

Community
  • 1
  • 1
Roger Barreto
  • 2,004
  • 1
  • 17
  • 21