JSP - IT

advertisement
Faculty of Information
Technology
31242/32549
Advanced Internet Programming
Java Server Pages (JSP)
V5
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-1
Topics
Faculty of Information
Technology
• JSP architecture
• JSP syntax
•
•
•
•
•
•
•
•
•
objects
directives
scripting elements
standard actions
expression language
JSP and JavaBeans
Tag libraries
JSP deployment
Model 1 and Model 2 JSP architectures
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-3
J2EE & JSP
© Copyright UTS Faculty of Information Technology 2008 – JSP
Faculty of Information
Technology
JSP-4
JSP architecture
HTTP
Faculty of Information
Technology
Web Server
JVM
Compile +
Execute JSP
JDBC
HTML
+ JSP
file
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-5
JSP architecture
Faculty of Information
Technology
• Advantages:
– all the advantages of servlets
• efficient, robust, secure, access to Java libraries
– uses "page-centric" coding
• HTML that contains embedded code
• Disadvantages:
– minor performance issue first time a JSP is loaded
• has to be compiled on-the-fly
• only affects very first request to a JSP
• after first request, compiled code is cached for faster execution
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-6
Topics
Faculty of Information
Technology
• JSP architecture
•  JSP syntax
•
•
•
•
•
•
•
•
•
objects
directives
scripting elements
standard actions
execution
JSP and JavaBeans
Tag libraries
JSP deployment
Model 1 and Model 2 JSP architectures
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-7
Not JSP syntax
Faculty of Information
Technology
• JSP is an embedded language like ASP, PHP
<P>This is my ASP Hello World program. So
<%
FirstName = Request.Form("FIRSTNAME")
Response.Write "hi " & FirstName & vbCrLf
%>
</P>
<P>This is my PHP Hello World program. So
<?php
$firstname = $HTTP_POST_VARS['FIRSTNAME'];
echo "hi " . $firstname . "\n";
?>
</P>
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-8
JSP syntax
Faculty of Information
Technology
<P>This is my JSP Hello World program. So
<%
String firstName = request.getParameter("FIRSTNAME");
out.println("hi " + firstName);
%>
</P>
• Java code is enclosed by <% ... %>
• Outside those tags, it is normal HTML
• e.g.:
http://127.0.0.1:7001/MyApp/hw.jsp?FIRSTNAME=Wayne
This is my JSP Hello World program. So hi Wayne
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-9
JSP Objects
Faculty of Information
Technology
• You can access Java objects from within JSP’s
• Main types of objects
– Implicit objects (provided by the container)
– Application-specific objects
• Local, instance & class variables
• JavaBeans
• EJBs
• Web container provides a context to provide scope
of object
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-10
JSP implicit objects
Faculty of Information
Technology
Variable
name
Type
Used for
request
javax.servlet.http.HttpServletRequest
Represents user's
request
response
javax.servlet.http.HttpServletResponse
Represents user's
response
pageContext javax.servlet.jsp.PageContext
Contains attributes of
this page
session
javax.servlet.http.HttpSession
Represents user's
session
application
javax.servlet.ServletContext
Contains attributes
for the entire
application
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-11
JSP implicit objects
Faculty of Information
Technology
Variable Type
name
Used for
out
javax.servlet.jsp.JspWriter
Output stream for the response
config
javax.servlet.ServletConfig
Contains initialization parameters
and the ServletContext
page
java.lang.Object
Current servlet object
exception
java.lang.Throwable
Only available for pages designated
as error pages
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-12
Kinds of embedded JSP code
Faculty of Information
Technology
1. Directives
2. Scripting Elements
• declarations
• scriptlets
• expressions
3. Actions
•
•
•
•
include
forward
useBean
get/setProperty
4. expression language (EL)
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-13
JSP Directives
Faculty of Information
Technology
<%@ directivename attribute=“value” attribute=“value” %>
• Note: <%@directive %> tags
• Directives are instructions to the JSP compiler
– e.g. "include", includes at compile-time, NOT run-time
• Main directives
– page
– include
– taglibs (later)
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-14
JSP Directives
Faculty of Information
Technology
• page Directive
<%@ page import=“java.util.*,java.io.*” %>
• include Directive [not at runtime!]
<%@ include file=“copyright.html” %>
<%@ page language="java"
import="java.util.*"
info="My wonderful JSP example" %>
<%@ include file="other_file.html">
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-15
Scripting Elements: Declarations
Faculty of Information
Technology
!
<% Java variable and method declarations %>
• Declarations executed when page is initialised
– used to define class-wide variables and methods
– declarations must produce no output
<%! int i = 0; %>
<%! int icubed = 0; %>
<%! public int cubed (int j) {
return (j * j * j);
}
%>
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-16
Scripting Elements: Scriptlets
Faculty of Information
Technology
• Basically any Java code can go in a scriptlet
• Executed during the request-processing time
<% Valid Java code statements %>
<%
try {
i = Integer.parseInt(request.getParameter("mynum"));
} catch (NumberFormatException nfe) {
out.println("Go back and enter a valid number.");
i = 0;
}
icubed = cubed(i);
%>
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-17
Scripting Elements: Expressions
Faculty of Information
Technology
= Java expression to be evaluated %>
<%
• Expressions are primarily for inserting values of
Java variables into HTML code without having to
type in full as a scriptlet:
– eg: <% out.print(i); %>
vs <%= i %>
No ;
<BODY>
<P>You entered the value <%= i %></P>
<P>That number cubed is <%= icubed %></P>
<P>I can say the same thing with <%= cubed(i) %></P>
</BODY>
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-18
Standard Actions
Faculty of Information
Technology
• Well-known tags that affect the runtime behaviour
• Generates the Java code that corresponds to the
required task - during conversion
<jsp:include page=“myjsp.jsp” flush=“true” />
• Other standard actions
–
–
–
–
<jsp:useBean>
<jsp:setProperty>
<jsp:getProperty>
etc.
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-19
Standard Actions
Faculty of Information
Technology
<jsp:forward page="MyOtherServlet" />
<jsp:include page="MyIncludedServlet" />
<jsp:param name=“var” value=“something”/>
<jsp:useBean id="myperson"
class="au.edu.uts.it.PersonBean"
scope="session" />
• Uses XML syntax.
• Actions are run-time behaviours
– "jsp:include" includes a page at run-time
– “jsp:param” adds parameters to the included page
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-20
Expression Language
Faculty of Information
Technology
${object}
• Expression Language ( EL) introduced with JSP 2.4
& J2EE 1.4
• It complements JSP Expressions with simpler
syntax.
Each ${object } would be same as <%= object %>
• Supports:
– JSP implicit objects
– JavaBeans
– simple calculations
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-21
Expression Language
Object
param
Faculty of Information
Technology
example
${param.newcol }
header
Description
Request params &
values
HTTP headers
cookie
Cookie names & value
${cookie[“id”] }
initParam
Init params in web.xml ${initParam.name }
${header.Host }
pageContext
Use this to get
${pageContext.request.
request, response,
remoteHost }
session
• Use pageContext to get servlet parameter. eg: the example
is same as <%= request.getRemoteHost() %>
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-22
EL operators
Faculty of Information
Technology
• EL also has some common programming operators
ie:
–
–
–
–
–
Math: + - * / div % mod
relational: == eq != ne < lt > gt <= le >= ge
negative: logical: && and || or ! not
empty: empty (used to test for null or “”)
• You can also access Java collections using array
syntax eg:
– ${myarray [1]}
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-23
JSP Execution
•
•
In practice, JSPs are converted into servlets for
execution
Conversion involves:
1.
2.
3.
4.
•
Faculty of Information
Technology
Container generates Java source code
Container invokes Java compiler
Class file is executed as with a normal servlet
A copy of the class file is kept (cached) to avoid
unnecessary recompilation in future
See for yourself!
– weblogic specific:
/home/chw/weblogic/AdminServer/tmp/_WL_user/_app
sdir_labs_war/fr8116/jsp_servlet/__jspfilename.java) !!!
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-24
Topics
Faculty of Information
Technology
• JSP architecture
• JSP syntax
•
•
•
•
•
•
•
•
•
objects
directives
scripting elements
standard actions
execution
 JSP and JavaBeans
