JSP Page Directive – JSP Directives Type

FREE Online Courses: Elevate Skills, Zero Cost. Enroll Now!

Welcome to DataFlair JSP Tutorial series. This article deals with the most important directive that is JSP page directive and its attributes in detail. It discusses include and taglib directive too. So let’s start!!!

JSP Page Directive

JSP Page Directive

The page directive is an important part of directives. Page directive has instructions that set the attributes of that JSP page. They determine the interpretation and execution of that JSP page.
Syntax:

<%@ page attribute=”value” attribute=”value”…%>

It gives instructions for that JSP page in which it is physically present to the JSP web container.

Page directive has following attributes:

  • language=”scripting language”
  • extends=”className”
  • import=”importList”
  • session=”true|false”
  • buffer=”none|sizekb”
  • autoFlush=”true|false”
  • isThreadSafe=”true|false”
  • info=”info_text”
  • contentType=”ctinfo”
  • errorPage=”error_url”
  • isErrorPage=”true|false”
  • pageEncoding= “value”
  • isELignored= “true|false”

More than one page directive tag can be in a program as well as the order of the attributes is not important. However, one attribute can only be defined once except the import attribute.

**The page directive attributes won’t show any output as they just set off the start for our JSP code. Thus there won’t be any outputs for page directive.

1. JSP language

JSP architecture allows it to be extended as a framework for server-side scripting only. For this reason, page directive supports language attribute.

By default, the value for this attribute is Java. It applies to all declarations, expressions, and scriptlets present under the files mentioned in an include directive.

Newer versions allow the other languages only with some restrictions. The language used as the value for language attribute must support the JRE so that it allows access to the implicit objects, to access get and set methods of JavaBeans, and to use public methods of Java classes.
Syntax: 

<%@ page language=“value” %> 

When Java is the value of language attribute—the code gets copied to the auto generated servlet the way it is.

<% int k = 10; %>
k =
<%= k %>

then the generated servlet includes the statements,

out.print("\r\n");
int k = 10;
out.print("\r\nk = ");
out.print(k);
out.print("\r\n\r\n");

which treats k as a Java variable,

When the language is javascript—the code is not as it is. Instead, a servlet engine gets initialized that reads and interprets

<%@ page language="javascript" %>
 <% var k = 10; %>
 k = <%= k %>

A scripting engine specific to JRE will generate following code:

