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
JCode Cell
1 
2public final class demo_jsp extends...
3{
4...
5public void _jspService(..)...
6{
7out.write("<h1>The Server Time is:");
8out.print(new java.util.Date());
9out.write("</h1>");
10}
11}
12

Template Text

Example02
JCode Cell
1 
2<jsp:useBean>
3<jsp:setProperty>
4<jsp:getProperty>
5<jsp:include>
6<jsp:forward>
7<jsp:param>
8<jsp:plugin>
9<jsp:fallback>
10<jsp:params>
11

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
JCode Cell
1 
2<%= 27 %>
3<%= "27" %>
4<%= Math.random() %>
5<%= 10*20 %>
6<%= 10>20 %>
7<%= new Student() %>
8<%= String s ="durga" %>
9

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
JCode Cell
1 
2%>
3

Scripting Elements

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

demo.jsp:

Example05
JCode Cell
1 
2<%!
3int x =10;
4static int y = 20;
5int[] a ={10,20,30};
6public void m1()
7{
8}
9%>
10

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
JCode Cell
1 
2<%!
3public void m1()
4{
5out.println("Hello");
6}
7%>
8
Output

Hello
      

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
JCode Cell
1 
2<%
3out.println("Hello");
4%>
5 
6<%= session.getId() %>
7
Output

Hello
      

Scripting Elements

Eg1:out.print(<%= new java.util.Date() %>);
Example08
JCode Cell
1 
2JSP Comments
3HTML Comments
4Java Comments
5

Scripting Elements

Eg 2:

Example09
JCode Cell
1 
2<%
3 
4%>
5

Scripting Elements

Eg 4:

Example10
JCode Cell
1 
2<%! <%-- This is very important method.. --%>
3public void m1()
4{
5}
6 
7%>Eg3:
8<% <%-- This java code meant for user validataion --%>
9out.println("validation");
10 
11%>
12
Output

validation
      

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
JCode Cell
1 
2<% <%
3out.println("Hello");
4 
5%>
6%>
7
Output

Hello
      

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
JCode Cell
1 
2page 2. include 3. taglib
3

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
JCode Cell
1 
2page directive
3include directive
4taglib directive
5

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
JCode Cell
1 
2import
3session
4contentType
5isELIgnored
6isThreadSafe
7isErrorPage
8errorPage
9language
10extends
11buffer
12autoFlush
13info
14pageEncoding
15import:
16

Scripting Elements

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

Example15
JCode Cell
1 
2<%@ page import="java.util.*" %>
3

Scripting Elements

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

Example16
JCode Cell
1 
2<%@ page import="java.util.*" import="java.io.*" %>
3

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
JCode Cell
1 
2<%@ page import="java.util.*" import="java.io.*" %>***Note:
3

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
JCode Cell
1 
2<%@ page session="true" session="false" %>
3<%@ page session="true" session="true" %>
4<%@ page session="true" %>
5<%@ page import="java.util.*" import="java.io.*" %>
6<%@ page import=java.util.* %> B'Z single or double quotes are required.
7

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
JCode Cell
1 
2session:
3

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
JCode Cell
1 
2contentType:
3

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
JCode Cell
1 
2isELIgnored:
3

Scripting Elements

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

Example22
JCode Cell
1 
2isELIgnored="true"
3

Scripting Elements

EL Syntax will be processed and print its value.

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

demo.jsp:

Example23
JCode Cell
1 
2isELIgnored="false":
3

Scripting Elements

o/p: User Name: Mallika

demo.jsp:

Example24
JCode Cell
1 
2<%@ page isELIgnored="false" %>
3<h1>User Name: ${param.user}</h1>
4

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
JCode Cell
1 
2<%@ page isELIgnored="true" %>
3<h1>User Name: ${param.user}</h1>
4

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
JCode Cell
1 
2isThreadSafe:
3

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
JCode Cell
1 
2isThreadSafe="true":
3

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
JCode Cell
1 
2isThreadSafe="false":
3

Scripting Elements

Summary of Page Attributes

AttributePurposeDefault Value

No Default Value. But the following 4

Example29
JCode Cell
1 
2<%@ page isThreadSafe="true" %>
3<%@ page isThreadSafe="false" %>
4Not required any arrangement b'z every JSP is by default Thread Safe
5

Scripting Elements

Interfacesavailable by Default in every JSP.
Example30
JCode Cell
1 
2import To Import Classes and Packages are not required to import because
3

Scripting Elements

Response4. javax.servlet.jsp

To disable Expression

Language in the JSPtrue

To provide Thread Safety to

the JSPtext/ html

false

true

Example31
JCode Cell
1 
2session
3contentType To make Session Object 1. java.lang
4isELIgnored unavailable to the JSP 2. javax.servlet
5isThreadSafe To specify MIME Type of 3. javax.servlet.http
6

II) include directive

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

Example32
JCode Cell
1 
2It promotes code reusability
3It improves maintainability of the code
4Enhancement will become very easy
5

Include Directive

second.jsp:

<h1>This is Second JSP</h1>

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

Example33
JCode Cell
1 
2<%@ include file="second.jsp" %>
3<h1>This is First JSP</h1>
4

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
JCode Cell
1 
2<jsp:include page="second.jsp" />
3<h1>This is First JSP</h1>
4

Include Action

Translation Time. Hence it is also considered asRuntime. Hence it is also considered as
Static Include.Dynamic Include.
Example35
JCode Cell
1 
2The Content of Target JSP will be included at 2) The Response Target JSP will be included at
3

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
JCode Cell
1 
2For both including and included JSPs, a Single 3) For both including and included JSPs,
3

Include Action

latest Version included JSP. It is Vendorbe included.

Dependent.

Example37
JCode Cell
1 
2Relatively Performance is High. 4) Relatively Performance is Low.
3There is no Guarantee for Inclusion of 5) Always latest Version of included Page will
4

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
JCode Cell
1 
2If the Target Resource won't change 6) If the Target Resource will change
3

III) taglib directive

Example39
JCode Cell
1 
2request HttpServletRequest(I)
3response HttpServletResponse(I)
4config ServletConfig(I)
5application ServletContext(I)
6session HttpSession(I)
7out javax.serlvet.jsp.JspWriter(AC)
8page java.lang.Object(CC)
9pageContext javax.servlet.jsp.PageContext(AC)
10exception java.lang.Throwable(CC)
11
📝 Key Takeaways
  • Scriptlets land inside _jspService(), declarations outside
  • page directive attributes and their defaults
  • include directive is static, jsp:include is dynamic