JSP 2.1 Overview: JSP stands for “Java server page” and built by SUN Microsystem. JSP technology is used to create web application. It focuses more on presentation logic of the web application. JSP pages are easier to maintain then a Servlet. JSP pages are opposite of Servlets. Servlet adds HTML code inside Java code while JSP adds Java code inside HTML. Everything a Servlet can do, a JSP page can also do it. JSP enables us to write HTML pages containing tags that run powerful Java programs. JSP separates presentation and business logic as Web designer can design and update JSP pages without learning the Java language and Java Developer can also write code without concerning the web design. JSP Architecture: The web server needs a JSP engine ie., container to process JSP pages. The JSP container is responsible for intercepting requests for JSP pages. A JSP container works with the Web server to provide the runtime environment and other services a JSP needs. It knows how to understand the special elements that are part of JSPs. Following diagram shows the position of JSP container and JSP files in a Web Application.
Fig: Architecture of jsp
JSP Processing: By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP
The following steps explain how the web server creates the web page using JSP: i. ii. iii. iv.
v. vi. vii. v. vi.
User requesting a JSP page through internet via web browser. The JSP request is sent to the Web Server. Web server accepts the requested .jsp file and passes the JSP file to the JSP Servlet Engine. If the JSP file has been called » the first time then the JSP file is parsed » otherwise servlet is instantiated. The next step is to generate a servlet from the JSP file. [In that servlet, all the HTML code is converted in println statements.] Now, the servlet source code file is compiled into a class file (bytecode file). The servlet is instantiated by calling the init and service methods of the servlet’s life cycle. Now, the generated servlet output is sent via the Internet form web server to user's web browser. Now in last step, HTML results are displayed on the user's web browser. In the end, a JSP is just a Servlet.
Life Cycle: A JSP life cycle can be defined as the entire process from its creation till the destruction which is similar to a servlet life cycle with an additional step which is required to compile a JSP into servlet. The following are the paths followed by a JSP Compilation Initialization Execution Cleanup The four major phases of JSP life cycle are very similar to Servlet Life Cycle and they are as follows: 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 into a servlet Compiling the servlet
By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP
JSP initialization: When a container loads a JSP it invokes the jspInit() method which is identical in both Java Servlet and applet. It is called first when the JSP is requested and is used to initialize objects and variables that are used throughout the life of the JSP. Syntax:
public void jspInit(){ //Initialization code... }
JSP execution: Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine invokes the _jspService() method is automatically and retrieves a connection to HTTP. It will call doGet or doPost() method of servlet created. Syntax: void _jspService(HttpServletRequest request, HttpServletResponse response) { // Service handling code... } JSP cleanup: The jspDestroy() method is automatically called when the JSP terminates normally. Override jspDestroy() for cleanup where resources used during the execution of the JSP, such as such as releasing database connections or closing open files. Syntax:
public void jspDestroy{ // Initialization code... }
All the above mentioned steps can be shown below in the following diagram:
Fig: Flow diagram of the JSP life Cycle By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP
JSP Operations in Various Scenarios:
2.2 Advantage of JSP over different technologies: Advantage of JSP over Servlet: Extension to Servlet: JSP technology is the extension to servlet technology. We can use all the features of servlet in JSP. In addition to, we can use implicit objects, predefined tags, expression language and Custom tags in JSP that makes JSP development easy. Easy to maintain JSP can be easily managed because we can easily separate our business logic with presentation logic. In servlet technology, we mix our business logic with the presentation logic. Fast Development: No need to recompile and redeploy If JSP page is modified, we don't need to recompile and redeploy the project. The servlet code needs to be updated and recompiled if we have to change the look and feel of the application.
By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP
Less code than Servlet In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the code. Moreover, we can use EL, implicit objects etc. Advantages of JSP vs. Active Server Pages (ASP): First, the dynamic part is written in Java, not Visual Basic or other MS specific language, so it is more powerful and easier to use. Second, it is portable to other operating systems and non-Microsoft Web servers. Advantages of JSP Vs PHP[“Hypertext Preprocessor”]: First, is that the dynamic part is written in Java, which already has an extensive API for networking, database access, distributed objects, and the like, whereas PHP requires learning an entirely new, less widely used language. A second, is that JSP is much more widely supported by tool and server vendors than is PHP. Advantages of JSP 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.
2.3 Basic syntax: JSP tags are an important syntax element of Java Server Pages which start with "<%" and end with "%>" just like HTML tags. Fundamental tags used in Java Server Pages are classified into the following categories: Comments Declaration tag Expression tag Scriptlet tag Directive tag Expression language tag Tags HTML Text
Comments
HTML Comments
Template Text JSP Comment
Description HTML content to be passed unchanged to the client HTML comment that is sent to the client but not displayed by the browser Text sent unchanged to the client. HTML text and HTML comments are just special cases of this. Developer comment that is not sent to the client
is used within a Java Server page to declare a variable or method that can be JSP referenced by other declarations, Declaration scriptlets, or expressions in a java server page, when page is translated into a servlet. Expression that is evaluated at requested JSP time and sent to the client each time the Expression page is requested. JSP Scriptlet
<%! Field Definition; %> <%! Method Definition;%> Eg:<%! int var = 1; %> <%! int x, y ; %>
<%= Java Value %> Eg:<%=new java.util.Date()%>
<% Java Statement %> Statement or statements that are executed Eg:<% out.println("Your IP each time the page is requested.
address is " + request.getRemoteAddr());%>
page
<%@ directive att="val" %> High-level information about the structure <%@page import="java.util.*"%> of the servlet code
include:
code that is included at page-translation <%@ include file="/header.jsp" %> time.
JSP Expression The purpose of EL is to produce scriptless ${ EL Expression } JSP pages. Language
JSP Action
Action that takes place when the page is requested
..........
Table 2.1: Basic Syntax of JSP Jsp Comments[Creating Template Text]: JSP comment marks text or statements that the JSP container should ignore. A JSP comment is useful when you want to hide or "comment out" part of your JSP page. There are a special constructs you can use in various cases to insert comments or characters that would otherwise be treated specially. Syntax
Purpose
<%-- comment --%>
A JSP comment. Ignored by the JSP engine.
An HTML comment. Ignored by the browser.
<\%
Represents static <% literal.
%\>
Represents static %> literal.
\'
A single quote in an attribute that uses single quotes.
\"
A double quote in an attribute that uses double quotes.
By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP
Example 1: Comments.jsp <%-Document : SimpleJsp Created on : Mar 2, 2015, 5:09:35 AM Author : Suma --%> <%@page contentType="text/html" pageEncoding="UTF-8" %> JSP Page
Hello World!
<%-- This comment will not be visible in the page source --%>
Types of JSP Scripting Elements [invoking java code with JSP Scripting element]: JSP scripting elements let you insert Java code into the servlet that will be generated from the JSP page. There are three forms: a. Declaration Tag b. Scriptlet Tag c. Expression Tag (For Definition refer table 2.1) Example 2: Demo <%! int a=2, b=3; %> <%! int sum(int x, int y){ return(x+y); } %>
Demo for Declaration tag
Addition of two values: <%= a+b %> Addition of two values using function: <%= sum(10,20) %> By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP
Control-Flow Statements: JSP provides full power of Java to be embedded in your web application. You can use all the APIs and building blocks of Java in your JSP programming including decision making statements, loops etc. Conditional Statements are: Branching Statements: if, if-else, nested else-if, else-if Ladder, switch Looping Statements: while, do-while, for, foreach Jumping Statements: continue, break
Branching / Decision Statements: You can also use all if statements are if, if-else, nested else-if, else-if Ladder, switch in your JSP programming. The if...else block starts out like an ordinary Scriptlet, but the Scriptlet is closed at each line with HTML text included between Scriptlet tags. Example 3: Value.html Demo on Conditional Statements CondDemo.jsp [using Scriptlet tag] <%@page="text/html" pageEncoding="UTF-8"%> Check Value using Conditions
By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP
CondDemo.jsp[ using Scriptlet tag] continued <% String str=request.getParameter("Evalue"); if(str.equals("")) out.println("String is Empty"); else { int i= Integer.parseInt(str); if(i==10) out.println("Entered Value is Equal"); else out.println("Entered Value is not equal"); } %> CondDemo.jsp [Scriptlet is closed at each line with HTML text included between Scriptlet tags] Check Value using Conditions <% String str=request.getParameter("Evalue"); if(str.equals("")) { %>
String is Empty
<% } else { int i= Integer.parseInt(str); if(i==10) { %>
Entered Value is Equal
<% } else { %>
Entered Value is not equal
<% } %>
By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP
Output:
Now look at the following switch...case block which has been written a bit differently using out.println() and inside Scriptlet as: Example 4: CondDemo.jsp [switch statement] Check Value using Conditions <% String str=request.getParameter("Evalue"); int i; switch(i=(Integer.parseInt(str)==10)?1:0) { case 0: out.println("Entered Value is not Equal"); break; case 1: out.println("Entered Value is Equal"); break; default: out.println("Entered Proper Input"); } %>
By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP
Looping Statements: You can also use three basic types of looping blocks in Java: for, while, and do…while blocks in your JSP programming. Example 5: Value.html Demo on Conditional Statements LoopDemo.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> Looping Page <% String str=request.getParameter("Evalue"); int n=Integer.parseInt(str); int i=1; while(i<=n) { out.println(i+ " "); i++; } %>
By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP
Output:
foreach Statement: The for-each loop is mainly used to traverse array or collection elements. The advantage of for-each loop is that it eliminates the possibility of bugs and makes the code more readable. Syntax:
for(data_type variable : array | collection){} Example 6: foreach.html foreachDemo
Invoking Java Code from JSP: There are a number of different ways to generate dynamic content from JSP, as illustrated in the below figure.
Call Java code directly: Scripting elements calling servlet code directly. Call Java code indirectly: Scripting elements calling servlet code indirectly (by means of utility classes).
JSP Directives:
Use beans: Develop separate utility classes structured as beans. Use jsp:useBean, jsp:getProperty etc. Use the MVC architecture: Have a servlet respond to original request, look up data, and store results in beans. Forward to a JSP page to present results. JSP page uses beans. Expression Language: Use shorthand syntax to access and output object properties. Custom tags: Develop tag handler classes. Invoke the tag handlers with XML-like custom tags. Fig: Strategies for invoking dynamic code from JSP.
Each of these approaches has a legitimate place; the size and complexity of the project is the most important factor in deciding which approach is appropriate. However, be aware that people err on the side of placing too much code directly in the page much more often than they err on the opposite end of the spectrum. Although putting small amounts of Java code directly in JSP pages works fine for simple applications, using long and complicated blocks of Java code in JSP pages yields a result that is hard to maintain, hard to debug, hard to reuse, and hard to divide among different members of the development team. For Details, see the following stages.
Limiting java code in JSP: You have 25 lines or more lines of Java code that you need to invoke. You have two options: i. Put all 25 lines directly in the JSP page ii. Put the 25 lines of code in a separate Java class, put the Java class in WEB-INF / classes /directoryMatchingPackageName, and use one or two lines of JSP-based Java code to invoke it. By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP
Which is better? The second. Here’s Why? Development: You generally write regular classes in a Java-oriented environment (e.g., an IDE like JBuilder, Eclipse or editor like UltraEdit, emacs). You generally write JSP in an HTML oriented environment like Dreamweaver. The Java-oriented environment is typically better at balancing parentheses, providing tooltips, checking the syntax, colorizing the code, and so forth. Compilation: To compile a regular Java class, you press the Build button in your IDE or invoke javac. To compile a JSP page, you have to drop it in the right directory, start the server, open a browser, and enter the appropriate URL. Debugging: We know this never happens to you, but when we write Java classes or JSP pages, we occasionally make syntax errors. If there is a syntax error in a regular class definition, the compiler tells you right away and it also tells you what line of code contains the error. If there is a syntax error in a JSP page, the server typically tells you what line of the servlet (i.e., the servlet into which the JSP page was translated) contains the error. For tracing output at runtime, with regular classes you can use simple System.out.println statements if your IDE provides nothing better. Division of labor: Many large development teams are composed of some people who are experts in the Java language and others who are experts in HTML but know little or no Java. The more Java code that is directly in the page, the harder it is for the Web developers (the HTML experts) to manipulate it. Testing: Suppose you want to make a JSP page that outputs random integers between designated 1 and some bound (inclusive). You use Math.random, multiply by the range, cast the result to an int, and add 1. Example:
return(1 + ((int)(Math.random() * range)));
If you do this directly in the JSP page, you have to invoke the page over and over to see if you get all the numbers in the designated range but no numbers outside the range. After hitting the Reload button a few dozen times, you will get tired of testing. But, if you do this in a static method in a regular Java class, you can write a test routine that invokes the method inside a loop and then you can run hundreds or thousands of test cases with no trouble. For more complicated methods, you can save the output, and, whenever you modify the method, compare the new output to the previously stored results.
By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP
Example: public class RanUtilities { /*A random int from 1 to range (inclusive)*/ public static int randomInt(int range) { return(1 + ((int)(Math.random() * range))); } /*Test routine. Invoke from the command line with the desired range. Will print 100 values. Verify that you see values from 1 to range (inclusive)and no values outside that interval.*/
public static void main(String[] args) { int range = 10; try { range = Integer.parseInt(args[0]); } catch(Exception e) { // Array index or number format // Do nothing: range already has default value. } for(int i=0; i<100; i++) { System.out.println(randomInt(range)); } } }
Reuse: You put some code in a JSP page. Later, you discover that you need to do the same thing in a different JSP page. What do you do? Cut and paste? Boo! Repeating code in this manner is a cardinal sin because if you change your approach, you have to change many different pieces of code. Solving the code reuse problem is what object-oriented programming is all about. Don’t forget all your good OOP principles just because you are using JSP to simplify the generation of HTML. Using Scripting Elements, Comparing servlets and jsp: Example 8: illustrate the difference in how the three JSP scripting elements are typically used by calling the java code indirectly. cssStyle.css body { background-color: #ffdd88; font-family: CurlZ MT, tahoma, helvetica, arial,; font-size: 1.9em; } By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP
ScriptletPage.jsp <%@page contentType="text/html" pageEncoding="UTF-8"%> JSP Page <%! int n=5;%> <% for(int i=0;i <%= Corepack.DisplayUtilities.display()%> <%}%> DisplayUtilities.java package Corepack; public class DisplayUtilities { public static String display() { return("Welcome"); } } Output:
By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP
In the above example, the goal is to generate a message of n times using scripting elements and compare how the statements are translated into the servlet from the JSP page as shown below. Since the structure of this page is fixed and we use a separate helper class for the display method. JSP declarations result in code that is placed inside the servlet class definition but outside the _jspService method. Since fields and methods can be declared in any order, it does not matter whether the code from declarations goes at the top or bottom of the servlet.
JSP Expression result in code that we oversimplified the out variable (which is a JspWriter, not the slightly simpler PrintWriter that results from a call to getWriter).
» JSP expressions basically become
print (or write) statements in the servlet that
results from the JSP page. » Whereas regular HTML becomes print statements with double quotes around the text, JSP expressions become print statements with no double quote. JSP Scriptlets can perform a number of tasks that cannot be accomplished with expressions alone. These tasks include setting response headers and status codes, invoking side effects such as writing to the server log or updating a database, or executing code that contains loops, conditionals, or other complex constructs. It is easy to understand how JSP scriptlets correspond to servlet code: the Scriptlet code is just directly inserted into the _jspService method: no strings, no print statements, no changes whatsoever.
Controlling the Structure of generated servlets: The JSP page directive: JSP directives provide directions and instructions to the container, telling it how to handle certain aspects of JSP processing. A JSP directive affects the overall structure of the servlet class. It usually has the following form: Syntax:
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. To obtain quotation marks within an attribute value, precede them with a backslash, using \’ for ’ and \" for ". In JSP, there are three main types of directives:
i. <%@ page . . . %>
ii. <%@ include . . . %> iii. <%@ taglib . . . %> i.
Let’s you control the structure of the servlet by importing classes, customizing the servlet superclass, setting the content type, and the like. Let’s you insert a file into the JSP page at the time the JSP file is translated into a servlet. defines custom markup tags.
The “page” attribute: The page directive is used to provide instructions to the container that pertain to the current JSP page. The page directive can define one or more of the following attributes and all are case-sensitive: By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2 Sl. No. i.
JSP
Attributes import
Description is used to define a set of class, interface or all the members of a package that must be imported in servlet class definition Syntax: <%@ page import = "package.class" %> <%@ page import = "package.class1,......., package.classN" %> Note: By default, the servlet imports following packages : java.lang.*; javax.servlet.*; javax.servlet.jsp.*; javax.servlet.http.*;
For example: Refer Example-a ii.
contentType
Defines the MIME (Multipurpose Internet Mail Extension) type of the HTTP response. Syntax: <%@ page contentType = “MIME Type" %> <%@ page contentType = “MIME Type” charset = “Character - Set” %> Note: By default value is "text/html; charset=ISO-8859-1". For example: Refer Example-b
iii.
pageEncoding is used to change the character set. Syntax: <%@ page pageEncoding=" ISO-8859-1" %> You can change this by specifying US-ASCII, Shift-JIS and etc., For example: Refer Example-b
iv.
session
Specifies whether or not the JSP page participates in HTTP sessions Syntax: <%@ page session = “true" %> <%@ page session = “false” %>
By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP It can have two values: true or false. Default value is true: which means if you do not mention this attribute, server may assume that HTTP session is required for this page. For example: Refer Example-c
v.
isELIgnored
Specifies whether the JSP Expression Language (EL) is ignored (true) or evaluated normally (false). Syntax: <%@ page isELIgnored = “true" %> <%@ page isELIgnored = “false” %> //By default false means EL is enabled It can have two values: true or false. Default value is false: which means Expression Language is enabled by default. For example: Refer Example-d
vi.
buffer
specifies the buffer size in kilobytes used by the out variable, which is of type JspWriter. Syntax: <%@ page buffer = “size kb" %> <%@ page buffer = “none” %> Note: Default size is 8Kb Servers can use a larger buffer than you specify, but not a smaller one. For example: Refer Example-e
vii.
autoFlush
specifies whether the output buffer should be automatically flushed when it is full (the default) or whether an exception should be raised when the buffer overflows ( autoFlush="false"). Syntax: <%@ page autoFlush = “true" %> <%@ page autoFlush = “false” %>
By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2
JSP It can have two values: true or false Default value is true : which means automatically flushed when buffered is full For example: Refer Example-e A value of false is illegal when buffer="none" as shown below: <%@ page buffer=“none”
viii.
info
autoFlush=“false” %>
defines a string that can be retrieved from the servlet by means of the getServletInfo method. Syntax: <%@ page info = “some message" %> For example: Refer Example-f
ix.
errorPage
is used to define the error page, if exception occurs in the current page, it will be redirected to the another JSP Page by the runtime. Syntax: <%@ page errorPage = “RelativeURL” %> The exception thrown will automatically be available to the designated error page by means of the exception variable. For example: Refer Example-g
x.
iserrorPage
indicates whether or not the current page can act as the error page for another JSP page. Syntax: <%@ page isErrorPage = “true” %> <%@ page isErrorPage = “false” %> It can have two value: true or false Default is false: which means not an error page. For example: Refer Example-g
By Rama Satish K V, Dept. of MCA
1 | 46
Chapter 2 xi.
isThreadSafe
JSP Servlet and JSP both are multithreaded. You can control that using “isThreadSafe” atttribute. Syntax: <%@ page isThreadSafe = “true” %> <%@ page isThreadSafe = “false” %> The default value of isThreadSafe is true. If you make it false, the web container will serialize the multiple requests, i.e. it will wait until the JSP finishes responding to a request before passing another request to it. For Example: Refer Example-h
xii.
language
The “language’ attribute is intended to specify the scripting language being used. Syntax: <%@ page language = “java” %> Default is java. But its support C++, PHP and other Scripting language For Example: Refer Example-i
xiii.
extends
It specifies the superclass of the servlet that will be generated for the JSP page. Syntax: <%@ page extends= “package.class” %> For Example: Refer Example-i