Open In App

Directives in JSP

JSP directives are the elements of a JSP source code that guide the web container on how to translate the JSP page into its respective servlet. 

Syntax :



<%@ directive attribute = "value"%>

Directives can have a number of attributes that you can list down as key-value pairs and separate by commas. The blanks between the @ symbol and the directive name, and between the last attribute and the closing %>, are optional. 

Different types of JSP directives : 



There are three different JSP directives available. They are as follows: 

<%@page attribute = "value"%>
<%@page import = "value"%>

Example : 




<%-- JSP code to demonstrate how to use page
 directive to import a package --%>
 
<%@page import = "java.util.Date"%>
<%Date d = new Date();%>
<%=d%>

Output

<%@page contentType="value"%>

Usage Example: 




<%-- JSP code to demonstrate how to use
page directive to set the type of content --%>
 
<%@page contentType = "text/html" %>
<% = "This is sparta" %>

Output : 

<%@page info="value"%>

Usage Example




<%-- JSP code to demonstrate how to use page
 directive to set the page information --%>
 
<%@page contentType = "text/html" %>
<% = getServletInfo()%>

Output

<%@page buffer = "size in kb"%>
<%@page isElIgnored = "true/false"%>

Usage Example




<%-- JSP code to demonstrate how to use page
directive to ignore expression language --%>
 
<%@page contentType = "text/html" %>
<%@page isELIgnored = "true"%>
<body bgcolor = "blue">
<c:out value = "${'This is sparta}"/>
</body>

Output
(blank page) 

<%@page errorPage = "true/false"%>

Usage Example: 




//JSP code to divide two numbers
<%@ page errorPage = "error.jsp" %> 
 
<%  
// dividing the numbers
int z = 1/0; 
 
 // result
out.print("division of numbers is: " + z);  
%>

<%@page isErrorPage="true/false"%>

Usage example




//JSP code for error page, which displays the exception
<%@ page isErrorPage = "true" %> 
    
<h1>Exception caught</h1
    
The exception is: <% = exception %>
Output:

Output

<%@include file = "file location"%>

Usage example
In the following code, we’re including the contents of an HTML file into a jsp page.
a.html 




<h1>This is the content of a.html</h1>

index.jsp 




<% = Local content%>
<%@include file = "a.html"%>
<% = local content%>

Output : 

<%@taglib uri = "library url" prefix="the prefix to 
identify the tags of this library with"%>

Usage Example




<%-- JSP code to demonstrate
taglib directive--%>
prefix = "c" %> 
   
<c:out value = "${'This is Sparta'}"/>

In the above code, we’ve used to taglib directive to point to the JSTL library which is a set of some custom-defined tags in JSP that can be used in place of the scriptlet tag (<%..%>). The prefix attribute is used to define the prefix that is used to identify the tags of this library. Here, the prefix c is used in the <c:out> tag to tell the container that this tag belongs to the library mentioned above.

Output
 


Article Tags :