Java Server Pages - PowerPoint PPT Presentation

1 / 57
About This Presentation
Title:

Java Server Pages

Description:

JSP comments are stripped out and do not appear in the generated HTML page ... errorPage - specifies JSP to invoke on uncaught exceptions ... – PowerPoint PPT presentation

Number of Views:101
Avg rating:3.0/5.0
Slides: 58
Provided by: JimSta1
Category:
Tags: java | pages | server | uncaught

less

Transcript and Presenter's Notes

Title: Java Server Pages


1
Java Server Pages
  • JSP

2
Topics
  • JSP Overview
  • JSP and Java Beans
  • Servlet Integration
  • JSP Scripting
  • Custom Tags
  • JSP and WARs/EARs

3
JSP Overview
  • Document-centric specification
  • similar to HTML
  • markup code embedded in the document
  • directives
  • actions
  • scripts
  • Java is the currently supported scripting
    language
  • Complementary to servlets

4
JSP Example
  • ltHTMLgt
  • ltHEADgtltTITLEgtJSP Examplelt/TITLEgt
  • lt_at_ page import"java.util.Date" gt
  • lt/HEADgt
  • lt-- Embed Date in generated output --gt
  • ltBODYgt
  • The Date is
  • lt new Date() gt
  • lt/BODYgt
  • lt/HTMLgt

5
JSP Components
  • JSP Tags
  • Comments
  • Scripting elements
  • Actions
  • Directives

6
JSP Comments
  • JSP comments are stripped out and do not appear
    in the generated HTML page
  • lt-- This is a JSP comment --gt
  • HTML comments are supported and do appear in the
    generated HTML page
  • lt!-- This is an HTML comment --gt

7
JSP Directives
  • Instructions for JSP Container
  • Processed when JSP page is converted to a servlet
  • Directives do not cause information to be written
    to JSPs output
  • Shorthand Form
  • lt_at_ page importjavax.naming. gt
  • XML Form
  • ltjspdirective.page importjavax.naming. /gt

8
JSP Page Directives
  • Page directive attributes
  • info - defines string returned from
    Servlet.getServletInfo()
  • language - only required language is java
  • contentType - defaults to text/htmlcharsetISO-8
    859-1
  • ltjspdirective.page contentTypetext/xml/gt
  • extends - specifies the base class of the
    generated servlet
  • generally not a good idea, limits the container
    implementation options
  • import - specifies classes to import for
    scriptlets/beans
  • ltjspdirective.page importpackage.Class/gt

9
JSP Page Directives (cont.)
  • Page directive attributes (Cont)
  • session - defines implicit HttpSession session
    variable
  • ltjspdirective.page sessiontrue/gt
  • buffer - specifies size of output buffer
  • autoFlush - flushes (true) buffer when
    fullthrows (false) exception
  • isThreadSafe - dispatches requests in single
    thread (false) or multiple threads (true).
    Default is true.
  • isErrorPage - defines implicit java.lang.Throwable
    exception variable
  • ltjspdirective.page errorPagetrue/gt
  • errorPage - specifies JSP to invoke on uncaught
    exceptions
  • ltjspdirective.page errorPage/ErrorPage.jsp/gt

10
JSP Include Directives
  • Static includes done at deployment
  • lt_at_ include filefileRelativeURL gt
  • ltjspdirective.include filefileRelativeURL /gt
  • Same as include is C/C
  • Imagine a page
  • ltjspdirective.include fileHeader.jsp /gt
  • lt jspdirective.include fileBody.jsp /gt
  • lt jspdirective.include fileFooter.jsp /gt
  • Another form may be done at runtimeltjspinclude
    pagepageRelativeURL/gt

11
JSP Declarations
  • Create variables (or methods) for later use in
    expressions or scriptlets
  • lt! String choice gt
  • ltjspdeclarationgt String choice
    lt/jspdeclaraiongt
  • Code is inserted in generated servlet outside of
    service() method.
  • Object-level scope
  • Example
  • ltjspdeclarationgt
  • int i0
  • void print() System.out.println(i)
  • ltjspdeclarationgt
  • ltjspscriptletgtprint()ltjspscriptletgt

12
Scriptlets
  • Code to be inserted directly in the generated
    servlet and executed when page is requested
  • i.e. inserted in service method
  • lt choice request.getParameter(Product) gt
  • ltjspscriptletgt
  • choicerequest.getParameter(Product)
  • lt/jspscriptletgt
  • Default scripting language is Java so all
    conditional statements, method invocations, etc.
    are supported

