The JavaServer pages technology model
JavaServer Pages (JSP) technology is an extension of the Java Servlet API. JSP pages are typically comprised of static HTML/XML components, custom JSP tags, and Java code snippets known as scriptlets.
Even though JSP pages can contain business processing logic, they are mainly used for generating dynamic content in the presentation layer. Separation of business logic from presentation logic is one of the main advantages of this technology.
JSP syntax can be classified into directives, declarations, scriptlets, expressions, standard actions, and comments.
Directives
A JSP directive provides information about the JSP page to the JSP engine. The types of directives are page,
include,
and taglib (a directive starts with a <%@ and ends with a %> ):
- The
pagedirective is used to define certain attributes of the JSP page:<%@ page import="java.util.*, com.foo.*" %> - The
includedirective is used to include the contents of a file in the JSP page:<%@ include file="/header.jsp" %> - The
taglibdirective allows us to use the custom tags in the JSP pages:<%@ taglib uri="tlds/taglib.tld" prefix="mytag" %>
Declarations
JSP declarations let you define variables and supporting methods that the rest of a JSP page may need.
To add a declaration, you must use the <%! and %> sequences to enclose your declarations, starting with a <%! and ending with a %>:
<%! int sum=0; %> |
Here the variable sum is initialized only once when the JSP page is loaded.
Scriptlets
Scriptlets are fragments of code that are embedded within <% ... %> tags.
They get executed whenever the JSP page is accessed:
<%
int count=0;
count++;
out.println("Count is "+count);
%>
|
Expressions
An expression is a Java expression that is evaluated when the JSP page is accessed and its value gets printed in the resultant HTML page. JSP expressions are within <%= ... %> tags and do not include semicolons:
<%= count %> |
The above expression prints out the value of the variable count.
Standard actions
JSP actions are instructions that control the behavior of the servlet engine. The six standard JSP actions are jsp:include, jsp:forward, jsp:useBean, jsp:setProperty, jsp:getProperty, and jsp:plugin. We will discuss actions in more detail in the following sections.
Comments
A JSP comment is of the form <%-- Content to be commented --%>.
The body of the content is ignored completely.
JSP files can now use either JSP syntax or XML syntax within their source files. However, you cannot intermix JSP syntax and XML syntax in a source file.
JSP files using XML syntax are called JSP documents. All JSP documents have a <jsp:root> element within which all the other elements are enclosed:
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:prefix1="URI-for-taglib1"
xmlns:prefix2="URI-for-taglib2" ...version="1.2">
// contents of the JSP page
</jsp:root>
|
Let's view a sample JSP document:
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="1.2"> <jsp:directive.page errorPage="error.jsp" /> <jsp:directive.include file="test.jsp"/> <jsp:declaration> int count=10; </jsp:declaration> <jsp:text> Hello </jsp:text> <jsp:expression> count * 10 </jsp:expression> <jsp:scriptlet> int i=100; int j=11; out.println(i+j); </jsp:scriptlet> </jsp:root> |
You can see that the <jsp:scriptlet> tag is used for scriptlets, the <jsp:expression> tag is used for expressions, the <jsp:declaration> tag is used for declarations, and the <jsp:text> tag is used to embed text within a JSP document. The page directive is represented as <jsp:directive.page> and the include directive is represented as
<jsp:directive.include>.
It is important to note that all the tags are case sensitive.
As discussed before, the page directives are used to define attributes that apply to the JSP page as a whole. These are passed onto the JSP container at translation time. Let's discuss the important page attributes that are relevant for the SCWCD exam.
import
The import attribute of a page directive is used to import a Java class into the JSP page. For instance:
<%@ page import="java.util.*, java.io.*,com.whiz.MyClass" %> <%@ page import="com.whiz.TestClass" %> |
It can appear multiple times in a translation unit.
session
The session attribute can have a value of true or false. It specifies whether the page should take part in an HttpSession.
The default value is true. For instance:
<%@ page session="false" %> |
errorPage
The errorPage attribute can be used to delegate the exception to another JSP page that has the error handling code. For instance:
<%@ page errorPage="error.jsp" %> |
isErrorPage
The isErrorPage attribute specifies whether the current page can be the error handler for other JSP pages. The default value is false. For instance:
<%@ page isErrorPage="true" %> |
language
The language attribute specifies the language used by the JSP page; the default value is "java." For instance:
<%@ page language="java" %> |
extends
The extends attribute specifies the superclass of the generated servlet class of the JSP page. The default value of this attribute is vendor-specific. For instance:
<%@ page extends="mypackage.MyServlet" %> |
buffer
The buffer attribute gives the minimum size of the output buffer before the content is sent to the client.
For instance:
<%@ page buffer="32kb" %> |
autoFlush
The autoFlush attribute specifies whether the data in the buffer should be sent to the client as soon as the buffer is full. The default value is true. For instance:
<%@ page autoFlush="false" %> |
When a request is mapped to a JSP page for the first time, it translates the JSP page into a servlet class and compiles the class. It is this servlet that services the client requests.
A JSP page has seven phases in its lifecycle, as listed below in the sequence of occurrence:
- Translation
- Compilation
- Loading the class
- Instantiating the class
-
jspInit()invocation -
_jspService()invocation -
jspDestroy()invocation
Translation
In this phase, the JSP page is read, parsed, and validated. If there are no errors, a Java file containing the servlet class is created.
Compilation
The Java file created in the translation phase is compiled into a class file. All the Java code is validated and syntax errors are reported in this phase.
Loading and instantiating
The servlet class is loaded into memory and instantiated, if the compilation is successful.
jspInit()
The jspInit() method is called only once in the life of the servlet. It is this method that we perform any initializations required for the servlet.
_jspService
The request and response objects are passed to this method when each client request is received for the JSP page. JSP scriptlets and expressions are processed and included in this method.
jspDestroy()
The jspDestroy() method is called when the servlet instance is taken out of service by the JSP engine. Any cleanup operation, such as releasing resources, can be performed in this method. After this method is called, the servlet is unable to serve any client requests.
The JSP container makes available nine implicit objects that can be used within scriptlets and expressions because they are defined in the _jspService() method of the generated servlet.
The nine implicit objects in the JSP API and their purpose are listed in the following table:
Table 2. Implicit objects
| Object | Class | Purpose |
application
|
javax.servlet.ServletContext
| Refers to the Web application's environment in which the JSP is executed. |
config
|
javax.servlet.ServletConfig
| The initialization parameters given in the deployment descriptor can be retrieved from this object. |
exception
|
java.lang.Throwable
| Available for pages that set the page directive attribute isErrorPage to true. It can be used for exception handling. |
Out
|
javax.servlet.jsp.JspWriter
| Refers to the output stream of the JSP page. |
page
|
java.lang.Object
| Refers to the current instance of the servlet generated from the JSP page. |
pageContext
|
javax.servlet.jsp.PageContext
| Provides certain convenience methods and stores references to the implicit objects. |
request
| Subtype of javax.servlet.ServletRequest
| Refers to the current request passed to the _jspService() method. |
response
| Subtype of javax.servlet.ServletResponse
| Refers to the response sent to the client. It is also passed to the _jspService() method. |
Conditional and iterative statements
For generating dynamic content based on conditions, we can use conditional statements, such as if/else blocks. For performing repetitive tasks, there are iterative statements using for or while loops. Conditional and iterative statements can span across multiple scriptlets, so that we can include HTML code in between.
For instance, the following scriptlet code uses a conditional statement to check whether a user's password is valid. If it is valid, the marks are printed using an iterative statement.
<% if(passwordValid)
{
%>
Welcome, <%= username %>
<%
for(int i=0; i<10; i++)
{
%>
Printing <%=marks[i] %>
<%
}
}
%>
|
Be careful not to leave out the curly braces at the beginning and end of the Java fragments.
In this section, you saw the basics of the JavaServer Pages (JSP) model. You learned about the various tag types and their purposes, and the various page directive attributes. Next, you identified the different phases in the JSP page lifecycle, followed by the nine implicit objects in the JSP API and the purpose of each of them. Finally, we saw how conditional and iteration statements can span across multiple scriptlets.
Question 1:
What will be the result of accessing the following JSP page, if the associated session does not have an attribute named str?
<%!
String str;
public void jspInit()
{
str = (String)session.getAttribute("str");
}
%>
|
The string is: <%= str %>.
Choices:
- A. "null" is printed
-
B.
NullPointerExceptionis thrown - C. Code does not compile
- D. None of the above
Correct choice:
- C
Explanation:
The JSP engine declares and initializes nine objects in the _jspService() method. These implicit object variables are application,
session,
request,
response,
out,
page,
pageContext,
config,
and exception.
Because they are declared locally to the _jspService() method, they are not accessible within the jspInit() method, which means this code will not compile. If this code was within the jspService() method, it would have compiled without errors and printed "null." Hence choices A, B, and D are incorrect, and choice C is correct.
Question 2:
What will be the result of an attempt to access this JSP page?
<% x=10;% > <% int x=5;% > <%! int x; %> x= <%=x%> x= <%=this.x%> |
The string is <%= str %>.
Choices:
- A. Code does not compile because x is used before declaration
- B. Prints x=5 followed by x=10
- C. Prints x=10 followed by x=5
- D. Prints x=10 followed by x=0
- E. None of the above
Correct choice:
- B
Explanation:
This declaration will create an instance variable x and initialize it to 0. Then in the service() method, you modify it to 10. Then you declare a local variable named x and give it the value 5. When you print x, it prints the local version of value 5. When you say this.x,
you refer to the instance variable x, which prints 10. Hence choices A, C, and D are incorrect, and choice B is correct.

