In this tutorial you will learn about the JSP Include Directive and its application with practical example.
JSP Include Directive
The include directive is used to include external files during the translation phase. Translation phase is the phase when JSP page get converted into the equivalent servlet. We can directly add in jsp but we have to write code each JSP page, let’s get understand it by simple example: suppose we have 50 JSP file and we want to add header in each file so write code to each JSP page will be bad idea, we can simply create a header file and then we can include it in each jsp. If we don’t like header color so we will go to header file and simply change the color, it will change in each JSP page. The main purpose of include directive is code re-usability.
Syntax:
1 |
<%@ include file="path or Url of file" %> |
Example: Let’s get understand it by an simple example. Here I have created two files,
1.header.html
2.index.jsp
1.header.html: We will include this file in our index.jsp page. I have created some menus in header file, check below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style> #navigation ul li{ display: inline-block; padding: 0px 5px; } #navigation ul li a{ color:#fff; text-decoration: none; } #navigation { background: #4062b7; padding: 3px } </style> </head> <body> <div id="header"> <div class="shell"> <div id="navigation"> <ul> <li><a href="#" class="active">HOME</a></li> <li><a href="#">ABOUT</a></li> <li><a href="#">GALLERY</a></li> <li><a href="#">RESERVATION</a></li> <li><a href="#">LOCATION</a></li> <li><a href="#">CONTACT</a></li> </ul> </div> </div> </div> </body> </html> |
2.index.jsp: It will be our launching page for our Java Web Application and also we will include our header.html file in this jsp page. Check below code.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
<%@page contentType="text/html" pageEncoding="UTF-8"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>W3Adda Page</title> </head> <body> <%@ include file="header.html" %> <br> Today is: <%= java.util.Calendar.getInstance().getTime()%> </form> </body> </html> |
Output: So we are done with our Include directive coding, run this code you will find output like below image.