5509009 Jstl Complete Reference

  • View
    223

  • Download
    1

Embed Size (px)

Text of 5509009 Jstl Complete Reference

  • 8/14/2019 5509009 Jstl Complete Reference

    1/37

    As J2EE programmers, we are familiar with Servlets , JSP and JavaBeans. Any JSP pageshould encapsulate the business logic in a bean and invoke it by using tag. Tillrecently, a combination of Servlets, JSP and beans was the standard practice. But, the JCPrealeased an API for enabling programmers to create custom tags and use them in their JSPpages. The difference between javabean and java custom tags was that, though both made use of

    java classes, tags can be used by non-programmers also without knowledge of Javaprogramming, just as they would use html tags.( From a programmer's perspective,however, amuch more important distinction is that tags are specific to the page in which they are createdwhile javabeans are general. )

    {{{ Back in 1998, a Web-Server Technology , known as ColdFusion , created by Allaire ofAllaire Corporation, was very much in demand!. It was a purely tag-based language, using whichpage-authors can turn into programmers overnight. The tags were so powerful and simple to use!There is a separate lesson on using ColdFusion for typical web-based database opeartions,elsewhere in this edition, just to indicate the source of inspiration of the tag library idea, of theJSTL. To this day, ColdFusion is unbeatable, in its power,speed, ease of use and productivity.

    However, among the various web-server technologies ( namely

    ASP, Servlets, JSP,Perl,PHP , ColdFusion &

    ASP.net), CF is the only technology that is not free!And perhaps for this reason, it is no longerpopular in Indian environment, though it is said to be very much in vogue still, in US!

    MacroMedia of 'Flash fame' purchased ColdFusion .There was even a tutorial on MacroMediaColdFusion Exprsess in DeveloperIQ., a few months back.It is interesting to make a comparisonof the CF tags approach and the JSTL approach., especially , in DataBase operations.Readers arerequested to read the lesson on ColdFusion,in this edition, after covering sql tags in JSTL , in the

    fourth part of this tutorial..}}}

    To resume,the release of the TagLibrary API, triggered a lot of activity and hundreds oftags were introduced by the java community, some of them 'open' and a few 'proprietary'. Thisled to a lot of confusion in code maintenance, because knowledge of Java was no longersufficient to understand and interpret a given jsp page using non-standard tags .The JCP hadunwittingly introduced elements of confusion by the JSP-Custom-Tag specification.

    To correct this problem, Sun and JCP, initiated the JSP-Standard Tag Library (JSTL)project. Though there are a number of popular and powerful tag-libraries, it is always better forj2ee coders to adopt the JCP standard because, it is likely to be merged into the core specification

    of Java langauage itself, in future. (That yardstick may be valid for all creations, in Java world.Splintering of the Java platform due to' hyper-active creativity without the correspondingdiscipline to get it through a standards body ,is the greatest threat, looming large in the Java-horizon.

    Too frequent revisions and additions, that too without caring for backward compatibility,are notconducive to programmer productivity and the net result is that programmers spend ,in learningnew twists in grammar, their precious time which should have been spent more usefully in

  • 8/14/2019 5509009 Jstl Complete Reference

    2/37

  • 8/14/2019 5509009 Jstl Complete Reference

    3/37

    -----------------------------------------------------------------------------(relevant section of greeting.java servlet)

    // greeting.java ( code-snippet only)public void doPost(HttpServletRequest req,

    HttpServletResponse resp)throws ServletException,IOException {

    resp.setContentType("text/html");PrintWriter out = resp.getWriter();

    //-------------------------------String s = req.getParameter("text1");out.println("");out.println("we welcome"+",
    ");out.println (s);out.println(" ");

    }

    -----------------------------------------------

    It will be noticed that we have to write so many 'out.println' statements. This makes the page

    unreadable.( If String-buffer is used , we can do it with just a single out.println , but forming thecorrect string may pose difficulties).

    It is to solve this problem that JSP was developed five years back(1999).While a servletinterposes HTML in java code, JSP interposes java-code in HTML, as some authors correctlyobserve..( in this case, we have to modify the action field in html form, so that it refers to thefollowing greeting1.jsp).Student readers will know about 'delimiters' (

  • 8/14/2019 5509009 Jstl Complete Reference

    4/37

    String s = request.getParameter("text1");out.println("we welcome"+
    );out.println(s);%>

    -----------------------------------------------

    Some coders prefer to use expressions.

    What is an 'expression'? It is a method of sustituting request-time values in html page. ( seegreeting2.jsp). Carefully note that there is no semi-colon after ("text1").

    ----------------------------------------------- // greeting2.jsp

    we welcome

    -----------------------------------------------

    The third variant is to use a javabean to encapsulate the business-logic. We develop a jsp-bean asfollows:

    ------------------------------------------

    // greeter.java//==============

    package ourbeans;

    public class greeter {

    public greeter() { } public String greetme(String s) {

    return "we welcome..."+s;}}-------------------------------------------

    This source file is compiled and the class-file is copied to :

    'e:\tomcat5\webapps\root\WEB-INF\classes\ourbeans'

  • 8/14/2019 5509009 Jstl Complete Reference

    5/37

  • 8/14/2019 5509009 Jstl Complete Reference

    6/37

    To consider another example, In servlet & jsp, we write:

    String s = request.getParameter("text1");

    to collect the input from the user.

    The same job is done in JSTL by:

    ==================================

    With these brief hints, it should not be difficult to understand the

    following JSP page written by using JSTL core-tags.

    -----------------------------------------------

    // greeting4.jsp ( uses JSTL)

    ===========

    We welcome

    -----------------------------------------------

    In the previous examples, there was java code in a few lines atleast. But, in the JSTL example,we find thatthere are only tags and no java scriptlets.This is the avowed objective of theJSTL initiative,

    under the auspices of Java Community Project! Why? This enables , clean separation of Pageauthor's role and Logic programmers' role. Thus maintenance becomes easy.

    ===============================================

  • 8/14/2019 5509009 Jstl Complete Reference

    7/37

  • 8/14/2019 5509009 Jstl Complete Reference

    8/37

    For the present, we are interested in JSTL folder only. If we expand the JSTL folder, we findfour sub folders :

    a) docs

    b) lib

    c) samples

    d) tld ( tag library descriptors)

    When we look into the 'lib' folder, we find two jar files:

    a) standard.jar

    b) jstl.jar

    We should copy these two jar files into :

    'e:\tomcat5\webapps\root\WEB-INF\lib'

    -----------------------------------------------

    ( Remember to restart the Tomcat server). That is all that is required to use JSTL. !

    The included taglibrary descriptors do not have to be placed in the WEB-INF folder.These filesare already included in the /META-INF folder of the jstl.jar and so will be automatically loaded

    by Tomcat, when it is restarted.

    ***********************************************

    ( we are using tomcat5 & jdk1.4.2)

    ( the results are not ensured for other environments.).( however, we adopted the samemethod in Tomcat4.1 withjdk1.41 and got correct functioning.)

    ===============================================

  • 8/14/2019 5509009 Jstl Complete Reference

    9/37

    The JSTL folder contains a sub-folder named 'tld'. There will be a number of tld files theresuch as

    c.tld, ( core)

    x.tld, (xml)

    fmt.tld, (format)

    sql.tld & (sql)

    fn.tld. (functions)

    ------------------------------

    Some authors say that we should copy these tld files to ..

    ..:\tomcat5\webapps\root\WEB-INF folder.

    A few others , say that there is automatic detection and so it is not necessary. We chose not tocopy the tld files into

    e:\tomcat5\webapps\root\WEB-INF folder !

    We found that the programs works well.No problem!

    When we study the web.xml file in e:\tomcat\webapps\root\WEB-INF folder, we find that itfollows DTD and not Schema.

    ( DTD stands for Document -Type- Definition).

    ( Schema serves the same purpose but is in XML format and is more powerful). ( The default isDTD ).

    This point is very important. The default allows us to use EL,(Expression Language) but byusing

  • 8/14/2019 5509009 Jstl Complete Reference

    10/37

    We are now ready to experiment with all the tags in the core

    library. The core tags have the following uniform uri.

    http://java.sun.com/jstl/core'

    ( However, in the book by Hans Bergsten titled,"Java Server

    Pages" ( third edition),

    (OReilly pub)the uri is consistently given as :

    'http://java.sun.com/jsp/jstl/core'.It looks as if there hasbeen some change in specification and grammar, after it was

    published!

    This appears to be wrong as the server threw exception.The

    correct uri is :

    'http://java.sun.com/jstl/core'.)

    The prefix is c:

    The following tags are available in the core library.

    ( Remember them as a dozen!).

  • 8/14/2019 5509009 Jstl Complete Reference

    11/37

    demo1.jsp uses

  • 8/14/2019 5509009 Jstl Complete Reference

    12/37

    The second example is very important. When the user enters

    data in a number of fields, it is tedious to collect the data

    and transfer it to jsp page for processing. In our example, we

    are collecting data about a player, such as his name, place and

    game. We can have much more but we are restricting for space

    considerations. JSP has an action tag , known as

    'jsp:setProperty'. Using this along with a standard javabean, wecan extract data and transfer it to our program in a single step.

    The syntax is

    :( the * sign denotes 'all').

    -----

    But, we should first create the 'player ' bean with all the

    attributes and getter & setter methods, as shown.

    ---------------------------------------------

    // player.javapackage ourbeans;

    public class player{String name;

    String place;

    String game;

    public player(){

    name=" ";

    place=" ";

    game=" ";

    }

    //---------------------------

    public void setName(String a){name=a;

    }

    public void setPlace(String b){place=b;

    }

  • 8/14/2019 5509009 Jstl Complete Reference

    13/37

    public void setGame(String c){game=c;

    }

    //------------------------------

    public String getName(){return name;

    }

    public String getPlace(){return place;

    }

    public String getGame(){return game;

    }

    }

    ---------------------------------

    In demo2.jsp, we collect the data and then display the data

    entered by the user.

    Note that instead of {param.text1}, we are using {bean1.name}.

    We should carefully name the html form controls with the

    corresponding attribute names given in the bean. We cannot name

    the controls as 'text1' etc, now!

    ---

    We get correct result.

    =============================================

  • 8/14/2019 5509009 Jstl Complete Reference

    14/37

    // demo2.jsp

    Name
    Place
    Game

    Name:
    Place:

    Game:

    =============================================

    Once again, it will be noticed that there is no java code in

    this example, as everything is being done by tags, only..

    ***********************************************

  • 8/14/2019 5509009 Jstl Complete Reference

    15/37

    We are now ready to take up examples for condition tags.

    There are two types of 'condition tags'.

    namely, & .

    In the third demo, we learn how to use the

  • 8/14/2019 5509009 Jstl Complete Reference

    16/37

    The above code is no Rocket-Science as American authors

    say!But , if we are careless in typing the names sam or tom

    in the test condition, we could spend hours together , trying to

    coax this code into functioning! We should not leave space after

    the single quote in the 'test expression'. Second point worth

    noting in the above example is that we can use either ==

    ( double equal to) or eq to test equality.

    ***********************************************

    In the fourth example which follows, we take up tag.

    The syntax is:

    something

    The peculiarity to be noted here is that unlike

  • 8/14/2019 5509009 Jstl Complete Reference

    17/37

    Today is


    Sunday Monday

    Tuesday

    Wednesday

    Thursday

    select between 1 & 5

    ---------------------------------------------

    Demo-5 deals with Iteration tag.

    We are familiar with the 'for-each' construct.

    JSTL's 'for-each' also has the same functionality.

    In the following example, we have a String array. named as

    'colors'.

    By using the tag, we iterate through the array and

    display the values.

    ------------------------------------

    //demo5.jsp

  • 8/14/2019 5509009 Jstl Complete Reference

    18/37

    We get the following display, when we execute the program.

    0 1 true false red

    1 2 false false green

    2 3 false false blue

    3 4 false false purple

    4 5 false true black

    ===============================================

    action tag contain the following attribute list:

    items : the collection of items like String[]

    var : a symbolic name for the collection

    begin : the starting index of iteration

    end : the ending index of iteration

    step : incremental step

    varStatus: symbolic name for current status.

    If we assign the symbolic name 'a' for the status, we are able

    to access its properties such as index, count, whether it is

    first item,

    whether it is last item and the current value.

    Demo6 also deals with iteration tag.In the following example, the iteration starts at value 3and ends at value 8 .It displays the values of n in each iteration.Each iteration increments the

    value of n automatically by 1,if step is not specified.

    -----------------------------------------------

    demo6.jsp


  • 8/14/2019 5509009 Jstl Complete Reference

    19/37

    3 4 5 6 7 8

    ===============================================

    Demo7 deals with JSTL's 'forTokens' tag., which iterates over a string of tokensseparated by a set of delimiters like the stringTokenizer class in Java.

    --------------------------------------------

    demo7.jsp

    Name

    Place

    Degree

    Age

    Mark


    ------------------------------------------

    Name Place Degree Age Mark

    kala Kkdi mca 23 87

    ------------------------------------------

    The essential attributes of 'forTokens' tag are:

    Attribute Description

  • 8/14/2019 5509009 Jstl Complete Reference

    20/37

    items The string to tokenize

    delims The delimiter characters that separate the tokens of thestring.

    ===============================================

    Demo8 deals with URL-Related actions.action tag imports the conent of a URL-based resource and provides a simple way to access URL-based resources that can either beincluded or processed within the JSP..

    In the following example,the import action tag imports the content of welcome.htm file here.Soit displays the contents of demo8.jsp and welcome.htm.

    --------------------------------------------

    // welcome.htm

    WELCOME


    ---------

    demo8.jsp

    ===============================================

    In demo9 we discuss theaction tag.

    prints the value of URL.It is easier to construct the

    hyperlinks.It is useful for session preservation (URL-Encoding).

    In the following example,we use to make a link to

    another html file. When we execute demo9, we get a link , with

    text 'send'.

    When we click on the link, we are taken to welcome.htm.

    --------------------------------------

    demo9.jsp

  • 8/14/2019 5509009 Jstl Complete Reference

    21/37

    %>

    ">send

    --------------------------------------

    ===============================================

    demo10 deals with action tag.

    This tag forwards the browser to the specified URL .

    demo10.jsp

  • 8/14/2019 5509009 Jstl Complete Reference

    22/37

    And to end our whirlwind tour of core-tags in JSTL, here is a

    demo which mixes EL of JSP-2(Expression Language of JSTL) with

    'Expression' (also known as request-time Expression ) of JSP1.2.

    demo12.jsp

    JSTL welcomes


    JSP Expression welcomes

    -------------------------------------------

    In the next and third part of this tutorial, we will learn about

    xml tags in JSTL.

    JSTL XML Tags

    No one can have any second opinion about the elegance of xml

    tags in JSTL.If the readers have been following the earlier

    instalments of this J2EE series of tutorials, they would have

    come across JAXP,DOM,SAX ,JDOM and such terms, and it may have

    been none too easy to learn. But the xml tags in JSTL , make XML

    processing and even Transformation , a cynch! And ,we nowproceed to study them.

    Making our study even easier, many of the xml tags in JSTL ,

    are very much similar to the 'core' tags. For example, just like

    , we have .

    Similarly,

    , , etc.

    So, if we have understood the syntax of the 'core'; tags, it

    will not be difficult to use the 'xml' tags.

    All the following examples use thebooks.xml file.It contains'elements' like 'title' and 'author'..

  • 8/14/2019 5509009 Jstl Complete Reference

    23/37

    books.xml

    cobolroy

    java

    herbert

    c++

    robert

    coldfusion

    allaire

    xml unleashed

    morrison

    jrun

    allaire

    -----------------------------------------------

    demo1

    The following program reads the xml file using 'forEach' tag anddisplays the title and author of each book..

    The syntax:

    is used to select the elements from the xml file.

  • 8/14/2019 5509009 Jstl Complete Reference

    24/37

    is used to print the elements of the xml file. We begin by

    importing the reference to the XML file to be parsed.

    -----

    We have given a symbolic name for this file as 'url'.Next we

    ask the program to parse this XML file.The resulting tree is

    given a symbolic name as 'doc'.

    In the next step, we direct the program to select each title and

    each author in the XPATH expression $doc/books/book. If we referto the xml file , we find that the root element of the document

    is 'books'. Inside this, we have 'book'.So, XPATH can be thought

    of as just a file hierarchy. Just like

  • 8/14/2019 5509009 Jstl Complete Reference

    25/37

    information, without any mention about DOM,SAX and such words.,

    atall!Wonderful!As a famous author would say, 'anything that

    makes my job easier, I like!'.

    When we execute the 'program', we get the following result.

    -------------------------------------------

    (Result for executing demo1.jsp)

    ==========================

    cobol

    roy

    ==========

    java

    herbert

    ==========

    c++

    robert

    ==========

    coldfusion

    allaire

    ==========

    xml unleashed

    morrison

    ==========

    jrun

    allaire==========

    ***********************************************

    The following program (demo2)displays the books and authors of

    xml file in table format.

    demo2.jsp

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

  • 8/14/2019 5509009 Jstl Complete Reference

    26/37

    title

    author

    title author

    cobol roy

    java herbert

    c++ robert

    coldfusion allaire

    xml unleashed morrison

    jrun allaire

    ------------------------------------------------

    demo3 deals with the selection of particular book's author from the xml file ,when we give thetitle, with the help of action tag.The title is choosen from combo box in demo2.htm fileand submitted.We get a display of the selected title and its author.

    Think of this as an sql query like

    "select * from table1 where title='jrun'"

    --------------------------------------------------

    demo3.htm

    SELECT THE TITLE.

    YOU WILL GET TITLE & AUTHOR.

  • 8/14/2019 5509009 Jstl Complete Reference

    27/37

    xml

    c++

    cold fusion

    java

    cobol

    --------------------------

    demo3.jsp

    ------



    -**********************************************

    demo4 is a simple variation on the same theme. In this case,the user selects the author name from the combo and any books by

    that author are displayed, due to the code.

  • 8/14/2019 5509009 Jstl Complete Reference

    28/37

    It will be noted that 'allaire' has two books to his credit and

    so if we choose 'allaire' in the combo,his two books are

    displayed.If 'haris' is chosen, we should display the message

    that it is yet to be published as there is no such entry in the

    xml file. But there is no 'if-else' construct and so we

    improvise.

    We have created a variable 'a' and assigned the value 'ok' to

    it. If there is no author to match the user's selection, the

    conditional block is ignored and 'a' will not be 'ok'.

    From this, we conclude that 'the book is not ready'.

    ----------------------------------

    demo4.htm

    Select name of author & view his books

    morrison

    robert

    allaire

    herbert

    roy

    haris

    ==============

    demo4.jsp

    ========

  • 8/14/2019 5509009 Jstl Complete Reference

    29/37



    ===============================================

    In demo5 also, we display the title & author for a given title, but we now use

  • 8/14/2019 5509009 Jstl Complete Reference

    30/37

    demo5.jsp

    Result

    --------------------

    title sent from user:

    c++

    --------------------

    c++

    robert

    ========================-

    title sent from user:

    VB

    --------------------no such records

    ***************************************

    In demo6 , we see XSLtransform using JSTL. ( as promised in the

    earlier tutorial on XSLT in October issue).For the sake of

    continuity with the earlier tutorial,we revert back to

  • 8/14/2019 5509009 Jstl Complete Reference

    31/37

  • 8/14/2019 5509009 Jstl Complete Reference

    32/37

    -----------------------------------------------

    xsl1.xsl

    =======

    Name

    Place

    Number

    Mark

    ---------------------------------------------

    Name Place Number Mark

    Thomas Delhi 1111 78

    David Bombay 4444 90

    Mathew Bangalore 5555 92

    John Hyderabad 6666 72

    ===============================================

  • 8/14/2019 5509009 Jstl Complete Reference

    33/37

    That completes our study of 'xml' tags in JSTL.We now move ahead

    to the fourth and final part of the present tutorial, dealing

    with 'sql' tags in JSTL.

    JSTL & SQL-TAGS

    The Struts community has ordained that JSP should be strictly a

    'view-technology', in the Model-View-Controller Architecture.

    According to Struts philosophy, JSP should not deal with Data-Accesss and such data access should be done by 'Model'

    components only.( read 'beans'). JSTL , however, provides for

    sql tags, inspired by ColdFusion! ( please see a very short

    tutorial on DB-Operations using ColdFusion' available in this

    issue as a separate lesson. and compare JSTL code and CF

    code!).And , a few months back, the editor of 'Java Lobby'

    magazine was all admiration for the absolutely nice features of

    these sql tags, whatever, 'struts' may say! Just as EJB may be

    'overkill', except for really big Enterprise applications,

    Struts also may be an unnecessary complication for small and

    medium level projects. In such cases, it is much more direct to

    provide for data access by the JSP itself, but using JSTL 'sql'

    tags.We take up these 'sql' tags in this part of the tutorial.

    Let us begin with 'sql.htm'. It just provides a simple form with

    just a textarea & submit button. Normally, queries by MIS

    department will be very complex and so we have provided a

    textarea for the 'select' query.After filling up the query, it

    is submitted and the corresponding query.jsp is invoked.

    // query.htm

  • 8/14/2019 5509009 Jstl Complete Reference

    34/37

    ------------------------------------

    query.jsp is given below. In the standard jdbc code,we begin by

    asking for the availability of the driver.

    "jdbc.odbc.JdbcOdbcDriver". And then, we specify the URL of the

    database as 'jdbc:odbc:telephone'.

    Similarly, in JSTL also, we begin with

  • 8/14/2019 5509009 Jstl Complete Reference

    35/37

    driver="sun.jdbc.odbc.JdbcOdbcDriver"

    url="jdbc:odbc:dbdemo" />


    ===============================================

    In the second example,(dbeditor.htm & dbeditor.jsp) we provide a

    combo, with options such as: add, modify, remove and verify.

    In JSTL , we have a separate sql tag known as '

  • 8/14/2019 5509009 Jstl Complete Reference

    36/37

    -------------------------------------------------

    dbeditor.jsp

    ----------------------------------------------

    ---------------------------------------------

    -------------------------------------------

  • 8/14/2019 5509009 Jstl Complete Reference

    37/37

    ------------------------------------------

    ====================