Nearby lessons

24 of 30

JSP Examples - Scripting Elements & Directives

📌 What You Will Learn
  • See every scripting element in action
  • Understand how directives control page behaviour
  • Compare include directive vs include action

Runnable JSP examples covering scriptlets, declarations, expressions, comments, the page directive (import, session, isELIgnored, isThreadSafe) and the include/taglib directives.

Template Text

Q. Template text will become argument to write() method where as expression value will

become argument to print() method. What is the reason?

write() method can take only character data as argument

print() method can take any type of data as argument

Template text is always character data and hence it will become argument to write() method.

But expression value can be any type and hence we should not use write() method, compulsory

we should go for print() method which can take any type of argument.

Directives:

These can provide general information about JSP page to the JSP Engine. i.e Directives are

translation time instructions to the JSP Engine.

Syntax: <%@ directiveName attributeName=attributeValue %>

There are 3 types of directives are possible

  • page directive:

<%@ page attributeName=attributeValue %>

It can be used to define page specific attributes.

  • include directive:

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

To include the content of header.html at translation time

  • taglib directive:

To make custom tags available to our JSP

Actions:

Actions are commands to the JSP Engine to perform certain task at runtime(execution time). There

are 9 standard actions are available.

Example01
Loading editor…

Template Text

Example02
Loading editor…

Scripting Elements

  • Scriptlet:

We can use scriptlet to place java code in the jsp.

Syntax: <%

Any Java Code

%>

Java Code inside scriptlet will be placed directly inside _jspService() method of generated servlet.

Every java statement present inside scriptlet should compulsary ends with ;

Q. Write a JSP Print hit count of the JSP?

test.jsp:test.jsp:
1. <h1>1. <h1>
2. <%2. <%!
3. int count=0;3. int count=0;
4. count++;4. %>
5. out.println(count);5. <%
6. %>6. count++;
7. </h1>7. out.println(count);
Example03
Loading editor…

Scripting Elements

It always prints same value 1. b'z9. </h1>

count is local variable of _jspService()

methodIt prints hit count of the jsp and count

is instance variable.

Q. What is the difference between the following?

<%! <%

int x =10; int x =10;

%> %>

In the first case x is local variable of _jspService() method where as in the second case x is instance

variable of generated servlet.

Note: It is not recommended to use scriptlets in the JSP.

  • Declaration Tag:

We can use Declaration tag to declare instance variables, static variables, instance blocks, static

blocks, methods etc..

Syntax: <%!

Any java declarations

%>

These declarations will be placed directly in the generated servlet but outside of _jspService()

method.

Example04
Loading editor…

Scripting Elements

Every Java statement inside Declaration tag should compulsary ends with semicolon(;)

demo.jsp:

Example05
Loading editor…

Scripting Elements

CE: out cannot be resolved.

*Note:

All JSP Implicit objects are declared as local variables of _jspService() method.But declaration tag

code will be placed outside of _jspService() method. Hence we cannot use JSP implicit objects

inside Declaration tag.

But Scriptlet and expression tags code will be placed inside _jspService() method. Hence inside

scriptlet and expression tags we can use JSP Implicit objects.

Eg:

Example06
Loading editor…

Scripting Elements

  • Comments:

In the JSP, 3 types of comments are allowed.

  • JSP Comments
  • HTML Comments
  • Java Comments
  • JSP Comments:

<%-- This is JSP Comment --%>

These comments are visible only in the JSP and not visible in the remaining phases of JSP

Execution. Hence these comments also known as Hidden Comments.

It is highly recommended to use JSP Comments in the JSP.

  • HTML Comments:

<!-- This is HTML Comment -->

Also known as Template text comments.

These are visible to the end user as the part of generated response source code.

Hence these are not recommended to use in the JSP.

  • Java Comments:

// single line java comment

/*

multiline java comment

*/

/**

Java Doc comment

*/

Also known as scripting comments.

These are also visible in the generated servlet source code but not visible in the remaining phases.

*Note:

