jsp

JSP Directives Example

JSP directives are messages to the JSP container. Directives play role when a JSP page is re-compiled after you modify it, they have no specific effect on the current out stream.

They provide global information about an entire JSP page. In this post, we will look into the details of the JSP directives and examine them on some code snippets.

1. What are JSP Directives?

JSP directives give some special commands to the Container while the JSP pages are translated to the Servlet code. Directives have this syntax:

   <%@ directive { attr="value" }* %>

You usually see this syntax at the top of the JSP pages. There are three directives: the page, the taglib and include directives. Each of these directives has some special attributes that affect the JSP page differently. For example, page directive attribute list contains the language, extends, import, session, buffer, autoFlush, isThreadSafe, info, errorPage, isErrorPage, contentType, pageEncoding, isELIgnored, deferredSyntaxAllowedAsLiteral, trimDirectiveWhitespaces attributes. The taglib directive has three attributes: uri, tagdir, prefix. The include directive has only one attribute: file.

2. Example Overview

In our previous JSP example ( JSP Scriptlet Example ), we created a ‘Pizza Order’ form in a JSP page with the help of scriptlets. We have already used some of the JSP directives in this example. In this post, we extend this example adding extra directives that we have not used before. Also, you can find the reference how to setup our environment in this example. Our preferred IDE is Eclipse. We use ‘Maven’ for the dependency management. We create a dynamic web application and deploy it into the Tomcat server.

3. Directives in the Code

3.1 Page Directive

The page directive defines a number of page dependent properties and communicates these to the JSP container.

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="com.javacodegeeks.examples.jspdirectivesexample.Pizza" %>
<%@ page import="java.util.*"%>
...

In the first line above, we see the language, contentType and pageEncoding page directive attributes in the same directive statement. The language attribute tells the server what language will be used to compile the JSP file. Currently, “java” is the only available language. Future versions of the JSP specification may define additional values for the language attribute.

The contentType attribute defines the MIME type and the character encoding for the response of the JSP page. The default value of the MIME type is “text/html” for JSP pages in a standard syntax. This affects the output of the JSP response. For example, If we change it as “text/plain” ( plain text document ), some browsers are supposed to display the raw HTML content in such a case. Then we see only the content of the HTML codes, not rendered HTML output.

The pageEncoding attribute describes the character encoding for the JSP page if it is present, otherwise the “charset” given by the contentType attribute if it is present, otherwise “ISO-8859-1” as default.

The following page directives above have import attribute. It is clear that this attribute defines the list of Java packages that will be available to this JSP. The value is as in an import declaration in the Java programming language. Also, you can give comma separated list like below:

<%@ page import="com.javacodegeeks.examples.jspdirectivesexample.Pizza, java.util.*" %>
...

Any JSP will automatically extend to HttpServlet class. The extends page directive attribute is very rarely used if we have extended HttpServlet and overridden some of it’s implementations. For example:

<%@ page extends="org.apache.jasper.runtime.HttpJspBase" %>
...

The session page directive attribute indicates that the page requires participation in an (HTTP) session. If true then the implicit script language variable named session of type “javax.servlet.http.HttpSession” references the current/new session for the page. If false then the page does not participate in a session; the session implicit variable is unavailable. Default is true.

<%@ page session="false" %>
...
<%=session.getAttribute( "pizzaTypeList" ) %>

In the Eclipse, if we put the code like above and try to use the session implicit object, you will take “session cannot be resolved” compilation error.

we can define an arbitrary string about the JSP page in the info page directive attribute. Then we can retrieve it using Servlet interface getServletInfo() method:

<%@ page info="Pizza Order Form JSP" %>
...

In the JSP page, if any Java programming language Throwable object(s) is thrown but not caught by the page implementation, it can be forwarded for error processing to another error handler with the errorPage page directive attribute. To declare a JSP page as an error page, we have to set isErrorPage attribute as “true”. In this way, JSP implicit attribute exception is available in this page.

In the code below, we define the errorPage attribute and redirect the uncaught errors to the “error.jsp” error handler page:

<%@ page errorPage="error.jsp" %>
...
<%
   // Create an error.
   int i = 45 / 0;
%>

In the “error.jsp” page, please notice that we set the “isErrorPage” page directive attribute as true and use the exception implicit object to access the error details.

error.jsp

<%@ page import="java.io.PrintWriter"%>
<%@ page isErrorPage="true"%>

An error is reported:<br/>
<i><%= exception %></i><br/>
This problem occurred in the following place:<br/>
<pre>
<% exception.printStackTrace( new PrintWriter( out ) ); %>
</pre>

After execution, you see the error.jsp in the browser:

error.jsp in the browser
error.jsp in the browser

