jsp - PowerPoint PPT Presentation

1 / 34
About This Presentation
Title:

jsp

Description:

Such markup is known as fixed-template data or fixed-template text. ... Some IDEs allow JSPs to be compiled in the environment, so you can see syntax error messages ... – PowerPoint PPT presentation

Number of Views:125
Avg rating:3.0/5.0
Slides: 35
Provided by: cyndi8
Category:
Tags: ides | jsp

less

Transcript and Presenter's Notes

Title: jsp


1
Chapter 10
  • jsp

2
Purpose
  • Simplifies the delivery of dynamic Web content,
    using predefined components and server-side
    scripting
  • javax.servlet.jsp, javax.servlet.jsp.tagext
    provide functionality

3
JSP
Template data static can be sent directly
to client
Elements dynamic interpreted by container
JSP normally includes XHTML or XML markup.  Such
markup is known as fixed-template data or
fixed-template text.  JSP is typically used when
most of the content sent to the client is
fixed-template data and only a small portion is
generated dynamically with Java code.  Servlets
are typically used when only a small portion of
the content is fixed-template data.  Some
servlets just perform a task for the client, then
invoke other servlets or JSPs to provide a
response. In most cases, servlet and JSP
technologies are interchangeable.  JSPs normally
execute as part of a Web server. The server (or
Tomcat) is the JSP container.
4
Dynamic JSP Components
  • actions encapsulate functionality in predefined
    tags. Can create Java objects for use in
    scriptlets (aka scripting elements).
  • scriptlets insert Java code into html.
    interacts with components in a JSP to process
    requests.
  • directives messages to the JSP container that
    enable the programmer to specify page settings,
    include content from other resources, specify
    custom tag libraries etc.
  • tag libraries tag extension mechanism that
    enables programmers to create custom tags.  These
    tags enable programmers to manipulate JSP
    content. 

5
JSP Lifecycle
browser
request
Translate to servlet
yes
First Time?
Tomcat
no
find in work directory
jsp service method ready for client
  • If there are any errors compiling the new
    servlet, they result in translation-time errors. 
  • Any errors during request processing are
    request-time errors.
  • Some JSP containers translate JSP at
    installation time, to eliminate overhead for
    first client.

6
Expressions
  • lt gt
  • Send a string of text to client
  • Object left as result of evaluation will have
    toString() called

7
clock.jsp uses expression for Date
  • lt?xml version "1.0"?gt
  • lt!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0
    Strict//EN"
  • "http//www.w3.org/TR/xhtml1/DTD/xhtml1-strict.
    dtd"gt
  • lthtml xmlns http//www.w3.org/1999/xhtmlgt
  • ltheadgt
  • ltmeta http-equiv "refresh" content "60"
    /gt
  • lttitlegtA Simple JSP Examplelt/titlegt
  • ltstyle type "text/css"gt
  • .big font-family helvetica, arial,
    sans-serif
  • font-weight bold
  • font-size 2em
  • lt/stylegt
  • lt/headgt
  • ltbodygt
  • ltp class "big"gtSimple JSP Examplelt/pgt
  • lttable style "border 6px outset"gt

8
Scripting
  • In some cases, the content of generated XHTML
    documents is static, but is output only if
    certain conditions are met (e.g., providing
    values in a form that submits a request). 
  • Scripting provides ability to use Java code, but
    no class declaration
  • Allows for loops, conditions
  • JSP currently supports scripting only with Java. 
    Future JSP versions may support other scripting
    languages.

9
Scripting Components
  • Scriptlets are blocks of code delimited by lt and
    gt.  They contain Java statements that the
    container places in method _jspService at
    translation time.
  • Scriptlets, expressions and fixed template data
    can be intermixed in a JSP to create different
    responses.
  • JSPs can be difficult to debug, because line
    numbers reported in JSP container refer to
    translated JSP servlet, not the original JSP line
    numbers.  Some IDEs allow JSPs to be compiled in
    the environment, so you can see syntax error
    messages
  • The Tomcat installation directory contains a
    subdirectory called work where you can find
    source code for the translated servlets.

10
Comments
  • JSP comments are delimited by lt-- and --gt.  Can
    be placed throughout a JSP, but not inside
    scriptlets.
  • XHTML comments are delimited with lt!-- and --gt. 
    Can be placed throught JSP, but not inside
    scriptlets. 
  • Scriptlets can use Java comments (delimited by //
    or /  and /).