Tag libraries
JSP deployment
Model 1 and Model 2 JSP architectures
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-25
Page View with Bean
Faculty of Information
Technology
• Refinement
Request
JSP
Java
utility
Bean
class
Business
Processing
Response
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-26
Using JavaBeans
Faculty of Information
Technology
• JavaBeans are a client-side component model
– not to be confused with Enterprise JavaBeans
• Allows you to encapsulate reusable functionality in
a "bean"
– a Bean is a normal Java class that follows some rules
– called "design patterns"
• One basic design pattern is for "properties"
– using a getter and/or a setter method
– more complex patterns too – see a JavaBeans tutorial
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-27
Using JavaBeans
Faculty of Information
Technology
public class Person {
private String yourname;
public String getName() {
return yourname;
}
public void setName (String yourname) {
this.yourname = yourname;
}
Person
+name
otherMethod()
public void otherMethod () {
// ...
}
}
• Note: method naming convention is important
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-28
Using JavaBeans
Faculty of Information
Technology
• Using beans
– <jsp:useBean id=“fred” class=“com.myapp.Person”
scope=“page” />
•  com.myapp.Person fred = new com.myapp.Person()
• Setting properties
– <jsp:setProperty name=“fred” property=“name”
value=“Fred Jones” />
•  fred.setName(“Fred Jones”)
• Getting properties
– <jsp:getProperty name=“fred” property=“name” />
•  fred.getName()
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-29
JSP Scopes
Faculty of Information
Technology
• JSP allows you to save data into a scope
• Scopes can be one of:
Scope
Where saved
page
request
Only for the current page, destroyed
when you leave the page.
kept while request is active.
session
saved in the current session. ***
application
saved for the whole application
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-30
EL and JavaBeans
Faculty of Information
Technology
• Expression Language also can access JavaBeans
• Instead of:
<jsp:useBean id="fred" class="com.myapp.Person" />
<jsp:getProperty name=“fred” property=“name” />
• [note: this invokes fred.getName() ]
• use:
${fred.name} instead
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-31
Topics
Faculty of Information
Technology
• JSP architecture
• JSP syntax
•
•
•
•
•
•
•
•
•
objects
directives
scripting elements
standard actions
execution
JSP and JavaBeans
 Tag libraries