Among Expressions, Scriptlets, Declarations and JSP Comments, we cannot use one inside another.

i.e. Nesting of these scripting elements is not possible, otherwise we will get Compile Time Error.

Summery of JSP Comments

Comment TypeIs it Visible in JSP Is it Visible inIs it Visible in End
Generated ServletUser's Response -

Source Code

Example07
Loading editor…

Scripting Elements

Eg1:out.print(<%= new java.util.Date() %>);
Example08
Loading editor…

Scripting Elements

Eg 2:

Example09
Loading editor…

Scripting Elements

Eg 4:

Example10
Loading editor…

Scripting Elements

Comparison Table of JSP Scripting Elements

ElementSyntaxEnds with ; Is Code generated

inside _jspService()

Expression <%= X %> No Method OR not?

ScriptletYes
Declaration <%Yes
Any Java CodeYes

Comments

%> Yes No

<%! NA NA

Any Java

Declarations

%>

<%--

This is JSP

Comment

%>

Directives (in Detail)

Objective:

Write JSP Code that uses the following directives

Example11
Loading editor…

Scripting Elements

Directives can provide general information about JSP page to the JSP Engine. i.e Directives are

translation time instructions to the JSP Engine.

Syntax: <%@ directiveName attributeName=attributeValue %>

page|include|taglib

There are 3 types of directives are possible

Example12
Loading editor…

Scripting Elements

I) page directive:

page directive specifies overall properties of JSP Page to the JSP Engine.

(like Tell me about yourself? in HR Round)

Eg1: <%@ page language="java" %>

This page directive specifies to the JSP Engine that the scripting language used in this jsp is

java.

Eg2: <%@ page session="true" %>

This page directive specifies that the current jsp participating in session management.

We can use page directive any number of times, anywhere in the jsp.

The following is the list of all possible 13 attributes of page directive.

Example13
Loading editor…

Scripting Elements

We can use import attribute to import classes and interfaces of a particular package in the

JSP.

This is similar to core java import statement.

demo.jsp without import attribute:

<h1>The Server Time is:<%= new java.util.Date() %></h1>

demo.jsp with import attribute:

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

<h1>The Server Time is:<%= new Date() %></h1>

To import multiple packages the following are various possibilities...

Example14
Loading editor…

Scripting Elements

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

Example15
Loading editor…

Scripting Elements

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

Example16
Loading editor…

Scripting Elements

Within the same JSP, we are not allowed to take any attribute multiple times with

multiple values. But we can take multiple times with same value. This rule is not

applicable for import attribute.

Q. Which of the following page directives are valid?

Example17
Loading editor…

Scripting Elements

Note:

Inside JSP, the following packages are by default available and hence we are not required to

import these packages explicitly.

java.lang.*;

javax.servlet.*;

javax.servlet.http.*;

javax.servlet.jsp.*;

Example18
Loading editor…

Scripting Elements

By default session object is available in every JSP. If we don't want session object then we can

make it unavailable by using page directive session attribute as follows

<%@ page session="false" %>

If we are not declaring session attribute explicitly or declaring session attribute with "true"

value, then the generated servlet code is:

HttpSession session = null;

session = pageContext.getSession();

If we declare explicitly with false value, then the above code won't be generated.

The allowed values for the session attribute are:

true TRUE True FALse durga

i.e. case insensitive String of true or false is allowed.

If we are taking any other value then we will get Translation Time error.

Eg: <%@ page session="sunny" %>

Error: invalid value for session

Example19
Loading editor…

Scripting Elements

We have to use this attribute to specify content type of response(i.e MIME Type of Response)

<%@ page contentType="application/pdf" %>

The default value content type is : text/html

Example20
Loading editor…

Scripting Elements

Expression Language(EL) has introduced in JSP 1.2V

The main objective of EL is to remove java code from the JSP.

Example21
Loading editor…

Scripting Elements

EL Syntax won't be processed and just treated as plain text.

Example22
Loading editor…

Scripting Elements

EL Syntax will be processed and print its value.