11
Declarations
  • Declarations are delimited by lt! and gt
  • They enable a JSP programmer to define variables
    and methods.  Variables and methods are instance
    members of the servlet class that represents the
    translated JSP.  Declarations use Java syntax
    (e.g., must end in a semicolon).   lt! int
    counter 0 gt
  • Variables and methods in JSP declarations are
    initialized when JSP is initialized and are
    available in all scriptlets and expressions in
    the JSP. 
  • JSPs should not store client state information in
    instance variables.  Should use JSP implicit
    session object.
  • Not thread-safe unless programmer takes care of

12
Escape Sequences
  • Must use escape sequences for characters used as
    JSP delimiters. 
  • lt  -gt lt\
  • gt -gt \gt
  • ' -gt \'
  • " -gt \"
  • \ -gt \\

13
Implicit Objects
  • Because no method calls, have automatic objects
    available
  • response httpServletResponse
  • request - httpServletRequest
  • out response.getWriter
  • page this reference in servlet

14
clock2.jsp - script
  • lttablegt
  • lttrgt
  • lttd style "background-color black"gt
  • ltp class "big" style "color cyan
    font-size 3em
  • font-weight bold"gt
  • lt-- script to determine client
    locale and format date accordingly --gt
  • lt
  • // get client locale
  • java.util.Locale locale
    request.getLocale()
  • // get DateFormat for client's
    Locale
  • java.text.DateFormat dateFormat
  • java.text.DateFormat.getDateTime
    Instance(
  • java.text.DateFormat.LONG,
    java.text.DateFormat.LONG, locale )
  • gt lt-- end script --gt
  • lt-- output date --gt
  • lt dateFormat.format( new
    java.util.Date() ) gt
  • lt/pgt
  • lt/tdgt

15
welcome.jsp - scriptlet
  • ltbodygt
  • lt // begin scriptlet
  • String name request.getParameter(
    "firstName" )
  • if ( name ! null )
  • gt lt-- end scriptlet to insert fixed
    template data --gt
  • lth1gt
  • Hello lt name gt, ltbr /gt
  • Welcome to JavaServer Pages!
  • lt/h1gt
  • lt // continue scriptlet
  • // end if
  • else
  • gt lt-- end scriptlet to insert fixed
    template data --gt
  • ltform action "welcome.jsp" method
    "get"gt
  • ltpgt Type your first name and press
    Submitlt/pgt
  • ltpgtltinput type "text" name
    "firstName" /gt
  • ltinput type "submit" value
    "Submit" /gt
  • lt/pgt
  • lt/formgt

16
Exercise
  • Run jsp examples clock.jsp, clock2.jsp,
    welcome.jsp
  • Look at work directory, see servlets
  • Change clock.jsp to display another expression,
    possibly the result of a numeric calculation
  • Change clock2.jsp to have a different date format
  • Change welcome.jsp to accept a different field
    and display a different message

17
Standard Actions
  • Actions provide JSP implementors with access to
    common tasks performed in a JSP. 
  • Actions are delimited by ltjspactiongt and
    lt/jspactiongt where action is the standard action
    name.
  • Can use lt/action /gt if nothing appears between
    start/end tags.
  • ltjspincludegt - dynamically includes another
    resource in a JSP. 
  • ltjspforwardgt - forwards to JSP, servlet or
    static page.  Terminates current JSP's execution.
  • ltjspplugingt - Allows plug-in component to be
    added to a page in the form of a browser-specific
    object or embed HTML element.  Can be an applet,
    which enables downloading the Java Plug-in, if
    not already installed.
  • ltjspparamgt - Used with include, forward and
    plugin actions to specify additional name/value
    pairs of information.

18
Standard Actions, cont
  • ltjspuseBeangt - specifies that JSP use a JavaBean
    instance.  Specifies the scope of the bean and
    assigns it an ID that scripting components can
    use to manipulate the bean.
  • ltjspsetPropertygt - sets a property in the
    specified JavaBean.  Matches request parameters
    to bean properties of the same name.
  • ltjspgetPropertygt - gets a property in the
    specified JavaBean, converts the result to a
    string for output in the response.

