JSP - Java Server Pages
JSP
Characteristics:
A way to create dynamic web pages,
Server side processing,
Based on Java Technology,
Large library base
Platform independence
Separates the graphical design from the
dynamic content.
Ref.:
Basic idea:
Separating Graphical Design and Dynamic Content
Similar approaches:
PHP, SSI, ASP
Graphical Design and System Design are two
separate and distinct specialities:
Different languages (HTML/XHTML vs. Java),
Different goals, and
Different Training.
Should be separated for optimal project
management.
<html>
<body>
<b>Hello World HTML!</b><br><br>
<% out.println("Hello World Java"); %>
</body>
</html>
http://149.222.51.81:8180/home-tomcat/jsp/dispert/hello.jsp
<html>
<body>
<b>Hello World HTML!</b><br><br>
<% out.println("Hello World Java") %>
</body>
</html>
http://http://149.222.51.81:8180/home-tomcat/jsp/dispert/helloError.jsp Missing ";"
JSP technology is essentially a language
specification
Used to mix code into text content
Typically HTML or XML
Special syntax embedded into pages
compile Directive blocks
code block
Code snippets that generate into strings
Compile into a servlet
Java Code
out.println("HTML")
HTML
HTML
Servlet
HTML Page
<% Java %>
Java
Java
JSP
JSP Compiler
Servlet
Source
Class
File
Java CompilerJSP
Browser
Browser
Browser
Browser
App
JSP/Servlet
JSP/Servlet
JDBC
JDBC
EJB
EJB
XML + HTML X,D-HTML XMLXSL/XTL
XSL/XTL
Servlets / Java Server Pages
Client Response
Request JSP Engine and
Web Server
(Creates a Servlet from a
JSP file and executes the servlet) (HTTP get or post) (HTML File) Response Request Servlet File Response Request Java Component
JSP Engine
User request a JSP Execute Servlet Page unchanged ? Page compiled before? Compile JSP into Servlet Yes Yes No No
JSP Engine
• JSP Elements must first be processed by the
server
• JSP Page => Servlet
• Compile Servlet
• Execute Servlet
• Web server must have JSP Container
Server
(JSP)
(1) GET / Hello.jspHello.jsp
HelloServlet.java
HelloServlet.class
(2) READ (3) GENERATE (4) COMPILE (5) EXECUTE (6) HTTP/1.0 200 OK <html> ... </html>CLIENT
JSP Translation/Processing
Javascript
Client side
Less secure
Browser dependent
Unstable
JSP versus Javascript
Active Server Pages (ASP, Microsoft)
Many similarities
Server side dynamic web page generator
Separate programming logic from page design
Similar syntax <% %>
Proprietary Product
Limited platform
Disadvantages of Servlets
Processing code & HTML code in same module
Changing look and feel requires servlet
re-compilation
Difficult to leverage web development tools
Generated HTML embedded into Servlet
Similarities between JSP and Servlets
Identical results to the end user
JSP is an additional module to the Servlet Engine
Differences
Servlets
“HTML in Java code”:
HTML code inaccessible to Graphics Designer,
Everything is accessible to Programmer
JSP
“Java Code Scriptlets in HTML”:
HTML code very accessible to Graphics Designer,
Java code very accessible to Programmer
JSP is a simple text file consisting of HTML or
XML content along with JSP elements
JSP packages define the interface for the
compiled JSP page
JSPPage
HttpJspPage
Three main methods
jspInit()
jspDestroy()
jspService(HttpServletRequest request,
HttpServletResponse response)
JSP Elements
“Template Text” - HTML
When request is processed
template text & dynamic content merged
result sent as response to browser
JSP Elements
Directive
Action
Scripting
Directives
provide global information to the page
Action
perform action based on up-to-date information
Scripting
Declarative:
for page-wide variable and method declaration
Scriptlets:
the Java code embedded in the page
Expressions:
Format the expression as a string for inclusion
Comment can be viewed in the HTML source file
<!-- comment <% expression%> -->
Example:
<!-- this is just Html comment -->
<!-- This page was loaded on <%= (new java.util.Date
()).toLocaleString()%> -->
View source:
<!-- this is just Html comment -->
<!-- This page was loaded on January 10, 2006 -->
Comment cannot be viewed in the HTML source
file
<% -- expression -- %>
Example:
<html>
<body>
<h2>A Test of Comments</h2>
<%--This comment will be invisible in page source --%>
</body>
</html>
A JSP directive is a statement that gives the
JSP engine information for the page.
Syntax:
- <%@ directive {attribute= “value” } %>
For example
- scripting language used
- session tracking required
- name of page for error reporting
<%@ page ... %>
Define page-dependent attributes, such as
scripting language, error page & buffering
requirements.
<%@ include ... %>
Include a file during the translation phase.
<%@ taglib ... %>
Declares a tag library, containing custom
actions (markup tags), used in the page.
Includes a static file
<%@ include file="relativeURL" %>
Example:
JSP-File "main.jsp":
<html><body>
Current date and time is:
<%@include file="date.jsp" %> </body></html>
File to include "date.jsp":
<%@page import ="java.util.*" %>
<% =(new java.util.Date()).toLocaleString() %>
JSP Syntax: Include Directive
Values
Attribute
true / false
isThreadSafe
text
info
pathToErrorPage
errorPage
true / false
autoflush
none / 8kb / sizekb
buffer
true / false
session
package.* / package.class
import
package.class
extends
java
language
The definition of class-level variables and
methods
Syntax:
<%! Declaration %>
<%! String var1 = "hi";
int count = 0;
private void incrementCount() {
count++;
}
Scriptlets definition:
any block of valid Java code that resides between
<% and %> tags.
This code will be placed into the generated
servlet_jspService()
method.
<%
String var1 = request.getParameter("lname");
out.println(var1);
%>
JSP expression:
used to embed values directly within HTML code.
Syntax:
<%= expression %>
Example:
<% for (int i=0; i<10; i++) { %>
<BR>
Counter value is
<%= i %>
<% } %>
<HTML>
<HEAD><TITLE>JSP Expressions</TITLE></HEAD> <BODY>
<H2>JSP Expressions</H2> <UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Your hostname: <%= request.getRemoteHost() %>
<LI>Your session ID: <%= session.getId() %>
<LI>The <CODE>testParam</CODE> form parameter:
<%= request.getParameter("testParam") %>
</UL> </BODY> </HTML>
<HTML>
<HEAD><TITLE>JSP Expressions</TITLE></HEAD> <BODY>
<H2>JSP Expressions</H2> <UL>
<LI>Current time: <%= new java.util.Date() %>
<LI>Your hostname: <%= request.getRemoteHost() %>
<LI>Your session ID: <%= session.getId() %>
<LI>The <CODE>testParam</CODE> form parameter:
<%= request.getParameter("testParam") %>
</UL> </BODY> </HTML>
Implicit JSP Objects
Scripting
.ServletConfig
config
.jsp.JspWriter
out
.ServletContext
application
.http.Session
session
.jsp.PageContext
pageContext
.http.HttpServletResponse
response
.http.HttpServletRequest
request
<%@ page errorPage="errorpage.jsp" %>
<html> <head>
<title>UseSession</title>
</head>
<body>
<%
// Try and get the current count from the session
Integer count =
(Integer)session.getAttribute("COUNT");
// If COUNT is not found, create it and add it to
Session Example
if ( count == null ) {
count = new Integer(1);
session.setAttribute("COUNT", count);
}
else {
count = new Integer(count.intValue() + 1);
session.setAttribute("COUNT", count);
}
// Get the User's Name from the request
out.println("<b>Hello you have visited this site:
"
+ count + " times.</b>");
%>
</body> </html>
Session Example
XML
XML Syntax for Expressions:
<jsp: expression>
Java Expression
</jsp: expression>
XML Syntax for Scriptlets:
<jsp: scriptlet>
Code
</jsp: scriptlet>
XML Syntax for Declarations:
<jsp: declaration>
Code
</jsp: declaration>
XML Syntax for Directives:
<jsp: directive.directiveType attribute="value" /> example:
<jsp: directive.page import="java.util.*" /> equivalent of:
Applications
<%@ page contentType="application/vnd.ms-excel" %> <%-- tabs between columns! --%>
2003 2004 2005 2006 2007
10 20 30 40 50
Tab
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD> <TITLE>Student Numbers</TITLE> </HEAD> <BODY> <H3>Student Numbers</H3> <%
String format = request.getParameter("format");
if ((format != null) && (format.equals("excel"))) { response.setContentType("application/vnd.ms-excel"); }
<TABLE BORDER=1> <TR><TH></TH><TH>SS2007<TH>WS2007/08 <TR><TH>Mult<TD>108<TD>108 <TR><TH>L<TD>272<TD>272 <TR><TH>IuE<TD>668<TD>668 <TR><TH>M<TD>745<TD>745 <TR><TH>B<TD>935<TD>935 <TR><TH>SAG<TD>953<TD>953 <TR><TH>W<TD>1401<TD>1401 </TABLE> </CENTER> </BODY> </HTML>
HTML table
interpreted by Excel
HTML Page
Generating Excel Sheets
Excel Sheet
Generating Excel Sheets
JSP - Java Server Pages
Unique feature of JSP:
Tag Libraries - Taglibs
custom defined JSP tags.
used to componentize presentation level logic.
similar to Java beans.
Basic idea:
Every tag is mapped to a particular class file which is executed
whenever the tag is encountered in a JSP file.
General syntax :
<%@ taglib uri = " --- " prefix = " --- " %>
JSP-tags can be nested within other tags.
Steps to create and use TAGLIBs :
1.
create the class file which should implement the
Tag
and
BodyTag
interfaces
2.
deploy the class file in the Servlet folder of the web server.
3.
mapping of a tag to a particular class is done through the
use of the file "
taglib.tld
".
The taglib file represents an XML document that defines
the tag operation.
4.
Tag library is made available to the JSP page using the
taglib
directive.
Tag Handler
The Tag Handler is responsible for the interaction between
the JSP page and additional server-side objects. The handler
is invoked during the execution of a JSP page when a
custom tag is encountered.
Two interfaces describe a tag handler:
an extension of
Tag
and gives the handler
access to its body
BodyTag
used for simple tag handlers not interested
in manipulating their body content
Tag
The Tag Handler has two main action methods:
Process the end tag of this action.
Called after returning from doStartTag.
doEndTag()
Release resources
release()
Process the start tag of this action.
doStartTag()
Tag interaction.
Tag
1: setPageContext (javax.servlet.jsp.PageContext):voidContainer
2: setParent (javax.servlet.jsp.tagext.Tag):void 3: //setAttribute:void 4: doStartTag()):int 5: doEndTag()):int 6: release()):intTag interaction.
Container function after page is parsed and a tag is encountered:
1. Use the setPageContext() method of the Tag to set the current PageContext for it to use.
2. Use the setParent() method to set any parent of the encountered Tag (or null if none).
3. Set any attributes defined to be given to the Tag.
4. Call the doStartTag() method. This method can either return
EVAL_BODY_INCLUDE or SKIP_BODY. If EVAL_BODY_INCLUDE is returned, the Tags body will be evaluated. If SKIP_BODY is returned, the Container will not evaluate the body of the Tag.
5. Call the doEndTag() method. This method can either return EVAL_PAGE or SKIP_PAGE. IF EVAL_PAGE is returned, the Container will continue to evaluate the JSP page when done with this Tag. If SKIP_PAGE is returned, the Container will stop evaluating the page when it's done with this Tag.
6. Call the release() method. This method can be used by the Tag developer to release any resources that the Tag was using. Please notice that it is up to the Container to call the release() method when seemed fit, so you can't rely on this method being called at any specific time. In theory, this method could be called 12 days after the Tag was used. For this reason, any code that must be
JSP file:
starts with
taglib
directive
<%@ taglib uri = "/taglib.tld"
prefix = "nLIB" %>
<html>
<body>
<nLIB: Helloworld />
</body>
</html>
<%@ taglib uri = "identifier"
prefix = "prefix" %>
Location of Tag Library
Distinguishes different tag libraries
Tag Library Descriptor
<?xml version=”1.0” encoding=”ISO-8859-1” ?>
<!DOCTYPE taglib
PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglib_1_1.dtd"> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>nLIB</shortname> <tag> <name>Helloworld</name> <tagclass>mytags.HelloWorld</tagclass> <body context>empty</body context>
Hello World Tag Library Descriptor
Tag class file
HelloWorld.class
package mytags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagtext.*;
public class HelloWorld implements Tag {
private PageContext pagecontext; private Tag parent;
public int doStartTag() throws JSPException { return SKIP_BODY;
}
public int doEndTag() throws JSPException { try{
pageContext.getOut().write("Hello World");
} catch(java.io.Exception ex) {
throw new JSPException("IO Exception"); }
Tag class file
public void release (){}
public void setPageContext(pageContext p) { pageContext=p;
}
public void setParent(Tag t) { parent = t;
}
public void getParent() { return parent;
} }
Tag XML file
file "web.xml" (example)
describes the mapping between the taglib uri and the location of the Tag Library Descriptor (maps action tags to tag handler
classes). <web-app> <taglib> <taglib-uri> http://jakarta.apache.org/taglibs/utilitytags </taglib-uri> <taglib-location> /WEB-INF/tld/utilitytags.tld </taglib-location> </taglib> taglib-uri associated with
JSP directive to tell JSP container to use the URI
"/taglib.tld"
and the prefix
"nLIB"
<%@ taglib uri = "/taglib.tld"
prefix = "nLIB" %>
Call JSP tag:
<nLIB:Helloworld />
JSTL
JavaServer Pages Standard Tag Library
The JavaServer Pages Standard Tag Library (JSTL)
encapsulates as simple tags the core functionality
common to many Web applications.
JSTL has support for common, structural tasks such as
iteration and conditionals, tags for manipulating XML
documents, internationalization tags, and SQL tags. It
also provides a framework for integrating existing custom
tags with JSTL tags.
Servlet - JSP
Comparison
For complex pages, use a combination of both
Servlet: get request, validate and process
forward() to JSP to generate response dynamically
pass information as request attributes
Browser