meljun_cortes_jedi slides web programming chapter06 advanced jsps

Upload: meljun-cortes-mbampa

Post on 06-Apr-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    1/49

    Advanced JSPs

    Web Programming

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    2/49

    JSP Expression Language

    2Web Programming

    Was introduced with the JSP 2.0 specification

    Provides a simple and clean syntax for writing expressionsthat perform simple logic or access scoped values

    Example: If we want to access the property of a JavaBean, we could use

    either:

    or

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    3/49

    3Web Programming

    (Example continued)

    Using this method, developers are exposed to Java programmingconstructs: to access a bean's property, developers have to use thebean's getter methods.

    The developer also needs to be aware of the Java type of the

    property.

    This method is more programming-neutral: access to the bean'sproperty is handled through tags that are conceptually similar toHTML tags.

    However, this method of accessing a bean's property is long andcumbersome.

    Also, this method presents its output directly to the client browser;no manipulation can be performed on the retrieved value.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    4/49

    JSP Expression Language

    4Web Programming

    (Example continued)

    Using the EL, the bean's property can be accessed as:

    ${user.lastName}

    The above construct is programming-neutral: the developer does not need toknow Java types or syntax.

    It is also short and to the point: the construct contains only the scoped variableand the property to be accessed, with a minimum of characters added.

    Also, it can be used equally for displaying output directly to the user, or to exposethe value for custom tags to process.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    5/49

    EL Syntax

    5Web Programming

    An EL construct can be a literal or an expression enclosedin between ${ and }.

    Literals

    EL Supported literals: Boolean

    Long

    Float

    String

    Null Treated identically as they are in Java. For example, boolean values

    can either be true or false, String values need to be enclosed ineither double-quotes ("") or single quotes (''), null defines a non-existent value.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    6/49

    EL Syntax

    6Web Programming

    Operators

    EL also defines standard operators that can be applied on literals.

    Include:

    Basic arithmetic operators (+, -, *, /, %) Logical operators (&&, ||, !)

    Comparison operators (==, !=, =)

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    7/49

    EL Syntax

    7Web Programming

    Reserved words

    EL also defines reserved words that mimic the functionality of someof the operators:

    and (&&), eq (==), gt(>), ge(>=), or (||), ne (!=), le (

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    8/49

    EL Syntax

    8Web Programming

    Examples of EL Expressions

    ${'JEDI'} - evaluates to the String 'JEDI'

    ${5 + 37} - evaluates to 42

    ${ (10 % 5) == 2} - evaluates to true ${empty ''} - evaluates to true

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    9/49

    Accessing Scoped Variables

    and Properties

    9Web Programming

    While being able to evaluate simple literal expressions isuseful, EL shows its utility the most when accessing andprocessing variables and properties in different scopes

    Variable access is simple with EL:

    Variables are simply referenced by name.

    Bean properties, methods, and arrays can all be accessed from a namedvariable using the "." notation.

    Nested methods/properties are accessed the same way.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    10/49

    Accessing Scoped Variables

    and Properties

    10Web Programming

    Example:

    ${user.lastName}

    Accesses a JavaBean that can be referenced by the name user andretrieves the value of its lastName property.

    The scope of the bean does not matter.

    EL performs the scope lookup, checking within the page, request, session, andapplication scopes (in that order) for a bean with the specified name.

    If EL was provided the name of a bean that does not exist within any scope, avalue of null will be returned.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    11/49

    EL Implicit Objects

    11Web Programming

    While automatic scope lookup makes it easier fordevelopers to write code, specifying a variable's scopeexplicitly makes our construct easier to maintain by futuredevelopers.

    EL provides us with several implicit objects that represent aMap of the objects within the different scopes:

    pageScope

    requestScope

    sessionScope applicationScope

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    12/49

    EL Implicit Objects

    12Web Programming

    In addition, EL also defines the following implicit objects:

    param: Represents as a Map request parameter names and values.For example invoking ${param.loginName} is equivalent to callingrequest.getParameter("loginName"). The values stored here are

    single String values. paramValues: A Map that maps parameter names to String arrays

    representing the values for the name. Invoking ${paramValues.choices} is similar to callingrequest.getParameterValues("choices").

    header: A Map representing the headers available from a givenrequest. Its contents are similar to that retrieved by calling thegetHeader method from a ServletRequest object.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    13/49

    EL Implicit Objects

    13Web Programming

    (Other implicit objects continued)

    headerValues: A Map representing the headers available from agiven request. Its contents are similar to that retrieved by calling thegetHeaders method from a ServletRequest object.

    cookies: Maps the cookies available in a request. Similar to invokingthe getCookies method from an HttpServletRequest object.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    14/49

    The [] Notation

    14Web Programming

    Aside from the "." notation, EL also provides the "[]" notationin accessing member variables, methods, and arrays.

    In many ways, the two notations are similar:

    ${user.lastName}

    ${user[lastName]}

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    15/49

    JSTL

    15Web Programming

    Java Standard Tag Library

    Frees us from the use of scriptlets within our JSP pages

    Custom tags

    One of the strong points of the JSP specification is that it allows for adegree of customization and extensibility through the use of customtags.

    Provide for a way to expose reusable functionality within a JSP pageusing a very simple interface while hiding the internal implementation.

    There are a number of such tag libraries available, and it is unavoidable for customtags developed by programmers to have some sort of overlap in the kind offunctionality that they provide.

    Java has recognized this and, in cooperation with the programming community,has provided a standard tag library that addresses the areas of overlap, called theJava Standard Tag Library or JSTL.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    16/49

    Including the JSTL in our

    Application

    16Web Programming

    To include JSTL functionality in our application:

    Simply unpack the zip file available as a download from Java's site.

    Copy the standard.jar and jstl.jar files located in the /lib directory intothe /lib directory of our application.

    There are several sets of tag libraries packaged underJSTL. Only the core library is covered in this discussion.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    17/49

    Core Library

    17Web Programming

    Provide functionality that is useful for any web project

    The Core set can be further sub-categorized into:

    General purpose tags

    Iteration Conditionals

    URL manipulation

    For every JSP page that will make use of the functionality in

    the Core tag library, the following directive must be added tothe page:

    This exposes the tags inside the core library using the c prefix.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    18/49

    General Purpose Tags

    18Web Programming

    Perform common and simple tasks, though one of them hassince become irrelevant with the release of the JSP 2.0specification

    The tags comprising the general purpose set are:

    out

    set

    remove

    catch

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    19/49

    19Web Programming

    Takes in an EL expression, evaluates its result, and thenoutput the result directly to the Writer object correspondingto the page's output.

    Functions much the same way as the standard action, with the exception that a JavaBean is notneeded to access the functionality.

    Has become rather obsolete with the release of the JSP 2.0specification:

    EL expressions can be evaluated direct into the output stream in anypart of the JSP page without using any tags with JSP 2.0.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    20/49

    20Web Programming

    Performs much the same functionality as the action in that it is able to set values withina target JavaBean.

    Also able to set a variable within a specified scope that canbe used later by the JSP or elsewhere in the application.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    21/49

    21Web Programming

    Has the following attributes:

    value: The value that will be set into the target bean. Can be an ELexpression.

    var: The name of the variable that will be set into a specified scope.

    scope: Defines the scope of the variable defined by the var attribute.The value can be one of the following: page, request, session, andapplication.

    target: The name of the JavaBean whose property will be set.

    property: The name of the property within the JavaBean that willreceive the value.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    22/49

    22Web Programming

    As mentioned, there are two primary uses for this tag:

    To set the value within a target JavaBean

    Tag makes use of only the value, target, and property attributes

    which is equivalent to

    To set a variable into a defined scope for later use

    Tag makes use of only the value, var, and scope attributes, though the scopeattribute is optional. When the scope attribute is omitted, it defaults into usingpage scope.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    23/49

    23Web Programming

    In the spirit of limiting the JSP for presentation purposes, weshould limit the use of this tag.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    24/49

    24Web Programming

    Provides a way to remove variables from a defined scope.

    Has two attributes:

    scope the scope of the variable to be removed.

    var the name of the variable to be removed from the definedscope.

    Like the tag though, use of this tag should belimited.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    25/49

    25Web Programming

    Provides error handling capability in specific areas in a JSP.

    It is simple to use:

    Place the JSP content that could potentially throw errors inside thebody of the tag.

    Has only one attribute:

    var: Defines the name that will be used to expose the thrownexception. The variable thus created will have page scope; that is, itis accessible even after the catch block has ended.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    26/49

    26Web Programming

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    27/49

    Iteration

    27Web Programming

    Provide alternatives to embedding do-while, while, and/or forloops inside our JSP page as scriptlets.

    Two tags:

    forEach

    forToken

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    28/49

    28Web Programming

    By far the more commonly used iteration tag.

    Allows iteration over:

    primitive arrays

    instances of: java.util.Collection

    java.util.Iterator

    java.util.Map

    java.util.Enumeration

    Does iteration by going through each element in the targetand exposing the current value of the iteration to the JSPcode contained inside the tag's body.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    29/49

    29Web Programming

    Has the following attributes:

    var: Defines the name of the variable used to expose the currentvalue of the iteration to the tag body. Its type is dependent on thecollection being iterated over.

    items: Defines the collection to be iterated over. This can bespecified as an EL expression.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    30/49

    30Web Programming

    (Attributes continued)

    Optional attributes:

    varStatus: Defines the name of a variable that can be accessed by the loop bodyto gain information on the current loop status.

    begin: An int value that defines the index that will be used as the starting point ofthe iteration. If this value is not supplied, the iteration index starts at 0, thebeginning of the collection. Can be a runtime expression.

    end: An int value that defines the index that determines the stopping point of theiteration. If no value is specified, the iteration will continue until the last element isreached.

    step: An int value that defines the step size to be used while going through the

    iteration.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    31/49

    31Web Programming

    A common use of this tag is to iterate over the results ofprocessing performed elsewhere in the application.

    Sample scenario

    We have an application module that retrieves from the database user details that

    fall under a specific search category. Naturally, we want to perform the databaseaccess logic from a servlet and pass on the data to a JSP for presentation.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    32/49

    32Web Programming

    ...// load user parameters into a MapMap parameters = loadUserParameters();UserDataService service = new UserDataService();// perform database search, and store the results inside a Collection.Collection results = service.searchUsers(parameters);

    // store the results for future accessrequest.setAttribute("searchResults", results);// forward the request to a JSP for displayrequest.getRequestDispatcher("/results.jsp").forward(request, response);...

    JSP using JSTL

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    33/49

    33Web Programming

    JSP using JSTL

    The following users met your search criteria :

    ${user.name} - ${user.address}

    JSP without JSTL

    The following users met your search criteria :

    -

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    34/49

    34Web Programming

    The other iteration tag provided by JSTL.

    Tag takes in a String and parses them into tokens based ona given delimiter.

    All of the attributes of the forEach tag are shared by this tag,with an addition:

    delims: Defines the delimiter to be used when parsing the targetString into tokens

    The items attribute now has a new purpose for this tag it

    defines the String that will be tokenized.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    35/49

    35Web Programming

    Sample JSP

    ...

    ${item}

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    36/49

    36Web Programming

    Output of Sample JSP

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    37/49

    Conditionals

    37Web Programming

    Mimic the funtionality provided by standard if, else-if, ...statements that can be found in standard Java.

    Usage of this tags over standard Java statements lead tocleaner code.

    Two main sets of conditionals:

    the tag that mimics a simple Java if statement.

    the tag along with the related tags and, that altogether mimic the functionality of a switchstatement.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    38/49

    38Web Programming

    Allows execution of the contents of its body if the value ofthe evaluated expression in its test attribute is equal to true.If the expression is evaluated to be false, the body is neverexecuted.

    Example:

    You are not currently logged in! Please correct before continuing any further.

    h h

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    39/49

    , ,

    39Web Programming

    These three tags work together to provide switchfunctionality within our application.

    Basically, one or more when tags are placed in the body ofa choose tag.

    The choose tag evaluates each of the test attributes of the whentags and executes the body of the when tag which evaluates to true.

    If there are no when tags that successfully match, choose calls onthe otherwise tag, if included.

    h h

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    40/49

    , ,

    40Web Programming

    Example:

    Outstanding!Good!Failed!

    Congratulations ...

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    41/49

    URL Manipulation

    41Web Programming

    JSTL provides a few custom tags that provides basic URLmanipulation capabilities.

    These tags build and improve upon actions alreadyavailable to JSPs:

    import

    param

    url

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    42/49

    42Web Programming

    Works in the same way as the JSP include action, onlybetter.

    The JSP include action allowed only pages inside the webapplication to be referenced and included within the current page's

    content. The tag allows developers to specify absolute URLs

    pointing to external resources.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    43/49

    43Web Programming

    The attribute to use for this tag is:

    url: The value of the URL to import, which can either be:

    A relative URL, pointing to a resource within the web application

    An absolute URL, capable of pointing to external resources

    Contains a number of other attributes. However, they areused for programmatic modification of the contents of theincluded resource, something that could be better doneoutside of the JSP.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    44/49

    44

    Web Programming

    A versatile tag used in conjunction with a number of othertags within the URL manipulation group.

    Cannot be used on its own, but only as a child tag of othertags available in JSTL.

    Used to provide a way to include request parameters andvalues within a URL.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    45/49

    45

    Web Programming

    The attributes used for this tag are:

    name: Used to indicate the name of the request parameter.

    value: Used to indicate the value of the request parameter.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    46/49

    46

    Web Programming

    Example:

    If we want to include a dynamic resource that needed values forrequest parameters, it should look like the snippet presented above.

    However, the problem with the above example is that it does nottake into account URL encoding rules.

    One rule for encoding URLs is that spaces must be denoted using specialcharacters.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    47/49

    47

    Web Programming

    Example:

    The tag is able to abstract those encoding rules for us.Instead of worrying about how to rewrite the URL such that it iscompliant with encoding rules, we could simply say:

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    48/49

    48

    Web Programming

    Used to provide a way to automatically reencode a URL withthe information necessary to support sessions.

    Relevant attribute:

    value: The URL to be processed.

    For clarification, this tag does NOT always reencode theURLs. It only does so when it detects that the client browserdoes not support cookies.

    Like the import tag, this tag can have zero to many

    tags for parameter inclusion.

  • 8/3/2019 MELJUN_CORTES_JEDI Slides Web Programming Chapter06 Advanced JSPs

    49/49

    49

    Web Programming

    Example:

    Click here to enter the application.