19
Include Mechanism
  • JSP supports two include mechanisms
  • The include directive (covered later) copies the
    content into the JSP once, at translation time. 
  • ltjspincludegt enables dynamic content to be
    included.  If the included resource changes
    between requests, the next request includes the
    new content.   This is more flexible than the
    include directive, but requires more overhead. 
    Use only when necessary. Includes attributes
  • page- specifies the relative URL of the resource
    to include.  Must be part of the same Web
    application, or a request-time error occurs.
  • flush- specifies whether buffer should be flushed
    after include is performed.  In JSP 1.1, required
    to be true. If this attribute is not specified, a
    translation-time error occurs.

20
Include.jsp
  • ltbodygt
  • lttablegt
  • lttrgt
  • lttd style "width 160px
    text-align center"gt
  • ltimg src "images/logotiny.png"
  • width "140" height "93"
  • alt "Deitel Associates,
    Inc. Logo" /gt
  • lt/tdgt
  • lttdgt
  • lt-- include banner.html in this
    JSP --gt
  • ltjspinclude page "banner.html"
    flush "true" /gt
  • lt/tdgtlt/trgt
  • lttrgt
  • lttd style "width 160px"gt
  • lt-- include toc.html in this JSP
    --gt
  • ltjspinclude page "toc.html"
    flush "true" /gt
  • lt/tdgt
  • lttd style "vertical-align top"gt
  • lt-- include clock2.jsp in this
    JSP --gt

21
forward1.jsp
  • ltbodygt
  • lt // begin scriptlet
  • String name request.getParameter(
    "firstName" )
  • if ( name ! null )
  • gt lt-- end scriptlet to insert fixed template
    data --gt
  • ltjspforward page "forward2.jsp"gt
  • ltjspparam name "date"
  • value "lt new java.util.Date()
    gt" /gt
  • lt/jspforwardgt
  • lt // continue scriptlet
  • // end if
  • else
  • gt lt-- end scriptlet to insert fixed template
    data --gt
  • ltform action "forward1.jsp" method
    "get"gt
  • ltpgtType your first name and press
    Submitlt/pgt
  • ltpgtltinput type "text" name
    "firstName" /gt
  • ltinput type "submit" value
    "Submit" /gt
  • lt/pgt
  • lt/formgt

22
forward2.jsp
  • ltbodygt
  • ltp class "big"gt
  • Hello lt request.getParameter( "firstName"
    ) gt, ltbr /gt
  • Your request was received ltbr /gt and
    forwarded at
  • lt/pgt
  • lttable style "border 6px outset"gt
  • lttrgt
  • lttd style "background-color black"gt
  • ltp class "big" style "color
    cyan"gt
  • lt request.getParameter( "date" )
    gt
  • lt/pgt
  • lt/tdgt
  • lt/trgt
  • lt/tablegt
  • lt/bodygt

23
Exercise
  • Modify include to have different layout/ pages
    included
  • Modify forward1 and forward2 to accept a
    different piece of information and respond
    differently
  • Also experiment with if-else structure

24
Plugins
  • type - Component type bean or applet
  • code - class that represents the component
  • codebase - location of class specified in the
    code attribute and archives specified with
    archive attribute
  • align - alignment of the component
  • archive  - space-separated list of archive files
    that contain resources used by the component. 
    May include the class specified by the code
    attribute.
  • height - component height specifed in pixels or
    percentage
  • hspace- number of pixels of space that appear to
    the left and to the right of the component.
  • jreversion - version of Java Runtime Environment
    and plug-in required to execute component. 
    Default is 1.1.
  • name - name of component.
  • vspace- number of pixels of space that appear
    above and below the component.
  • title - text that describes the component.
  • width  - component width specified in pixels or
    percentage.
  • nspluginur1- location for download of Java
    Plug-in for Netscape
  • iepluginurl - location for download of Java
    Plug-in for Internet Explorer
  • Most Web browsers do not support applets written
    for Java 2 platform, so you must use Java
    Plug-in.  (still true?)

25
useBean Action
  • like constructor, only executed when bean is
    first created
  • has attributes that can be manipulated
  • id - name used to manipulate the Java object with
    actions like ltjspsetPropertygt and
    ltjspgetPropertygt A variable of this name is
    available for use in scripting elements. The bean
    should name properties using set and get in order
    to work with setProperty and getProperty.
  • scope- Can have page, request, session or
    application scope that indicates where they can
    be used in a Web application.
  • class - fully qualified class name of the Java
    object
  • beanName - name of a bean that can be used with
    method instantiate of class java.beans.Beans to
    load a JavaBean
  • type- Can be the same as the class attribute, a
    superclass of that type or an interface
    implemented by that type.  A ClassCastException
    occurs if the Java object is not of the type
    specified with the attribute type.
  • One or both of type and class must be specified,
    or a translation-time error occurs