the JspWriter has buffering capabilities. It means that the document content should be buffered and not sent to the client until at least certain amount of kilobytes have been accumulated or the page is completed. This buffer size can be specified with the buffer page directive attribute like shown below. The default value is “8kb”. If we ignore the buffering ability, we can set as “none”. If there is no buffering and all output is written directly through to the ServletResponse PrintWriter.

<%@ page buffer="16kb" %>
...
<!-- If you don't want buffering:-->
<%@ page buffer="none" %>
...

The autoFlush page directive attribute specifies whether the buffered output should be flushed automatically (true value) when the buffer is filled. Its default value is true. If we set it to false, the buffer will not be flushed automatically and if it’s full, we will get an exception. Please note that a value of “false” is illegal when also using buffer=”none”. Because there is no buffering, so we have to flush automatically.

<%@ page autoFlush="false" %>
...

The isThreadSafe page directive attribute Indicates the level of thread safety implemented in the page. Its default value is “true”. So simultaneous user requests result in multiple threads concurrently accessing the service method of the same servlet instance. The servlet synchronizes access to data in its fields so that inconsistent values will not result from an unexpected ordering of thread execution.

If we set it as false like below, the generated servlet will implement SingleThreadModel and accesses to any shared objects can yield inconsistency. So such codes should be properly synchronized. The Servlet 2.4 specification deprecates SingleThreadModel, so the page authors are advised against using isThreadSafe.

<%@ page isThreadSafe="false" %>
...

We can ignore the Expression Language (EL) (of the form ${…} and #{…} ) in JSP using isELIgnored page directive attribute. Its default value is false, so EL is enabled by default. We can tell the container to ignore EL using the directive like below:

<%@ page isELIgnored="true" %>
...

The trimDirectiveWhitespaces page directive attribute was introduced in JSP 2.1. This new feature enables to remove the blank lines or white spaces from the response output and it helps in reducing the generated code size. For example, in the code below, we use JSP Standard Tag Library (JSTL) for defining and displaying the value of a variable:

<%@ page trimDirectiveWhitespaces="false"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<h3>Order Details</h3>
<c:set var="str1" value="See the details:"/>
<c:out value="${str1}" />
...

JSTL statements produce blank lines in the output of the JSP. View the generated source:

Jsp response
Jsp response

But after setting the “trimDirectiveWhitespaces” as true, we see the blank lines removed:

ff
Jsp response

Deferred evaluation expressions take the form #{expr} in the JSP pages. This syntax is usually used by the JSF technology. If we want to use these character sequence ( #{ ) as a String literal, we can set deferredSyntaxAllowedAsLiteral page directive attribute as true. If false (the default value), a translation error occurs when the character sequence is used as a String literal:

<%@ page deferredSyntaxAllowedAsLiteral="true" %>
...

3.2 Taglib Directive

JSP is extendable and we can create our own custom tags to perform certain operations or use other tag libraries. We need taglib directive to define the tag library, it uniquely identifies the tag library using a uri and associates a tag prefix that will distinguish usage of the actions in the library. The code below shows a declaration sample in a JSP page:

<%@ taglib prefix="jgc" uri="WEB-INF/custom.tld"%>
...
<jgc:HelloWorld/>
...

The tagdir taglib directive attribute indicates this prefix is to be used to identify tag extensions installed in the /WEB-INF/tags/ directory or a subdirectory. In other saying, you can define the prefix for all of the tag libraries in a directory rather than certain one tag library setting with uri attribute.

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

3.3 Include Directive

The include directive is used to substitute text and/or code at JSP page translation-time. The <%@ include file=”relativeURLspec” %> directive inserts the text of the specified resource into the page or tag file. You can insert any other JSP or HTML files into your JSP page during the translation phase.

You can describe the same information with the following XML syntax:

<jsp:directive.include file="relative url" />

We insert a “header.html” page into the Pizza form in the example:

...
<head>
	<meta charset="UTF-8">
	<title>Jsp Directives Example</title>
	<link rel="stylesheet" href="./static/css/pizzaorder.css">
</head>
<body>
	<%@ include file="header.html" %>
	<form action="orderResult.jsp" method="POST">
		<h3>Pizza Types</h3>
		<div>
		...	

header.html:

<h4>Java Code Geeks Examples<h4>

After execution, you see the inserted HTML file in the form:

Include Directive
Include Directive

4. Download the Eclipse Project

This code demonstrates JSP directives in a simple example. Download link is below.

Download
You can download the full source code of this example here : jspDirectivesExample

Ilker Konar

I am a senior software developer with experience mostly in java-related technologies with appliance in the telecommunication industry. I have been programming for more than fifteen years. I am passionate about programming. I like learning new frameworks, languages and design patterns.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Inline Feedbacks
View all comments
Back to top button