09 JSTL Tutorial

download 09 JSTL Tutorial

of 35

Transcript of 09 JSTL Tutorial

  • 8/2/2019 09 JSTL Tutorial

    1/35

    2009 Marty Hall

    The JSP Standard TaLibrary (JSTL)

    -

    in MVC-Based JSP PagesCustomized Java EE Training: http://courses.coreservlets.com/

    Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.3

    2009 Marty Hall

    For live Java training, please see training courses atp: courses.coreserv e s.com . erv e s, , ru s,JSF, Ajax, GWT, Java 5, Java 6, Spring, Hibernate, JPA,

    and customized combinations of to ics.

    Taught by the author ofCore Servlets and JSP, More

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.

    , .venues, or customized versions can be held on-site at your

    organization. Contact [email protected] for details.

  • 8/2/2019 09 JSTL Tutorial

    2/35

    Agenda

    Obtaining JSTL documentation and code

    The JSTL Expression Language

    Looping TagsLooping a certain number of times

    Looping over data structures

    -

    Conditional Evaluation Tags

    Multiple choices

    Database Access Tags Other Tags

    7

    2009 Marty Hall

    Installation

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.8

  • 8/2/2019 09 JSTL Tutorial

    3/35

    JSTL Overview

    Full JSTLContains many common and useful JSP custom tags

    Particularly useful when you are using MVC, but the

    Based on the Struts looping and logic tags

    ot art of the JSP 1.2 2.0 or 2.1 s ecs It is a separate specification that requires a separate

    download

    The JSP expression language came from JSTL, but is now

    art of JSP 2.0, JSP 2.1, and JSF

    The JSTL Specification is available in PDFhttp://jcp.org/en/jsr/detail?id=52

    9

    Downloading JSTL

    JSTL 1.1 ome page

    http://jakarta.apache.org/taglibs/doc/standard-doc/intro.html

    own oa http://jakarta.apache.org/site/downloads/

    downloads_taglibs-standard.cgi

    ocumen a on ava oc http://java.sun.com/products/jsp/jstl/1.1/docs/tlddocs/

    Note Many server packages (e.g., MyFaces) and IDEs (e.g.,

    MyEclipse) alreadyhave JSTL 1.1 bundled

    JSTL 1.2As of 10/2008, only available as part of Java EE 5

    Not as a separate download for use in other servers10

  • 8/2/2019 09 JSTL Tutorial

    4/35

    Enabling JSTL with Eclipse or

    EclipseDownload from

    Apache site .

    standard.jaronto WEB-INF/lib

    They also

    show up here.

    ey a so ge s e n Web App Libraries

    I usually rename JAR

    You drop

    them here.

    es o s ow exac vers on

    MyEclipse ,

    FileNewWeb Project,select JSTL 1.1 option

    11

    Enabling JSTL Manually

    Put in Web AppDrop JAR files in the WEB-INF/lib folder

    of your Web app

    Add the JAR files to the CLASSPATH used by your

    development environmentDo notadd to the CLASSPATH used by the server

    12

  • 8/2/2019 09 JSTL Tutorial

    5/35

    The JSTL Expression Language

    Accessed via ${expression}

    Similar to JavaScript and XPath

    Provides shorthand notation to access:Attributes of standard servlet objects

    Bean properties

    , ,

    Is standard part of JSP 2.0 and 2.1 ,

    In JSP 2.0, the EL can be used anywhere

    web.xmlelement and page directive attribute let yousa e e or ac war compa y

    EL covered in separate lecture13

    2009 Marty Hall

    Iteration Tags

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.15

  • 8/2/2019 09 JSTL Tutorial

    6/35

    Constructs for Handling-

    Simplest

    Bean ${cust.withdrawals}

    for Page

    Author

    Custom tag (non-looping)

    Custom tag (looping) ee examp es n A vance ustom ags

    lecture

    JSTL looMost

    JSP scripting loop

    17

    for Page

    Author

    Looping Tags: Summary

    Looping with explicit numeric values

    Blah, blah ${name}

    Looping over data structures , , ,

    Blah, blah ${name}

    forTokens

    18

  • 8/2/2019 09 JSTL Tutorial

    7/35

    Looping Tags: Motivation

    JSP without JSTL

  • 8/2/2019 09 JSTL Tutorial

    8/35

    Looping with a Designated Step

    .

    Timeout exceeded.

    21

    Looping Down Arrays (Servlet)public class ArrayServlet extends HttpServlet {

    ,

    HttpServletResponse response)

    throws ServletException, IOException {

    = " " " " " "

    request.setAttribute("words", words);

    String address = "/WEB-INF/results/array-loop.jsp";

    =

    request.getRequestDispatcher(address);

    dispatcher.forward(request, response);

    }

    Note url-pattern in web.xml is /test-array

    22

  • 8/2/2019 09 JSTL Tutorial

    9/35

    Looping Down Arrays

    ${word}

    Values of the test Parameter:< H2>

    ${val}

    23

    Note for Older Servers

    Examples in this lecture assume JSP 2.0+ a so runs n o er servers, ut you ave to rep ace

    direct output of ${foo} with

    Previous exam le JSP 2.0+

    ${word}

    Previous exam le JSP 1.2

    24

  • 8/2/2019 09 JSTL Tutorial

    10/35

    ${foo} vs.

    c:out runs on older serversOracle 9i, BEA WebLogic 8.x, IBM WebSphere 5.x

    c:out escapes HTML (XML) characters outputs

    Very important if value being output comes from end user.

    =" " =" "

    c:out lets you supply a default value or

    The default is output when ${foo} evaluates to null

    25

    Looping Down Collections: Notes

    Can loop down collections other than arrays items can refer to an array, collection (List, Map, Set,

    etc.), comma-separated String, Iterator, or Enumeration

    -

    ${bean.property}

  • 8/2/2019 09 JSTL Tutorial

    11/35

    Looping Down Arrays:

    public class ArrayServlet2 extends HttpServlet {

    public void doGet(HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    Name[] names ={ new Name("Bill", "Gates"),

    new ame arry , son ,

    new Name("Sam", "Palmisano"),

    new Name("Scott", "McNealy"),

    new Name("Eric", "Schmidt"),

    " " " ",

    request.setAttribute("names", names);

    String[][] sales =

    { {"2005", "12,459", "15,622"},

    "2006" "18 123" "17 789"

    {"2007", "21,444", "23,555"} };

    request.setAttribute("sales", sales);

    String address = "/WEB-INF/results/array-loop2.jsp";RequestDispatcher dispatcher =

    request.getRequestDispatcher(address);

    dispatcher.forward(request, response);

    }

    }27

    Note: url-pattern is /test-array2

    Looping Down Arrays:

    public class Name {

    private String firstName;

    private String lastName;

    public Name(String firstName, String lastName) {

    setFirstName(firstName);

    setLastName(lastName);

    }

    public String getFirstName() { return(firstName); }

    public void setFirstName(String firstName) {

    this.firstName = firstName;

    }

    public String getLastName() { return(lastName); }

    public void setLastName(String lastName) {

    this.lastName = lastName;

    }

    }28

  • 8/2/2019 09 JSTL Tutorial

    12/35

    Looping Down Arrays:

    Attendees at the coreservlets.com Party

    ${name.firstName} ${name.lastName}

    Comparing Apples and Oranges

    Year

    Apples Sold

    Oranges Sold

    ${col}

    29

    Looping Down Arrays:

    30

  • 8/2/2019 09 JSTL Tutorial

    13/35

    Loop Status

    You can assign varStatus.

    Usually using c:if (covered later in this lecture)

    index (int: the current index)

    first (boolean: is this the first entry?)

    last (boolean: is this the first entry?)

    begin (Integer: value of 'begin' attribute)en nteger: va ue o en attr ute

    step (Integer: value of 'step' attribute)31

    Loop Status: Example

    Names:

    ${name},

    32

  • 8/2/2019 09 JSTL Tutorial

    14/35

    Looping Down Comma-

    ${country}

    33

    Looping Down Arbitrarily-

    ${color}

    Point:forTokensbuilt on forEach:you can build your

    based on JSTL tags

    34

  • 8/2/2019 09 JSTL Tutorial

    15/35

  • 8/2/2019 09 JSTL Tutorial

    16/35

    HTML Code

    ...

    Getting XML Data from Server...

    City Type:

    >37

    Servlet Codepublic class ShowCities extends HttpServlet {

    public void doGet(HttpServletRequest request,

    HttpServletResponse response)

    throws ServletException, IOException {

    response.setHeader("Cache-Control", "no-cache");

    response.se ea er ragma , no-cac e ;

    String cityType = request.getParameter("cityType");

    List cities = findCities(cityType);

    request.setAttribute("cities", cities);String format = request.getParameter("format");

    String outputPage;

    if ("xml".equals(format)) {

    " ".

    outputPage = "/WEB-INF/results/cities-xml.jsp";

    } ...

    RequestDispatcher dispatcher =

    request.getRequestDispatcher(outputPage);

    dispatcher.include(request, response);

    }38

  • 8/2/2019 09 JSTL Tutorial

    17/35

    Original JSP Code- - .

    CityTime

    ea ng opu a on ea ng

    ${cities[0].name}

    ${cities[0].shortTime}

    ${cities[0].population}

    ... , , --

    ${cities[4].name}

    ${cities[4].shortTime}

    ${cities[4].population}

    39

    Problems with JSP Code

    RepetitiveAlmost-identical city entries repeated five times

    If the city format changes, all five entries need to change

    resumes exac y ve c esWill not work with a different number of cities

    Even thou h both the servlet code and the client-sideJavaScript code can handle any number of cities

    Solution se

    40

  • 8/2/2019 09 JSTL Tutorial

    18/35

    Updated JSP Code- .

    City

    Population

    =" "

    uri="http://java.sun.com/jsp/jstl/core" %>

    ${city.name}

    ${city.shortTime}

    < o ulation>${cit . o ulation}

    41

    Alternative Version- .

    " ". .

    City

    Population

    =" " =" "

    ${city.name}

    cit .shortTime < time>

    ${city.population}

    42

  • 8/2/2019 09 JSTL Tutorial

    19/35

    XML Data: Results

    43

    JSON Version: Original- - .

    { headings: ["City", "Time", "Population"],

    . , . ,

    "${cities[0].population}"],

    ["${cities[1].name}", "${cities[1].shortTime}",

    c es .popu a on ,

    ["${cities[2].name}", "${cities[2].shortTime}",

    "${cities[2].population}"],

    " c t es .name ", " c t es .s ortT me ",

    "${cities[3].population}"],

    ["${cities[4].name}", "${cities[4].shortTime}",

    "${c t es[4].populat on}"]]

    }

    44

  • 8/2/2019 09 JSTL Tutorial

    20/35

    JSON Version: Updated- .

  • 8/2/2019 09 JSTL Tutorial

    21/35

    Delimited String Version: Original- - .

    City#Time#Population

    . . .

    ${cities[1].name}#${cities[1].shortTime}#${cities[1].population}

    ${cities[2].name}#${cities[2].shortTime}#${cities[2].population}

    . . .

    ${cities[4].name}#${cities[4].shortTime}#${cities[4].population}

    47

    Delimited String Version: Updated- .

  • 8/2/2019 09 JSTL Tutorial

    22/35

    String Version: Results

    49

    2009 Marty Hall

    Logic Tags

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.50

  • 8/2/2019 09 JSTL Tutorial

    23/35

    Conditional Evaluation Tags

    One choice: if

    Content

    Lots of choices: choose

    Content1

    Content2

    ...

    ContentN

    Default Content

    Caution: resist use of business logic!51

    The "if" Tag

    (greater than 7)

    52

  • 8/2/2019 09 JSTL Tutorial

    24/35

    The "choose" Tag

    ${i}

    :

    (small)

    (medium)

    (large)

    53

    2009 Marty Hall

    Pages

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.54

  • 8/2/2019 09 JSTL Tutorial

    25/35

    Output Pages vs. Direct-Access

    Output pages n pages t at are t e resu t o a nav gat on ru e .e., ste

    under to-view-id), you can use JSTL as shown onprevious slides nce ean s a rea y n reques , sess on, or app ca on

    Direct access pages JSTL does not know about faces-confi .xml so ou

    cannot refer to beans that are listed there but not yetinstantiated

    Usin direct-access a es is rare in real life but is veruseful for testing when learning JSTL

    Solution: use h:outputText to refer to bean once first Declare bean containing array of numbers in faces-config.xml

    First num: ...

    55

    JSF Does Not Know About JSTL

    JSTL puts data in page scope s wor s

    $ name

    Example assumes this is an output page and "names" set

    earlier b JSF This fails

    " ":ou pu ex va ue= name

    Supposedly fixed in JSTL 1.2But there are no standalone releases of JSTL 1.2Use facelets instead

    56

  • 8/2/2019 09 JSTL Tutorial

    26/35

    2009 Marty Hall

    Database Access Tags

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.57

    Database Access Tags

    pec es a a source can a so e se y con g se ngs

    ueries database and stores ResultSet in variableWarning: this usage violates rule of keeping business

    logic out of presentation layer. Instead, do database

    access in servlet and ass results to JSP via MVC.

    actions as a single transaction

    58

  • 8/2/2019 09 JSTL Tutorial

    27/35

    Aside: The Microsoft Access

    Database that comes preinstalled withMicrosoft Office

    59

    Using Microsoft Access via

    Click Start, Settings, Control Panel,Administrative Tools, Data Sources, SystemDSN, and select Add

    60

  • 8/2/2019 09 JSTL Tutorial

    28/35

    Using Microsoft Access via

    Select Microsoft Access Driver, Finish, typea name under Data Source Name, and hit

    Select

    61

    Using Microsoft Access via

    Navigate to the Samples directory of MSOffice, select Northwind.mdb, hit OK, thenhit OK in following two windows

    62

  • 8/2/2019 09 JSTL Tutorial

    29/35

    Using Microsoft Access via

    Driver sun.jdbc.odbc.JdbcOdbcDriver

    Comes bundled with JDK

    jdbc:odbc:Northwind Local access only; for testing. Not for serious applications.

    UsernameEmpty string

    Password

    Empty string

    63

    sql:setDataSource

    You can set a data source globally viaconfiguration settings or application-scopedvariables.

    Or, you can set it on a specific page

  • 8/2/2019 09 JSTL Tutorial

    30/35

    sql:query

    Form 1: use the sql attribute

    Form 2: put the query in the body of the tagsq :query var= resu s

    SELECT * FROM

    OptionsdataSource

    maxRows

    startRow au on

    Embedding SQL directly in JSP may be hard to maintain.65

    Simple Example

    66

  • 8/2/2019 09 JSTL Tutorial

    31/35

    Simple Example (Continued)

    ${row.firstname}

    ${row.lastname}

    67

    Simple Example: Results

    68

  • 8/2/2019 09 JSTL Tutorial

    32/35

    2009 Marty Hall

    Other Tags

    Customized Java EE Training: http://courses.coreservlets.com/Servlets, JSP, Struts, JSF/MyFaces/Facelets, Ajax, GWT, Spring, Hibernate/JPA, Java 5 & 6.

    Developed and taught by well-known author and developer. At public venues or onsite at yourlocation.69

    URL-Handling Tags

    Read content from arbitrary URLs

    Insert into page

    Store in variable

    Or make accessible via a reader

    Unlike , not restricted to own system Redirects response to specified URL

    Encodes a request parameter and adds it to a URL

    70

  • 8/2/2019 09 JSTL Tutorial

    33/35

    Formatting Tags

    Formats a numeric value as a number, currency value, or

    percent, in a locale-specific manner

    Reads string representations of number, currency value,or percent

    71

    Internationalization (I18N) Tags

    Sets Locale

    < m : un e>

    etr eves oca ze message rom a resource un e

    72

  • 8/2/2019 09 JSTL Tutorial

    34/35

    XML Manipulation Tags

    Core

    XPath

    XSLT

    73

    Summary

    JSTL overview JSTL s s m ar to t e o Struts oop ng an og c tags, ut etter

    JSTL is standardized, but not a standard part of JSP You have to add JAR files to WEB-INF/lib

    t s suppose to e nc u e w t a mp ementat ons

    Supports a concise expression language

    Lets you access bean properties and implicit objects EL is standard part of JSP 2.0, JSP 2.1, and JSF

    Looping tags

    Arrays, collections, maps, strings, etc.

    Conditional evaluation tags Single options

    Multiple options

    74

  • 8/2/2019 09 JSTL Tutorial

    35/35

    Summary (Continued)

    Database Access TagsAlways a bad idea when using MVC approach

    With or without a framework like JSF or Struts

    sql:query to perform query

    Loop down results using iteration tags

    Other tagsHandling URLS

    Internationalizing pages

    Formatting strings

    Bad idea when using MVC

    75

    2009 Marty Hall

    Questions?