VI SEM BCA Advanced Java - UNIT 4 - JSP-P1 MATERIAL
VI SEM BCA Advanced Java - UNIT 4 - JSP-P1 MATERIAL
STUDY MATERIALS
FOR
VI SEMESTER BCA
Advantages of JSP
Following is the list of other advantages of using JSP over other technologies:
vs. JavaScript
JavaScript can generate HTML dynamically on the client but can hardly
interact with the web server to perform complex tasks like database access and
image processing etc.
The JSP engine compiles the servlet into an executable class and
forwards the original request to a servlet engine.
Apart of the web server called the servlet engine loads the Servlet class
and executes it. During execution, the servlet produces an output in
HTML format. This output is further passed on to the web server by the
servlet engine inside an HTTP response.
The web server forwards the HTTP response to our browser in terms of
static HTML content.
Finally, the web browser handles the dynamically-generated HTML page
inside the HTTP response exactly as if it were a static page.
All the above mentioned steps canbe seen in the following diagram:
Typically, the JSP engine checks to see whether a servlet for a JSP file already
exists and whether the modification date on the JSP is older than the servlet. If
the JSP is older than its generated servlet, the JSP container assumes that the
JSP hasn't changed and that the generated servlets till matches the JSP's
contents. This makes the process more efficient than with the other scripting
languages (such as PHP) and therefore faster.
So in a way, a JSP page is really just another way to write a servlet without
having to be a Java programming wiz. Except for the translation phase, a JSP
page is handled exactly like a regular servlet.
The four major phases of a JSP life cycle are very similar to the Servlet Life
Cycle. The four phases have been described below:
JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it
needs to compile the page. If the page has never been compiled, or if the JSP
has been modified since it was last compiled, the JSP engine compiles the
page.
The compilation process involves three steps:
Parsing the JSP.
Turning the JSP in to a servlet.
Compiling the servlet.
JSP Initialization
When a container loads a JSP it invokes the jspInit() method before servicing
any requests. If we need to perform JSP-specific initialization, override the
jspInit() method:
Typically, initialization is performed only once and as with the servlet init
method, we generally initialize database connections, open files, and create
lookup tables in the jspInit method.
JSP Execution
This phase of the JSP life cycle represents all interactions with requests until
the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and
initialized, the JSP engine invokes the _jspService() method in the JSP.
The_jspService() method takes an HttpServletRequest and an
HttpServletResponse as its parameters as follows:
JSP Cleanup
The destruction phase of the JSP lifecycle represents when a JSP is being
removed from use by a container.
The jspDestroy() method is the JSP equivalent of the destroy method for
servlets. Override jspDestroy when you need to perform any cleanup, such as
releasing database connections or closing open files.
The jspDestroy() method has the following form:
public void jspDestroy()
{
//Yourcleanupcodegoeshere.
}
P─SYNTAX
JSP Syntax:
Let us understand the basic use of simple syntax (i.e., elements) involved with
JSP development.
Elements of JSP
The elements of JSP have been described below:
The Scriptlet
A scriptlet can contain any number of JAVA language statements, variable or
method declarations, or expressions that are valid in the page scripting
language.
Following is the syntax of Scriptlet:
<jsp:scriptlet>
Code fragment
</jsp:scriptlet>
Any text, HTML tags, or JSP elements we write must be outside the scriptlet.
Following is the simple and first example for JSP:
<html>
<head><title>HelloWorld</title></head>
<body>
HelloWorld!<br/>
<%
out.println("Your IP address is"+request.getRemoteAddr());
%>
</body>
</html>
Let us keep the above code in JSP file hello.jsp and put this file inC:\apache-
tomcat- 7.0.2\webapps\ROOT directory. Browse through the same using URL
http://localhost:8080/hello.jsp. This would generate the following result:
JSP Declarations
A declaration declares one or more variables or methods that we can use in
Java code later in the JSP file. You must declare the variable or method before
you use it in the JSP file.
Following is the syntax for JSP Declarations:
You can write the XML equivalent of the above syntax as follows:
Following is an example for JSP Declarations:
JSP Expression
A JSP expression element contains a scripting language expression that is
evaluated, converted to a String, and inserted where the expression appears in
the JSP file. Because the value of an expression is converted to a String, you can
use an expression within a line of text, whether or not it is tagged with HTML, in
a JSP file.
The expression element can contain any expression that is valid according to the
Java Language Specification but you cannot use a semicolon to end an
expression.
Following is the syntax of JSP Expression:
You can write the XML equivalent of the above syntax as follows:
<jsp:expression>
expression
</jsp:expression>
<html>
<head><title>A Comment Test</title></head>
<body>
<p>
Today'sdate:<%= (new java.util.Date()).toLocaleString()%>
</p>
</body>
</html>
The above code will generate the following result:
JSP Comments
JSP comment marks the text or the statements that the JSP container should
ignore. A JSP comment is useful when you want to hide or "comment out", a
part of your JSP page.
Following is the syntax of the JSP comments:
<html>
<head><title>A Comment Test</title></head>
<body>
<h2>A Test of Comments</h2>
<%--This comment will not be visible in the page source--%>
</body>
</html>
There are a small number of special constructs you can use in various cases to
insert comments or characters that would otherwise be treated specially. Here's
a summary:
Syntax Purpose
JSP Directives
A JSP directive affects the overall structure of the servlet class. It usually has
the following form:
<%@directive attribute="value"%>
Directive Description
JSP Actions
JSP actions use constructs in XML syntax to control the behavior of the
servlet engine. You can dynamically insert a file, reuse JavaBeans components,
forward the user to another page, or generate HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML
standard:
<jsp:action_name attribute="value"/>
Action elements are basically predefined functions. Following table lists out the
available JSP Actions:
Syntax Purpose
Objects Description
Control-Flow Statements
You can use all the APIs and building blocks of Java in your JSP programming
including decision-making statements, loops, etc.
Decision-Making Statements
The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is
closed at each line with HTML text included between the Scriptlet tags.
<%!intday=3;%>
<html>
<head><title>IF...ELSEExample</title></head>
<body>
<%if(day==1|day==7){%>
<p>Todayisweekend</p>
<%}else{%>
<p>Todayisnotweekend</p>
<%}%>
</body>
</html>
Now look at the following switch...case block which has been written a bit
differently using out.println() and inside Scriptletas:
break;
case 1:
out.println("It\'sMonday.");
break;
case2:
out.println("It\'sTuesday.");
break;
case3:
out.println("It\'sWednesday.");
break;
case4:
out.println("It\'sThursday.");
break;
case5:
out.println("It\'sFriday.");
break;
default:
out.println("It'sSaturday.");
}
%>
</body>
</html>
Loop Statements
You can also use three basic types of looping blocks in Java: for, while, and
do…while blocks in your JSP programming.
Let us look at the following for loop example:
<body>
<%for(fontSize=1;fontSize<=3;fontSize++){ %>
<fontcolor="green"size="<%=fontSize%>"> JSP
Tutorial
</font><br/>
<%}%>
</body>
</html>
JSP Operators
JSP supports all the logical and arithmetic operators supported by Java.
Following table lists out all the operators with the highest precedence appear at
the top of the table, those with the lowest appear at the bottom.
Within an expression, higher precedence operators will be evaluated first.
JSP Literals
The JSP expression language defines the following literals:
Boolean: true and false
Integer: as in Java
Floating point: as in Java
String: with single and double quotes; " is escaped as \", ' is escaped as
\', and \ is escaped as \\.
Null: null
JSP Directives
The JSP directives provide directions and instructions to the container, telling it
how to handle certain aspects of the JSP processing.
A JSP directive affects the overall structure of the servlet class. It usually has the
following form:
Directives can have a number of attributes which you can list down as key-
value pairs and separated by commas.
The blanks between the @symbol and the directive name, and between the last
attribute and the closing %>, are optional.
There are three types of directive tag:
Directive Description
You can write the XML equivalent of the above syntax as follows:
<jsp:directive.page attribute="value"/>
Attributes
Following table lists out the attributes associated with page directive:
Attribute Purpose
Use the following to direct the servlet to write the output to a buffer of size not
less than 8 kilobytes:
This directive causes the servlet to flush the output buffer when full:
Usually, the buffer and the autoFlush attributes are coded on a single page
directive as follows:
The following statement directs the browser to render the generated page as
HTML:
The following directive sets the content type as a Microsoft Word document:
You can also specify the character encoding for the response. For example, if
you wanted to specify that the resulting page that is returned to the browser
uses ISOLatin1, you can use the following page directive:
<%@ page contentType="text/html:charset=ISO-8859-1" %>
The filename in the include directive is actually a relative URL. If you just
specify a filename with no associated path, the JSP compiler assumes that the
file is in the same directory as your JSP.
You can write the XML equivalent of the above syntax as follows:
Example
A good example of the include directive is including a common header and
footer with multiple pages of content.
Let us define following three files (a)header.jps, (b)footer.jsp, and (c)main.jsp
as follows:
Followingisthecontentofheader.jsp:
<%!
intpageCount=0; void
addCount() {
pageCount++;
}
%>
<%addCount();%>
<html>
<head>
<title>TheincludeDirectiveExample</title>
</head>
<body>
<center>
<h2>TheincludeDirectiveExample</h2>
<p>Thissitehasbeenvisited<%=pageCount%>times.</p>
</center>
<br/><br/>
<%@includefile="header.jsp"%>
<center>
<p>Thanksforvisitingmypage.</p>
</center>
<%@includefile="footer.jsp"%>
Let us now keep all these files in the root directory and try to access main.jsp.
You will receive the following output:
Refresh main.jsp and you will find that the page hit counter keeps increasing.
You can design your web pages based on your creative instincts; it is
recommended you keep the dynamic parts of your website in separate files and
then include them in the main file. This makes it easy when you need to
change a part of your webpage.
Here, the uri attribute value resolves to a location the container understands
and the prefix attribute informs a container what bits of markup are custom
actions.
You can write the XML equivalent of the above syntax as follows:
When you use a custom tag, it is typically of the form <prefix:tagname>. The
prefix is the same as the prefix you specify in the taglib directive, and the tag
name is the name of a tag implemented in the tag library.
Example
For example, suppose the custlib tag library contains a tag called hello. If you
wanted to use the hello tag with a prefix of mytag, your tag would be
<mytag:hello> and it will be used in your JSP file as follows:
<body>
<mytag:hello/>
</body>
</html>