13
Expressions
  • Insert results from code execution directly onto
    the JSP Page
  • ltPgt
  • The Date is lt new Date() gt
  • lt/Pgt
  • ltPgt
  • The Date is ltjspexpressiongtnew
    Date()lt/jspexpressiongt
  • lt/Pgt
  • Automatically converts toString() and writes
    result

14
Implicit Objects
  • page
  • Pages servlet instance
  • config
  • ServletConfig (configuration data)
  • request
  • HttpServletRequest
  • response
  • HttpServletResponse

15
Implicit Objects (Cont)
  • out
  • Output Stream for content (JspWriter)
  • session
  • HttpSession
  • application
  • ServletContext
  • pageContext
  • Context Data for page execution (PageContext)
  • exception
  • Available on error pages (java.lang.Throwable)

16
Implicit Object Example
  • ltHTMLgt
  • ltBODYgt
  • lt String visitorrequest.getParameter(name)
  • if( visitornull) visitorUnknown gt
  • Hello, lt visitor gt
  • lt/BODYgt
  • lt/HTMLgt
  • http//localhost7001/jsp/implicit.jsp?nameDan
  • Remember Keep URLs shorter than 255 characters

17
JSP-Specific Tags
  • jspforward
  • Switch to another URL
  • jspinclude
  • Embed the contents of another URL in this page
  • jspuseBean, jspsetProperty, jspgetProperty
  • Embed and use JavaBeans in a JSP Page
  • jspplugin
  • downloads Java plugin to client

18
Risks
  • Embedding code in the HTML page is convenient,
    but .
  • We are mixing business logic with presentation
  • Use JSP for simple coding e.g. Date
  • Defer business logic to Beans and or Servlets

19
JSP and Java Beans
20
What is a Bean?
  • Java class that follows a set of implementation
    and naming guidelines
  • Typically named xxxBean
  • Public no argument constructor
  • Setters/Getters for attributes
  • Indexed properties
  • BeanInfo interface
  • Should implement java.io.Serializable
  • Event model, bound and constrained properties

21
HelloBean
packages corej2ee.examples.web.usebean public
class HelloBean implements java.io.Serializable
String name public HelloBean()
nameAnonymous public String getName()
return name public void setName(String
argName) nameargName
22
usebean.html
lthtmlgt ltheadgtlttitlegtTest of jsp use
beangtlt/titlegtlt/headgt ltbodygt lth1gtEnter
Namelt/h1gt ltform action"usebean.jsp"
method"POST"gt lttable border"0"
width"30" cellspacing"3" cellpadding"2"gt
lttrgtlttdgtltbgtUser Namelt/bgtlt/tdgt
lttdgtltinput type"text" size"20"
name"name"gtlt/tdgtlt/trgt
lttrgtlttdgtltpgtltinput type"submit"
value"Login"gtlt/tdgtlt/trgt lt/tablegt
lt/formgt lt/bodygt lt/htmlgt
23
Using Java Beans in JSP
  • ltjspuseBean id"hellobean" class"corej2ee.exampl
    es.web.usebean.HelloBean"/gt
  • ltjspsetProperty namehellobean property"name"
    param"name"/gt
  • ltHTMLgt
  • Hello, ltjspgetProperty name"hellobean"
    property"name"/gt
  • ltBODYgt
  • lt/BODYgt
  • lt/HTMLgt

24
Setting Bean Attributes
  • jspsetProperty tag
  • Can initialize bean properties from HttpRequest
  • ltjspsetProperty namehello propertyname
    paramname/gt
  • Param attribute (from form) is the equivalent of
  • request.getParameter(name)
  • Property attribute (from JavaBean) is equivalent
    of
  • hello.setName()
  • Shortcut to set all parameters in bean that match
    request parameter names
  • ltjspsetProperty namehello property/gt
  • Use value attribute to set the property to a
    specific value
  • propertyname valuehard-coded-value

25
Bean Scope
  • Bean lifetime defaults to the execution of the
    page that contains the useBean tag
  • scope
  • page - defined in jsp.PageContext
  • request - defined in Servlet.service()s
    request object
  • (jspforward, jspinclude)
  • session - defined in users session object
  • application - defined in Servlets Context
  • Interesting servlet/jsp communication mechanism

26
Benefits and Limitations
  • Benefits
  • Separates business logic from HTML content
  • Easier maintenance
  • Component Re-usability
  • Can be configured with commercial tools
  • Limitations
  • Java Bean event model not supported

27
JSP Summary
  • Allows HTML authors to be HTML authors and not
    Java programmers
  • While Java code can be embedded in the .jsp page
    this should be kept to a minimum
  • Use JavaBeans for model data and tags as the
    interface between the html page and the model
  • Avoid HTML output from Beans
  • Custom Tags are useful for generating HTML