if (scriptEngine == null)
{
try { scriptEngine = ScriptEngineFactory.getScriptEngine("javascript"); scriptEngine.init(pageContext);
}
 catch (Exception e)
{
      throw new ServletException ("Error initializing scripting engine.", e);
 }
      if (request.getAttribute(SCRIPT_KEY) != null)
 {
scriptEngine.init( pageContext, (String) request.getAttribute(SCRIPT_KEY), (String) request.getAttribute(DECLARATION_KEY));
}
scriptEngine.evaluate(pageContext);

For Example:

<%@ page language = “java” contentType = “text/html” pageEncoding = “ISO-8859-1” isErrorPage = “false”%>

Explanation:

The language here is Java. Java Compiler will compile all the code under expression tags.

2. JSP extends

The page directive allows extending the functionalities of a class (parent) to subclass. Specify the full name of the class under the extends attribute that you want to extend. Without explicitly coding one can add an additional behavior of another class in a JSP page.

However, take some cautions while extending a class because it may affect factors like vendor-specific performance and reliability of a JSP page.

Syntax:

<%@ page extends="value" %>

For Example:

<%@ page language = “java” contentType = “text/html” pageEncoding = “ISO-8859-1” %>
<%@ extends = “pack.firstclass”%>

Explanation:

The extend tag in this example extends the first class of pack package that makes the first class available to this JSP page.

3. JSP import

The import describes the qualified names of classes, the JSP page will use. You can also import a package, but import makes that class. Import the classes by their names rather than package names. Imports can be done for interfaces, enumerations, etc. It is one of the frequently used attributes under the page directive.

Import statements will convert to import statements of Java.

The syntax is as follows:

<%@ page import=“value” %>
<%@ page import="java.io.*,java.sql.*,java.util.*" %>

or

<%@ page import="java.io.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>

In the auto generated servlet it converts to following –

import java.io.*;
import java.sql.*;
import java.util.*;

Apart from the import statement, four packages get directly imported. We don’t need to mention them. The list of default import is:

a. java.lang
b. javax.servlet
c. javax.servlet.http
d. javax.servlet.jsp

For Example:

<%@ page language=“java” contentType=“text/html” pageEncoding= “ISO-8859-1” isErrorPage = “false” import=“java.util.Calender.Date” %>

Explanation:
The code in the above example imports the instance of Date from the util package.

4. JSP session

The work of session directive is to see if the HTTP sessions are the requirement of your page or not. It can have two values:

a. If the value of session=”true”
This value specifies that the page needs an HTTP session. The default value of this attribute is true.

b. If the value of session=”false”
This value shows that the page doesn’t require an HTTP session. The implicit variable of the session generation can’t be used if the value of the session is false. It causes errors at the time of translation.
If the page doesn’t need a http session then Specify it to save the memory and CPU cycles.

Syntax:

<%@ page session= “true/false” %>

For Example:

<%@ page language=“java” contentType = “text/html; charset=ISO-8859-1” pageEncoding = “ISO-8859-1” session= “false”%>
 

Explanation:
The above code suggests that we don’t want to create a session for the particular JSP page.

5. JSP buffer and autoFlush

These attributes describe the way the output will be processed. If buffer is set as none, the output gets written to the response directly, whereas the output is written to buffer of the specified size. 8kb is the default size of the buffer.
On the other hand, autoFlush can have two values. If it is “true” it flushes the output in the buffer if it is full, whereas if the value of autoflush is “false” that means it will not work and as soon as the buffer will be filled an exception of buffer overflow occurs.

Syntax:

<%@ page buffer=“value” %>
<%@ autoFlush=“true/false” %>

The following are the possible combinations:

BufferautoFlushEffect
NoneTrueThe result is directly written to the output stream of the auto generated servlet.
NoneFalseThis operation is illegal as, if there is no buffer. Nothing will be stored and hence autoflush is of no use.
8kbTrueAn 8kb of default buffer is initialized. It is flushed automatically once it fills.
8kbFalseAgain an 8kb size of default buffer is used. As the autoFlush is false, if the buffer fills an exception occurs.
size kbTrueOnly the buffer size changes in this. Users can choose any integer. A size times 1,024-byte buffer is used. As autoflush is true, when this buffer fills, it gets flushed automatically.
size kbFalseIt is similar to the 4th combination. The only difference is this the size of buffer varies according to the user i.e. A size times 1,024-byte buffer is used. When the buffer fills, an exception occurs.

 

For Example:

<%@ page language=“java” contentType = “text/html; charset=ISO-8859-1” pageEncoding = “ISO-8859-1” buffer=“8kb” autoFlush=“true”%>

Explanation:
For the above example, an 8kb buffer will be generated to map the output and it will automatically get flushed once it fills.

6. JSP isThreadSafe

A servlet engine, by default, uses a lot of threads and loads a solo instance of generated servlet to service one request. This implies that two or even more threads might be executing the same method of servlet simultaneously. The threads thus can collide. This can lead to interference of threads with each other towards the access of the variable.

Thus, to go a way around with this SingleThreadModel, the isThreadSafe attribute of the page directive helps.
If you specify isThreadSafe=”true”, it implies that you take care of any possible thread conflicts. A defined JSP container safely dispatches multiple requests.

If the value is “false”, the JSP container implements SingleThreadModel. By default value is taken as “true”. The Syntax for isThreadSafe is as follows:

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

Class signature is generated as follows :

public class jrun__Chap10__examples__isThreadSafe__ex12ejsp25
extends allaire.jrun.jsp.HttpJSPServlet
implements allaire.jrun.jsp.JRunJspPage
 
<%@ page isThreadSafe="false" %>

Class signature is:

public class jrun__Chap10__examples__isThreadSafe__ex22ejsp25
extends allaire.jrun.jsp.HttpJSPServlet
implements allaire.jrun.jsp.JRunJspPage, SingleThreadModel 

For Example:

<%@ page language=“java” contentType = “text/html; charset=ISO-8859-1” pageEncoding = “ISO-8859-1” isThreadsafe= “true”%>
 

Explanation:
This code suggests that multiple threads will be used and they will be synchronized avoiding any thread conflict.

7. JSP info

The info attribute provides the functionality to provide the descriptive info of the JSP page/servlet. A description is useful for an interactive page.The Syntax for info is as follows:

<%@ page info=“value” %>
<%@ page info="Shopping Cart Checkout Page" %>

This value gets compiled to a class. This is made available using the getServletInfo() method.

For Example:

<%@ page language=“java” contentType = “text/html; charset=ISO-8859-1” pageEncoding = “ISO-8859-1” info= “JSPDirectives_Kajal”%>

Explanation:
The value in the info attribute describes that this page is about Directives and thus using getServletInfo() method, servlet retrieves this value.

8. contentType

A JSP page normally generates output in HTML output. But this is not always the case. Using contentType, you can specify the type of content according to you. It can be a jpg image or a pdf. The Syntax for contentType can be:

<%@ page contentType=“value” %>

The character set can be specified in addition to the content type. The default value for contentType is “text/html; charset=ISO-8859-1” until and unless the user defines it. For example:

<%@ page contentType="type/subtype; charset=charset" %>

For Example:

<%@ page language=“java” contentType = “text/html; charset=ISO-8859-1” pageEncoding = “ISO-8859-1” session= “false”%>

Explanation:
contentType sets the type of response as text or html. The character set is specified too for the JSP and response page.

9. JSP errorPage and isErrorPage

While a JSP page is being evaluated and an exception occurs, the servlet engine dumps a stack track. This is not desirable for commercial Web applications. JSP offers a simple and convenient solution. We need two attributes: errorPage and isErrorPage and their synchronization.
What a JSP can do is to indicate that whenever a page throws an exception, then an error page can be displayed. The Syntax can be:

<%@ page errorPage="value" %>

Where error_url is the url of the error page of that JSP page in the same servlet context.
Now, if the JSP page contains the attribute isErrorPage then it becomes capable of receiving exceptions of the JSP pages that have error pages. That JSP page generated after error needs to have following described in its page directive:

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

Then It may simply report the exception:

<%@ page isErrorPage="true" session="false"%>
<H3>Application Error</H3>
The error message is:
<B><%= exception.getMessage() %></B>

For Example:

<%@ page language=“java” contentType = “text/html; charset=ISO-8859-1” pageEncoding = “ISO-8859-1” isErrorPage=“true” errorPage= “Handleexception.jsp”%>

Explanation:
In this code, if the page contains error, then it should be referred to the Handle Exception page.

10. JSP pageEncoding

It is a character encoding in which JSP files are encoded. The default value for page encoding is ISO-8859-1. It is a character 8-bit (single-byte) coded graphic character set. Page encoding

1. Through the value of page encoding in JSP Property group.
2. Through the value present in page encoding attribute. A translation error is generated if the page encoding of a JSP page is different from its property groups.
3. Through the contentType attribute that has charset value.

The pageEncoding and contentType attribute tells about page encoding of the That JSP file in which page directive is physically present.
Syntax:

<%@ pageEncoding= “value” %>

For Example:

<%@ page language=“java” contentType = “text/html; charset=ISO-8859-1” pageEncoding = “ISO-8859-1” session= “false”%>

Explanation: The pageEncoding has been shown in the above example using the default value i.e. ISO-8859-1.

11. JSP isELignored

The attribute stands for Expression Language ignored. This attribute specifies the inability of an expression to be evaluated saying that expression is static and will not be evaluated. However, the default value of the attribute is false and expressions are evaluated as specified.
Syntax:

<%@ isELignored = “true/false”%>

For Example:

<%@ page language=“java” contentType = “text/html; charset=ISO-8859-1” pageEncoding = “ISO-8859-1” isELignored= “false”%>

Explanation:
For the above example, all the expression language statements will be calculated as they were specified. They will not be ignored.

JSP Include Directive

It works similarly to the #include of the C preprocessor directory. Its work is to merge the contents of another file into .jsp source input stream at the translation phase.

Syntax:

<%@ include…….%>
<%@ include file=”filename”%>
The “filename” can be the absolute name or the relative path name as following:
            <%@ include file=”header.html”>
            <%@ include file=”sortmethod”>

The include directive however contrasts with the <jsp:include> action. <jsp:include> merges the output of another file at request time into the response output stream unlike include directive. Either of them can be used to include texts, headers, footers, etc.

For Example:

include1.jsp
<%@ page language="java" contentType = "text/html; charset=ISO-8859-1" %>
<%@ include file="include2.jsp" %>
<html>
<head><title>Include Application </title></head>
<body>
<a>I am the main, including second.</a>
</body>
</html>

include2.jsp
<%@ page language="java" contentType = "text/html; charset=ISO-8859-1" %>
<html>
<head></head>
<body>
<a>Second file will be executed first </a>
<% int num=1; num++; %>
<br/>
<% out.println("The result is:" + num);%>
<br/>
</body>
</html>

Explanation:
In the above example, there are two jsp files include1 and include2. First file is the main file that includes the second file. As the second file is first, it compiles and executes first and then the main file is compiled.

jsp page directive

JSP Taglib Directive

With the use of tag library this directive makes the custom tags available in the current page. The JSP page uses them through the standard tag libraries of JSP.

It takes custom tags and finds their location in the library. Once it gets the location it searches for that tag in the JSP page. Thus the tag is available for that page.

Syntax can be shown as:

<%@ taglib uri=“taglib URI” prefix=“value”%>

The attributes of this directive are:

  • tagLibrary URI
  • tagPrefix

a. tagLibraryURI
This attribute contains the URL of a Tag Library Descriptor as a value.

b. tagPrefix
It contains unique prefixes for the identification of custom tags.

For Example

<%@ page language=“java”contentType = “text/html; charset=ISO-8859-1” %>
<%@ taglib prefix=“mytag” uri=“http://www.getsuccess.com/jsp_core”%>
<html>
<head><title>taglib</title>
<mytag: Hi I am a custom tag. />
</head>
<body>
You are seeing an example of custom tags.
</body>
</html>

Explanation: This is an example of custom tags where mytag is the custom tag prefix and it identifies the concerned tag in the head of the code.

Conclusion

In this article, we discussed JSP page directive in detail with syntax and examples. Page directive is an important part of a JSP page as they determine the interpretation of a JSP code. They act like an index to the book. Further, we discussed all the attributes of page directive such as language, is thread safe, isErrorPage, etc. that form a crucial part of JSP coding. In addition to it, we also glanced at include and taglib directives that are equally important as page directive.

You give me 15 seconds I promise you best tutorials
Please share your happy experience on Google

follow dataflair on YouTube

1 Response

  1. sumanth says:

    By default Expression Language (EL) is disabled in JSP. so that default attribute value is “true”. to enable the EL in a JSP file we use page directive element as

Leave a Reply

Your email address will not be published. Required fields are marked *