JSP deployment
Model 1 and Model 2 JSP architectures
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-32
Tag libraries
Faculty of Information
Technology
• Create your own custom tags that can be used in
documents
– encapsulate reusable functionality
– simplify page coding
– Apache Jakarta project has large range of taglibs
http://jakarta.apache.org/taglibs
– J2EE 1.4 adopted some of these as the Java Standard
Tag Library (JSTL) http://java.sun.com/products/jsp/jstl
<%@ taglib uri=“/hello” prefix=“examples” />
<html>
<p>Hello message is:<examples:hello />
</html>
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-33
Tag libraries
•
Faculty of Information
Technology
Four things needed:
1. in JSP file:
<%@ taglib uri=“/hello” prefix=“examples” />
<html>
<p>Hello message is:<examples:hello />
</html>
2. Update web.xml with the taglib declaration
<web-app>
<taglib>
<taglib-uri>/hello</taglib-uri>
<taglib-location>/WEB-INF/hellotags.tld</taglib-location>
</taglib>
</web-app>
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-34
Tag libraries
•
Faculty of Information
Technology
Four things needed (continued):
3. Create a Tag Library Descriptor (TLD) file in WEB-INF
directory: (hellotags.tld)
<taglib>
<tag>
<name>hello</name>
<tagclass>HelloTag</tagclass>
</tag>
</taglib>
4. Create Java class that implements the tag handler
public class HelloTag extends TagSupport {
public int doStartTag() throws JspTagException { ... }
}
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-35
Topics
Faculty of Information
Technology
• JSP architecture
• JSP syntax
•
•
•
•
•
•
•
•
•
objects
directives
scripting elements
standard actions
execution
JSP and JavaBeans
Tag libraries
 JSP deployment