28
JSP Custom Tags
29
JSP Tags Overview
  • Capability to define your own jsp tags in a
    portable manner
  • Required components
  • Tag Handler class
  • Implements tag behavior
  • Tag Library Descriptor File
  • Define class to server and associate it with an
    XML tag name
  • XML document

30
Tag Handler
  • Must implement the javax.servlet.jsp.tagext.Tag
    interface
  • doStartTag() and doEndTag() are key methods
  • Frequently extend TagSupport

31
(No Transcript)
32
Handler Example (DebugTag.java)
  • package corej2ee.examples.web.tag
  • import javax.servlet.jsp.
  • import javax.servlet.jsp.tagext.
  • import java.io.
  • import javax.servlet.
  • / A tag that includes the body content only if
  • the "debug" request parameter is set.
  • ltPgt
  • Taken from Core Servlets and JavaServer Pages
  • from Prentice Hall and Sun Microsystems
    Press,
  • http//www.coreservlets.com/.
  • copy 2000 Marty Hall may be freely used or
    adapted.
  • /
  • public class DebugTag extends TagSupport
  • public int doStartTag()
  • ServletRequest request pageContext.getReques
    t()
  • String debugFlag request.getParameter("debug
    ")
  • if ((debugFlag ! null)
  • (!debugFlag.equalsIgnoreCase("false")))
  • return(EVAL_BODY_INCLUDE)
  • else
  • return(SKIP_BODY)

33
TagLib Descriptor FileWEB-INF/csajsp-taglib.tld
lt?xml version"1.0" encoding"ISO-8859-1"
?gt lt!DOCTYPE taglib PUBLIC "-//Sun Microsystems,
Inc.//DTD JSP Tag Library 1.1//EN"
"http//java.sun.com/j2ee/dtds/web-jsptaglibrary_1
_1.dtd"gt lttaglibgt lttlibversiongt1.0lt/tlibversion
gt ltjspversiongt1.1lt/jspversiongt
ltshortnamegtcsajsplt/shortnamegt lturigtlt/urigt
34
WEB-INF/csajsp-taglib.tld (Cont)
  • ltinfogt
  • A tag library from Core Servlets and
    JavaServer Pages,
  • http//www.coreservlets.com/.
  • lt/infogt
  • lttaggt
  • ltnamegtdebuglt/namegt
  • lttagclassgtcorej2ee.examples.web.tag.DebugTaglt/
    tagclassgt
  • ltbodycontentgtJSPlt/bodycontentgt
  • ltinfogtIncludes body only if debug param is
    set.lt/infogt
  • lt/taggt
  • lt/taglibgt

35
web.xml entry
lt?xml version"1.0" ?gt lt!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application
2.3//EN " "http//java.sun.com/j2ee/dtds/web-app_2
_2.dtd"gt ltweb-appgt lttaglibgt
lttaglib-urigtcsajsp-taglib.tldlt/taglib-urigt
lttaglib-locationgtWEB-INF/csajsp-taglib.tldlt/taglib
-locationgt lt/taglibgt lt/web-appgt
36
DebugExample.jsp
  • lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
    Transitional//EN"gt
  • lt!--
  • Illustration of SimplePrimeTag tag.
  • Taken from Core Servlets and JavaServer Pages
  • from Prentice Hall and Sun Microsystems Press,
  • http//www.coreservlets.com/.
  • copy 2000 Marty Hall may be freely used or
    adapted.
  • --gt
  • ltHTMLgt
  • ltHEADgt
  • ltTITLEgtUsing the Debug Taglt/TITLEgt
  • ltLINK RELSTYLESHEET
  • HREF"JSP-Styles.css"
  • TYPE"text/css"gt
  • lt/HEADgt
  • ltBODYgt
  • ltH1gtUsing the Debug Taglt/H1gt
  • lt_at_ taglib uri"csajsp-taglib.tld"
    prefix"csajsp" gt
  • Top of regular page. Blah, blah, blah. Yadda,
    yadda, yadda.
  • ltPgt
  • ltcsajspdebuggt
  • ltBgtDebuglt/Bgt
  • ltULgt
  • ltLIgtCurrent time lt new java.util.Date() gt
  • ltLIgtRequesting hostname lt request.getRemoteHo
    st() gt
  • ltLIgtSession ID lt session.getId() gt
  • lt/ULgt
  • lt/csajspdebuggt
  • ltPgt
  • Bottom of regular page. Blah, blah, blah. Yadda,
    yadda, yadda.
  • lt/BODYgtlt/HTMLgt

37
Invoking debug.jsp
38
Invoking debug.jsp with Debug
39
Tag Complexity
  • Tags can become very complicated
  • Can parse body themselves
  • Can become nested in other tags
  • Ex. IF/THEN/ELSE
  • Looping constructs
  • While beans are generally used for model data and
    shared information, tags are typically confined
    to a single page

40
Tag Summary
  • Tags are a portable extension mechanism for jsp
  • Can build a library of components
  • Ex. XSLT renderer of XML data
  • Bridge to JavaBean model data
  • Ex. Setting indexed properties
  • Further eliminates the need for HTML authors to
    learn Java

41
JSTL and Expression Language
  • Optional Topic

42
JSP Standard Tag Library
  • Encapsulates core functionality for many web
    applications in custom tags
  • http//java.sun.com/products/jsp/jstl
  • Requires JSP 1.2
  • Custom tags
  • Iteration, Control, Internationalization,
    Database Access
  • Expression language to simplify page development

43
JSTL Libraries
  • Core
  • XML Processing
  • I18N
  • Database Access

44
Expression Language
  • Simpler syntax for accessing Java Bean properties
  • Similar to JavaScript
  • customerBean.name
  • customerBeanname
  • customerBean is in one of the JSPs scopes
  • page, request, session, or application
  • Implicit variables also available
  • param collection of all request parameters
  • cookie collection of all cookies
  • header collection of all request headers

45
Basic Example (e1.jsp)
  • lt_at_ taglib uri"myTLD" prefix"c" gt
  • lthtmlgt
  • ltheadgt
  • lttitlegtJSTL Basic EL Supportlt/titlegt
  • lt/headgt
  • ltbody bgcolor"FFFFFF"gt

46
lth1gtBasic EL exampleslt/h1gt cookie.JSESSIONID.val
ue ltcout value"cookie.JSESSIONID.value"
/gt ltBRgt param'name' ltcout
value"param'name'" /gt ltBRgt header'User-Ag
ent' ltcout value"header'User-Agent'"
/gt ltBRgt lt/bodygt lt/htmlgt
47
(No Transcript)
48
Iteration Example (IterateSetup.jsp)
lt_at_ page import"corej2ee.examples.web.jspstl.,
java.util.List,
java.util.ArrayList" gt lt STLPerson
personnew STLPerson() person.setName("Dan")
person.setStreet("Poplar Ridge")
person.setZip("21122")
49
STLPerson person2new STLPerson()
person2.setName("Jim") person2.setStreet("Seve
rna Park") person2.setZip("21046") List
peopleListnew ArrayList() peopleList.add(pers
on) peopleList.add(person2)
request.setAttribute("people", peopleList) gt ltjs
pinclude page"Iterate.jsp" /gt
50
Iterate.jsp
lt_at_ taglib uri"myTLD" prefix"c"
gt lthtmlgt ltheadgt lttitlegtJSTL Iteration
Examplelt/titlegt lt/headgt ltbody bgcolor"FFFFFF"gt lt
h3gtSimple Iterationlt/h3gt lth4gtPeople listlt/h4gt
51
ltTABLE BORDER"1"gt ltTRgtltTDgtNamelt/TDgtltTDgtStreetlt/
TDgtltTDgtZiplt/TDgtlt/TRgt ltcforEach var"person"
items"people" gt ltTRgt ltTDgtltcout
value"person.name" /gtlt/TDgt ltTDgtltcout
value"person.street" /gtlt/TDgt ltTDgtltcout
value"person.zip" /gtlt/TDgt
lt/TRgt lt/cforEachgt lt/TABLEgt lt/bodygt lt/htmlgt
52
(No Transcript)
53
JSP and J2EE
54
JSP and WARs
  • JSPs can be treated like a static resource and
    grouped with html and image files in the WAR
  • JSPs can also be configured like servlets in the
    WAR file to
  • Map to a URL
  • Receive initialization parameters, etc.
  • ltservletgt     ltservlet-namegtmyFoolt/servlet-na
    megt     ltjsp-filegtmyJSPfile.jsplt/jsp-filegtlt/serv
    letgt
  • ltservlet-mappinggt     ltservlet-namegtmyFoolt/
    servlet-namegt     lturl-patterngt/mainlt/url-pattern
    gtlt/servlet-mappinggt

55
Web Architectures
56
Session EJB
Action/ Worker Servlet
Java Bean
Controller Servlet
HTTP
Entity Beans
DAO
View JSP
Custom Tags
Database
57
JSP Summary
  • Page-centric technology for dynamic web pages
  • Avoid Java code in JSP pages
  • Use Java Beans
  • Custom Tags
  • STL
  • For mid-large sites use MVC architecture
  • Servlets for getting work done
  • JSP for page templates
Write a Comment
User Comments (0)
About PowerShow.com