26
setProperty
  • can be used to set JavaBean properties
  • Often used to map request parameter values to
    JavaBean properties
  • Can set primitive types boolean, byte, char, int,
    long, float, double and java.lang types String,
    Boolean, Byte, Character, Integer, Long, Float
    and Double.
  • Attributes used with setProperty
  • name- ID of JavaBean
  • property - name of property to set.  Can specify
    '' to cause JSP to match the request parameters
    to the properties of the bean.  If the value of
    the request parameter is "", property remains
    unchanged.
  • param- Can be used to specify which request
    parameter to use, in case names do not match bean
    properties. If omitted, names must match.
  • value - value to assign.  Often the result of a
    JSP expression.  Used when property types cannot
    be set with request parameters (avoid conversion
    errors).

27
adRotator.jsp
  • ltjspuseBean id "rotator" scope "session"
  • class "com.deitel.advjhtp1.jsp.beans.Rotator"
    /gt
  • lthtml xmlns "http//www.w3.org/1999/xhtml"gt
  • ltheadgt
  • lttitlegtLogoAnimator Examplelt/titlegt
  • ltstyle type "text/css"gt
  • .big font-family helvetica, arial,
    sans-serif
  • font-weight bold
  • font-size 2em
  • lt/stylegt
  • lt-- update advertisement --gt
  • lt rotator.nextAd() gt
  • lt/headgt
  • ltbodygt
  • ltp class "big"gtAdRotator Examplelt/pgt ltpgt
  • lta href "ltjspgetProperty name
    "rotator" property "link" /gt"gt
  • ltimg src "ltjspgetProperty name
    "rotator" property "image" /gt"

28
Exercise
  • Run adRotator.jsp
  • Create your own small bean, attach it to a jsp.
  • Example User.java. I have a user name and
    message. The output message depends on the user
    name. (idea business login encapsulated in the
    java class. Want to eliminate scriptlets
    expressions by using beans, makes cleaner syntax
    for jsp)

29
Directives
  • Messages to JSP that enable you to specify page
    settings, to include content from other
    resources, and to specify custom-tag libraries. 
    Directives are processed at translation time
    (i.e., before any requests are received). 
  • Three types of directives page, include and
    taglib

30
Handling Exceptions
  • When a JSP performs an operation that causes an
    exception, the JSP can include scriptlets that
    catch the exception and process it. 
  • Exceptions that are not caught can be forwarded
    to a JSP error page.
  • page directive defines information that is
    globally available in a JSP
  • Directives are delimited by lt_at_ and gt
  • errorPage attribute specifies page to handle all
    uncaught exceptions
  • isErrorPage set to true creates a page that can
    be used to catch errors
  • the implicit object exception can only be used in
    error pages

31
Page Directives
  • Attributes include
  • language - scripting language used, currently
    must be java
  • extends - class from which JSP will be inherited,
    must be fully qualified
  • import - comma-separated list of fully qualified
    names/packages to be used.
  • session - specifies whether the page participates
    in a session.  Default is true, which makes the
    implicit object session available. 
  • buffer - size of output buffer used with implicit
    object out.  Can be none or a value such as 8kb
    (the default).
  • autoFlush - If true (the default), indicates
    buffer associated with out should be flushed
    automatically when full.  If false, an exception
    occurs when the buffer is full. 
  • isThreadSafe - If true (default), the page can
    process multiple requests at the same time.  JSP
    allows multiple instances of a JSP if not thread
    safe.
  • info- information string that describes the
    page.  Returned by getServletInfo method.
  • errorPage - processes exceptions.
  • isErrorPage - if true, will handle exceptions.
  • contentType - MIME type of data in response,
    default is text/html.

32
On Your Own
  • Review Guest Book application
  • Interacts with database
  • Uses GuestDataBean
  • Uses one error page for application
    (guestBookErrorPage.jsp)

33
Include directives
  • includes the content of another resource, at
    compile time.  Only attribute is a file that
    specifies the URL of the page to include. 
    ltjspincludegt is processed each request to the
    server, so should be used if content of included
    resource can change.
  • view includeDirective.jsp

34
JSP
  • JSP syntax may be normal, as in text examples
  • Newer versions are XML-compliant
  • Not widely supported in 2003, probably is now
  • Easier to use with development tools
Write a Comment
User Comments (0)
About PowerShow.com