Model 1 and Model 2 JSP architectures
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-36
JSP deployment
Faculty of Information
Technology
• For a simple JSP, just include it in a WAR file, no
need to put anything in web.xml file
• If you want to call your JSP by a different name,
you can map it in web.xml, e.g.
<servlet>
<servlet-name>MyFirstJSP</servlet-name>
<jsp-file>foobar.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>MyFirstJSP</servlet-name>
<url-pattern>/foobar/*</url-pattern>
</servlet-mapping>
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-37
JSP deployment – tag libraries
Faculty of Information
Technology
• For tag libraries, need to specify in web.xml:
<web-app>
<taglib>
<taglib-uri>/hello</taglib-uri>
<taglib-location>/WEB-INF/tlds/hellotags.tld</tagliblocation>
</taglib>
</web-app>
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-38
WAR file directory structure
Faculty of Information
Technology
Same as servlets:
– Put JSP same place as html/gif etc, ie: top level directory or
subdirectory
– *NOT* in WEB-INF
Not same as servlets:
• WEB-INF/classes
– Java classes required to implement tag libs or supporting classes
• WEB-INF/lib
– JAR files containing additional classes for tag libs
• WEB-INF/tlds
– contains TLDs (not mandatory though) - conventional
– not tag handler classes
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-39
JSTL
Faculty of Information
Technology
• J2EE 1.4 provides Java Standard Tag Library (JSTL)
– <%@ taglib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core” %>
• Core tags:
–
–
–
–
–
–
<c:set> <c:remove> set/remove attributes from JSP
<c:catch>
catch Java errors!
<c:forEach>
equivalent of Java for loop
<c:forTokens>
iterate over tokens in string
<c:if>
equivalent to Java if but no else !
<c:choose><c:when> <c:otherwise>
equivalent to Java switch
– <c:out value=“${x}”> like ${x} but escapes XML chars
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-40
JSTL – more libraries
Faculty of Information
Technology
• More JSTL tag libraries:
just use @taglib with the following parameters:
Function
prefix
URL
http://java.sun.com/jsp/...
XML processing
x
xml
Internationalisation, fmt
formatting
fmt
SQL access
sql
sql
String, Collection
functions
fn
functions
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-41
JSTL example
• Scriptlet based
<ul>
<%
for (int i=0; i< arr.length; i++) {
String msg = arr[i];
%>
<li><%= msg %></li>
<% } %>
</ul>
Faculty of Information
Technology
• JSTL based
<ul>
<c:forEach var=“msg”
items=“${arr}”>
<li>${msg}<li>
</c:forEach>
• No java code needed!!
• This also works if arr[] was
a java collection!
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-42
Topics
Faculty of Information
Technology
• JSP architecture
• JSP syntax
•
•
•
•
•
•
•
•
•
objects
directives
scripting elements
standard actions
execution
JSP and JavaBeans
Tag libraries
JSP deployment
 Model 1 and Model 2 JSP architectures
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-43
Web application architectures
Faculty of Information
Technology
• In theory, you can use servlets and JSPs
interchangeably
• However current best practice is to design the web
part of your application according to a particular
architecture
– Model 1 architecture
– Model 2 architecture
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-44
JSP Model 1 Architecture
Faculty of Information
Technology
1
HTTP
JSP
4
Browser
2
JavaBeans
Client
Web Server
© Copyright UTS Faculty of Information Technology 2008 – JSP
3
Data Source(s)
JSP-45
JSP Model 1 Arch (cont'd)
Faculty of Information
Technology
1. Browser makes HTTP request to JSP
JSP performs control logic
2. JSP may make use of JavaBeans for accessing
either state information or database data
3. JavaBean may retrieve its data from an external
data source (optional)
4. JSP finishes execution and returns result to
browser
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-46
Limitations of Model 1
•
Faculty of Information
Technology
Model 1 applications have no structured way of
keeping track of "what to do next"
– JSPs can call each other in random patterns
•
Model 1 applications also have no separation
between "design" and "coding" functions
– typically these are performed by different people
•
•
Model 1 is okay for simple applications
For larger applications it becomes hard to keep
track of JSP interdependences
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-47
Model-View-Controller
Faculty of Information
Technology
• Model-View-Controller (MVC)
– a design pattern for building applications that interact
with a user (not web-specific, not Java-specific)
• Model
– code for internal representation of system state (data)
• View
– code for displaying information to user (GUI)
• Controller
– code for changing system state (logic)
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-48
JSP Model 2 Architecture
Faculty of Information
Technology
1
HTTP
6
Browser
Servlet
(Controller)
2
4
JavaBeans
JSP
5
(View)
Client
(Model)
Web Server
3
Data Source(s)
• Model 2 = MVC for web applications
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-49
JSP Model 2 Arch (cont'd)
Faculty of Information
Technology
1. Browser makes HTTP request to controller servlet
2. Controller servlet instantiates any JavaBeans that might be
needed for data displayed to user
3. JavaBean may retrieve external data (parallel to step 4)
4. Controller forwards request to appropriate JSP
JSP only contains presentation/view code
5. JSP accesses JavaBean data set up by controller
6. Execution finishes and result is returned to browser
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-50
Advantages of Model 2
•
•
Faculty of Information
Technology
Introducing a "controller" provides more structure
to the application
Also provides clearer separation of "design" and
"coding"
– web designers create JSPs without much coding
– programmers write the controller servlet without being
concerned by design issues
•
A large application may contain many controllers
– e.g. one for each use case / piece of functionality
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-51
Model 2 Architecture Summary
Faculty of Information
Technology
•
Building web applications using the Model 2
architecture is current best practice
•
We'll revisit Model 2 again when we consider EJBs
– EJBs change the picture, but only slightly
•
If you design a three-tier application using Model
2, migrating it to an N-tier application (with EJBs)
should involve minimal code changes
– changes only to the JavaBeans, in theory
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-52
Model 2 Implementations
•
•
•
Faculty of Information
Technology
The Struts framework http://struts.apache.org/ is a
common implementation of MVC architecture.
Consists of a controller servlet + config file + JSP taglib
You write View(JSP), Action and Model classes
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-53
Summary
Faculty of Information
Technology
• JSP has many similarities to servlets
• Again a fair amount of information to know about
– use the documentation as a reference
• Many ways to modularise and simplify coding
– include directive
– forward and include actions
– tag libraries, especially Apache Jakata & JSTL
• Tag libraries complex, but useful for big projects
• Model 2 is best practice application architecture
© Copyright UTS Faculty of Information Technology 2008 – JSP
JSP-54
Download