JSP - Helmut Dispert

Werbung
Fachbereich Informatik und Elektrotechnik
JSP - Java Server Pages
JSP
Java Server Pages
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP - Java Server Pages
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.:
http://java.sun.com/products/jsp
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP - Java Server Pages
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.
JSP way: special Java tags in HTML.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP - Code Example
<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
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP - Code Example with Errors
<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
Programming in Java,  Helmut Dispert
Missing ";"
Fachbereich Informatik und Elektrotechnik
JSP - Code Example with Errors
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Java Server Pages
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
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Java Server Pages
Servlet
JSP
Java Code
HTML Page
out.println("HTML")
<% Java %>
HTML
Java
HTML
Java
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Java Server Pages
JSP
JSP
Compiler
Programming in Java,  Helmut Dispert
Servlet
Source
Java
Compiler
Class
File
Fachbereich Informatik und Elektrotechnik
Servlets / Java Server Pages
XML + HTML
JDBC
JDBC
Browser
Browser
JSP/Servlet
JSP/Servlet
EJB
EJB
Browser
Browser
X,D-HTML
XSL/XTL
XSL/XTL
XML
App
App
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP Engine
(HTML File)
Client
Response
Request
JSP Engine and
Web Server
(HTTP get or post)
Response
(Creates a Servlet from a
JSP file and executes the servlet)
Servlet
File
Response
Request
Java
Request
Programming in Java,  Helmut Dispert
Component
Fachbereich Informatik und Elektrotechnik
JSP Engine
User request
a JSP
Page
compiled
before?
No
Yes
Page
unchanged
?
Yes
Execute
Servlet
Programming in Java,  Helmut Dispert
No
Compile JSP
into Servlet
Fachbereich Informatik und Elektrotechnik
JSP Processing
• JSP Elements must first be processed by the
server
• JSP Page => Servlet
• Compile Servlet
• Execute Servlet
• Web server must have JSP Container
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP Translation/Processing
Hello.jsp
(2) READ
(1) GET / Hello.jsp
CLIENT
Server
(JSP)
HelloServlet.java
(3) GENERATE
(6) HTTP/1.0 200 OK
<html> ... </html>
(5) EXECUTE
HelloServlet.class
Programming in Java,  Helmut Dispert
(4) COMPILE
Fachbereich Informatik und Elektrotechnik
JSP versus Javascript
Javascript
Client side
Less secure
Browser dependent
Unstable
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP versus ASP
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
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP versus Servlets
Disadvantages of Servlets
Processing code & HTML code in same module
Changing look and feel requires servlet recompilation
Difficult to leverage web development tools
Generated HTML embedded into Servlet
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP versus Servlets
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
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP Architecture
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)
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Elements of a JavaServer Page
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
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Elements of a JavaServer Page
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
in the output of the page.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP Syntax HTML Comment
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 -->
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP Syntax Hidden Comment
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>
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP Directives
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
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Types of Directive Elements
<%@ 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.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP Syntax: Include Directive
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>
Include code here
File to include "date.jsp":
<%@page import ="java.util.*" %>
<% =(new java.util.Date()).toLocaleString() %>
Output : Current date and time is: Mar 5, 2010 4:56:50
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Page Directive - Attributes/Values
Attribute
Values
language
java
extends
package.class
import
package.* / package.class
session
true / false
buffer
none / 8kb / sizekb
autoflush
true / false
isThreadSafe
true / false
info
text
errorPage
pathToErrorPage
isErrorPage
true / false
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP Declaration
The definition of class-level variables and
methods
Syntax:
<%! Declaration %>
<%! String var1 = "hi";
int count = 0;
private void incrementCount() {
count++;
}
%>
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP Scriptlets
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);
%>
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP Expressions
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 %>
<% } %>
http://149.222.51.81:8180/home-tomcat/jsp/dispert/counter.jsp
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP Expressions
<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>
http://149.222.51.81:8180/home-tomcat/jsp/dispert/express.jsp
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP Expressions
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP Expressions
<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>
http://149.222.51.81:8180/home-tomcat/jsp/dispert/express.jsp?testParam=FH-Kiel
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP Expressions
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Scripting: Implicit JSP Objects
Scripting
Implicit JSP Objects
request
.http.HttpServletRequest
response
.http.HttpServletResponse
pageContext
.jsp.PageContext
session
.http.Session
application
.ServletContext
out
.jsp.JspWriter
config
.ServletConfig
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Session Example
<%@ 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
the session
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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>
http://149.222.51.81:8180/home-tomcat/jsp/dispert/ShowSession.jsp
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
XML
XML Syntax
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
XML Syntax
XML Syntax for Expressions:
<jsp: expression>
Java Expression
</jsp: expression>
XML Syntax for Scriptlets:
<jsp: scriptlet>
Code
</jsp: scriptlet>
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
XML Syntax
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:
<%@ page import="java.util.*" %>
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Applications
Starting Applications
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Generating Excel Sheets
<%@ page contentType="application/vnd.ms-excel" %>
<%-- tabs between columns! --%>
2003
2004
2005
2006
2007
10
20
30
40
50
Tab
http://149.222.51.81:8180/home-tomcat/jsp/dispert/Excel.jsp
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Generating Excel Sheets
<!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");
}
%>
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Generating Excel Sheets
<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
HTML table
<TR><TH>SAG<TD>953<TD>953
interpreted by Excel
<TR><TH>W<TD>1401<TD>1401
</TABLE>
</CENTER>
</BODY>
</HTML>
http://149.222.51.81:8180/home-tomcat/jsp/dispert/StdNumb.jsp
http://149.222.51.81:8180/home-tomcat/jsp/dispert/StdNumb.jsp?format=excel
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Generating Excel Sheets
HTML Page
http://149.222.57.15:8080/home-tomcat/jsp/dispert/StdNumb.jsp
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Generating Excel Sheets
Excel Sheet
http://149.222.57.15:8080/home-tomcat/jsp/dispert/StdNumb.jsp?format=excel
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
JSP - Java Server Pages
Taglibs
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Taglibs
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.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Taglibs
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.
Ref.:
http://jakarta.apache.org/taglibs/tutorial.html
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Tag Handler
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:
Tag
used for simple tag handlers not interested
in manipulating their body content
BodyTag
an extension of Tag and gives the handler
access to its body
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Tag Handler
The Tag Handler has two main action methods:
doStartTag()
Process the start tag of this action.
doEndTag()
Process the end tag of this action.
Called after returning from doStartTag.
release()
Release resources
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Tag interaction.
Container
1: setPageContext (javax.servlet.jsp.PageContext):void
2: setParent (javax.servlet.jsp.tagext.Tag):void
3: //setAttribute:void
4: doStartTag()):int
5: doEndTag()):int
6: release()):int
Programming in Java,  Helmut Dispert
Tag
Fachbereich Informatik und Elektrotechnik
Tag 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
executed at the end of the Tag usage should be called from the doEndTag()
method.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Example: Hello World
JSP file:
starts with taglib directive
<%@ taglib uri = "identifier"
Location of Tag Library
<%@ taglib uri = "/taglib.tld"
<html>
<body>
<nLIB: Helloworld />
</body>
</html>
Programming in Java,  Helmut Dispert
prefix = "prefix" %>
Distinguishes different
tag libraries
prefix = "nLIB" %>
Fachbereich Informatik und Elektrotechnik
Tag Library Descriptor
Hello World 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>
tag handler class
<shortname>nLIB</shortname>
<tag>
<name>Helloworld</name>
<tagclass>mytags.HelloWorld</tagclass>
<body context>empty</body context>
</tag>
</taglib>
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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");
}
return EVAL_PAGE;
continued
}
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Tag class file
continued
public void release (){}
public void setPageContext(pageContext p) {
pageContext=p;
}
public void setParent(Tag t) {
parent = t;
}
public void getParent() {
return parent;
}
}
Doku: interface Tag, class PageContext
http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/jsp/tagext/Tag.html
http://java.sun.com/j2ee/sdk_1.3/techdocs/api/javax/servlet/jsp/PageContext.html
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
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).
taglib-uri
<web-app>
<taglib>
<taglib-uri>
http://jakarta.apache.org/taglibs/utilitytags
</taglib-uri>
<taglib-location>
associated with
/WEB-INF/tld/utilitytags.tld
</taglib-location>
</taglib>
Tag Library Descriptor
</web-app>
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Usage
JSP directive to tell JSP container to use the URI
"/taglib.tld"
and the prefix
"nLIB"
<%@ taglib uri = "/taglib.tld"
Call JSP tag:
<nLIB:Helloworld />
Programming in Java,  Helmut Dispert
prefix = "nLIB" %>
Fachbereich Informatik und Elektrotechnik
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.
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Servlet - JSP
Comparison
Servlet - Java Server Pages
Programming in Java,  Helmut Dispert
Fachbereich Informatik und Elektrotechnik
Servlet or JSP?
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
Request
Servlet
URL
Browser
Response
Programming in Java,  Helmut Dispert
JSP
Herunterladen
Explore flashcards