Eg: http://localhost:7777/jspdapp1/demo.jsp?user=Mallika

demo.jsp:

Example23
Loading editor…

Scripting Elements

o/p: User Name: Mallika

demo.jsp:

Example24
Loading editor…

Scripting Elements

o/p: User Name: ${param.user}

Note:

The default value of isELIgnored is true in JSP 1.2V.

But from JSP 2.0V onwards the default value is false.

Example25
Loading editor…

Scripting Elements

By Default a single JSP page can be accessed by multiple threads simultaneously. Hence JSP is

not thread safe by default.

To provide Thread Safety to the JSP we should go for isThreadSafe attribute.

Example26
Loading editor…

Scripting Elements

It means JSP page is already thread safe & it is not required generated servlet to

implement SingleThreadModel.

In this case JSP Page can process any number of client requests simultaneously.

Example27
Loading editor…

Scripting Elements

The current JSP is not thread safe. Hence to provide thread safety, Generated servlet will

implements SingleThreadModel interface.

In this case JSP Page can process only one request at a time.

Note: The default value of isThreadSafe attribute is true.

Q. To provide Thread Safety, which of the following arrangement we have to take in the JSP?

Example28
Loading editor…

Scripting Elements

Summary of Page Attributes

AttributePurposeDefault Value

No Default Value. But the following 4

Example29
Loading editor…

Scripting Elements

Interfacesavailable by Default in every JSP.
Example30
Loading editor…

Scripting Elements

Response4. javax.servlet.jsp

To disable Expression

Language in the JSPtrue

To provide Thread Safety to

the JSPtext/ html

false

true

Example31
Loading editor…

II) include directive

We can implement include mechanism either by include directive or by include action.

Example32
Loading editor…

Include Directive

second.jsp:

<h1>This is Second JSP</h1>

For both including and included JSPs, a single servlet will be generated.

Example33
Loading editor…

Include Action

second.jsp:

<h1>This is Second JSP</h1>

For both including and Included JSPs, separates servlets will be generated.

Differences b/w Include Directive and Include Action

Include DirectiveInclude Action
1) <%@ include file = "second.jsp" %>1) <jsp:include page = "second.jsp"
Contains only one Attribute File.flush = "true"/>

Contains 2 Attributes Page and File.

Example34
Loading editor…

Include Action

Translation Time. Hence it is also considered asRuntime. Hence it is also considered as
Static Include.Dynamic Include.
Example35
Loading editor…

Include Action

Servlet will be generated. Hence Code sharingseparate Servlets will be generated. Hence Code
between the Components is possible.sharing between the Components is not

possible.

Example36
Loading editor…

Include Action

latest Version included JSP. It is Vendorbe included.

Dependent.

Example37
Loading editor…

Include Action

frequently then it is recommended to usefrequently then it is recommended to use
Static Include.Dynamic Include.

Logo Inclusion

(Static Include by Include Directive)

About Us InclusionSports Info Inclusion

(Static Include by Include Directive) (Dynamic Include by Include Action)

Politics InformationMovies Information

(Dynamic Include by Include Action) (Dynamic Include by Include Action)

Copy Right Inclusion

(Static Include by Include Directive)

Note:

To include the content of header.jsp at translation time, the required import is:

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

To include the response of header.jsp at request processing time (run time), the required import

is:

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

Q. Which of the following inclusions are valid?

1.<%@ include page="header.jsp" %>

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

3.<jsp:include file="header.jsp" />

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

5.<jsp:include page="header.jsp" flush="true"/>

6.<%@ include file="header.jsp" flush="true"%>

Note:

page attribute is applicable for include action where as file attribute is applicable for include

directive.

flush attribute is applicable only for include action but not for include directive.

Example38
Loading editor…

III) taglib directive

Example39
Loading editor…
📝 Key Takeaways
  • Scriptlets land inside _jspService(), declarations outside
  • page directive attributes and their defaults
  • include directive is static, jsp:include is dynamic

Finished this lesson?

Mark it as complete to track your progress and see technology completion stats.