one of the best and most flexible options is the mvc …yozbek/isyg250/el_tags_jstl.pdf ·...

17
3/16/2009 1 As discussed in the previous lectures, you have many options when it comes to generating dynamic content inside the JSP page. These options are as follows: Motivating EL Usage One of the best and most flexible options is the MVC approach. In that approach, 1. a servlet responds to the request; 2. invokes the appropriate business logic or data access code; 3. places the resultant data in beans; 4. stores the beans in the request, session, or servlet context; 5. and forwards the request to a JSP page to present the result.

Upload: dothuan

Post on 28-Aug-2018

214 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

1

As discussed in the previous lectures, you have many options when it comes to generating dynamic content inside the JSP page. These options are as follows:

Motivating EL Usage

• One of the best and most flexible options is

the MVC approach.

• In that approach,

1. a servlet responds to the request;

2. invokes the appropriate business logic or data access code;

3. places the resultant data in beans;

4. stores the beans in the request, session, or servlet context;

5. and forwards the request to a JSP page to present the result.

Page 2: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

2

• The one inconvenient part about this approach is the final step:

– presenting the results in the JSP page.

• You normally use jsp:useBean and jsp:getProperty, but these elements are a bit verbose and clumsy.

• Furthermore, jsp:getProperty only supports access to simple bean properties; if the property is a collection or another bean, accessing the “subproperties” requires you to use complex Java syntax (precisely the thing you are often trying to avoid when using the MVC approach).

The JSP 2.0 expression language lets you simplify the presentation layer

• by replacing hard-to-maintain Java scripting elements or clumsy jsp:useBean and jsp:getProperty elements with short and readable entries of the following form.

${expression}

Page 3: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

3

In particular, the expresion language supports the following capabilities.

1. Concise access to stored objects.

To output a “scoped variable” named saleItem,

you use ${saleItem}

2. Shorthand notation for bean properties.

To output the companyName property (i.e., result of the getCompanyName method) of a scoped variable named company,

you use ${company.companyName}.

To access the firstName property of the president property of a scoped variable named company,

you use ${company.president.firstName}.

3. Simple access to collection elements.

To access an element of an array, List, or Map,

you use ${variable[indexOrKey]}.

4. Simple access to request parameters, cookies, and other request data.

To access the standard types of request data, you can use one of several predefined implicit objects.

5. A Small but useful set of simple operators.

To manipulate objects within EL expressons, you can use any of several arithmetic, relational, logical, or empty testing operators.

6. Conditional output.

To choose among output options, you can use ${test ? option1 : option2}

7. Automatic type conversion.

The EL removes the need for most typecasts and for much of the code that parses strings as numbers

8. Empty values instead of error messages.

In most cases, missing values or NullPointerExceptions result in empty strings, not thrown exceptions.

Invoking the Expression Language

• In JSP 2.0, you invoke the expression language with elements of the following form.

${expression}

• These EL elements can appear in ordinary text or in JSP tag attributes, provided that those attributes permit regular JSP expressions. For example:

<UL>

<LI>Name: ${expression1}

<LI>Address: ${expression2}

</UL>

<jsp:include page="${expression3}" />

• When you use the expression language in tag attributes, you can use multiple expressions (possibly intermixed with static text) and the results are coerced to strings and concatenated. For example:

<jsp:include page="${expr1}blah${expr2}" />

Page 4: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

4

• First, we will illustrate the use of expression

language elements in ordinary text.

• Then, we will illustrate the use of EL elements

in attributes of tags that you write and tags

that are provided by the JSP Standard Tag

Library (JSTL) and JavaServer Faces (JSF)

libraries.

Accessing Scoped Variables

• When you use the MVC approach, a servlet invokes code that creates the data, then uses RequestDispatcher.forward or response.sendRedirect to transfer control to the appropriate JSP page.

• To permit the JSP page to access the data, the servlet needs to use setAttribute to store the data in one of the standard locations:the HttpServletRequestthe HttpSession,the ServletContext.

• Objects in these locations are known as “scoped variables,” and the expression language has a quick and easy way to access them.

• You can also have scoped variables stored in the PageContext object, but this is much less useful because the servlet and the JSP page do not share PageContext objects. So, page-scoped variables apply only to objects stored earlier in the same JSP page, not to objects stored by a servlet.

Page 5: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

5

• To output a scoped variable, you simply use its name in an expression language element. For example,

${name}

means to search the PageContext, HttpServletRequest, HttpSession, and ServletContext (in that order) for an attribute named name.

• If the attribute is found, its toString method is called and that result is returned.

• If nothing is found, an empty string (not null or an error message) is returned.

• So, for example, the following two expressions are equivalent.

${name}

<%= pageContext.findAttribute("name") %>

• The problems with the latter approach are that it is verbose and it requires explicit Java syntax.

• It is possible to eliminate the Java syntax, but doing so requires the following even more verbose jsp:useBean code.

<jsp:useBean id="name" type="somePackage.SomeClass" scope="...">

<%= name %>

• Besides, with jsp:useBean, you have to know which scope the servlet used, and you have to know the fully qualified class name of the attribute. This is a significant inconvenience, especially when the JSP page author is someone other than the servlet author.

An Example

• To illustrate access to scoped variables, the ScopedVars servlet stores a String in the HttpServletRequest, another String in the HttpSession, and another String in the ServletContext.

• The servlet forwards the request to a JSP page that uses ${attributeName} to access and output the objects.

Page 6: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

6

Let’s use the Expression Language in the Following Web Application

http://www.coe.neu.edu/~yozbek/isyg250/scope.zip

Accessing Bean Properties

• When you simply use ${name}, the system finds the object named name, coerces it to a String, and returns it.

• Although this behavior is convenient, you rarely want to output the actual object that the MVC

servlet stored.

• Rather, you typically want to output individual properties of that object.

• The JSP expression language provides a simple but very powerful dot notation for accessing bean properties.

To return the firstName property of a scoped variable named customer, you use ${customer.firstName}.

• So, assuming the object is of type NameBean and that NameBean is in the myservlets package, to do the same thing with explicit Java syntax, you would have to replace

${customer.firstName}

with

<%@ page import=“myservlets.NameBean" %>

<%

NameBean person = (NameBean)pageContext.findAttribute("customer");

%>

<%= person.getFirstName() %>

Page 7: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

7

Accessing Collections

• The EL lets you access different types of collections in the same way: using array notation.

For instance, if attributeName is a scoped variable referring to an array, List, or Map, you access an entry in the collection with the following:

${attributeName[entryName]}

• If the scoped variable is an array, the entry name is the index and the value is obtained with theArray[index]. For example, if customerNames refers to an array of strings,

${customerNames[0]}

would output the first entry in the array.

• If the scoped variable is an object that implements the List interface, the entry name is the index and the value is obtained with theList.get(index).

For example, if supplierNames refers to an ArrayList,

${supplierNames[0]}

would output the first entry in the ArrayList.

• If the scoped variable is an object that implements the Map interface, the entry name is the key and the value is obtained with theMap.get(key). For example, if stateCapitals refers to a HashMap whose keys are U.S. state names and whose values are city names,

${stateCapitals["maryland"]}

would return "annapolis". If the Map key is of a form that would be legal as a Java variable name, you can replace the array notation with dot notation. So, the previous example could also be written as:

${stateCapitals.maryland}

Page 8: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

8

Referencing Implicit Objects

• In most cases, you use the JSP expression language in conjunction with the Model- View-Controller architecture in which the servlet creates the data and the JSP page presents the data.

• In such a scenario, the JSP page is usually only interested in the objects that the servlet created, and the general bean-access and collection-access mechanisms are sufficient.

• However, the expression language is not restricted to use in the MVC approach; the expression language can be used in any JSP page.

• To make this capability useful, the specification defines the following implicit objects.

1. pageContext

2. param and paramValues

3. cookie

4. pageScope, requestScope, sessionScope, and applicationScope

5. header and headerValues

Page 9: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

9

An Example

Custom Tags• As discussed in the previous lectures, there are many options to generate dynamic content inside the JSP page.

– Scripting elements

– Beans

– Servlet/JSP combo (MVC)

– JSP Expression Language

– Custom tags

• The options at the top of the list are much simpler to use and are just as legitimate as the options at the bottom of the list. However industry has adopted a best practice to avoid placing Java code inside the JSP page. This best practice stems from it being much harder to debug and maintain Java code inside the JSP page.

• In addition, JSP pages should concentrate only on the presentation logic. Introducing Java code into the JSP page tends to divert its purpose and, inevitably, business logic starts to creep in. To enforce this best practice, version 2.4 of the servlet specification went so far as to provide a way to disable any type of JSP scripting for a group of JSP pages.

• That said, there are cases where the presentation logic itself is quite complex and using the non-Java code options in the JSP page to express that logic becomes either too clunky and unreadable or, sometimes, just impossible to achieve.

• This is where logic through the familiar HTML-like structures. The new SimpleTag API was introduced in version 2.4 of the servlet specification and it is very easy to use in comparison to its predecessor, now known as the classic tag API.

• Although, the SimpleTag API completely replaces the classic tag API, you should keep in mind that it works only in containers compliant with servlet specification 2.4 and above.

Page 10: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

10

Tag Library Components• To use custom JSP tags, you need to define three separate components:

1. The tag handler class that defines the tag's behavior

2. The TLD file that maps the XML element names to the tag implementations

3. The JSP file that uses the tag library

1. TagHandler Class• When defining a new tag, your first task is to define a Java class that tells the system what

to do when it sees the tag.

• This class must implement the SimpleTag interface. In practice, you extend SimpleTag Support, which implements the SimpleTag interface and supplies standard implementations for some of its methods.

• javax.servlet.jsp.tagext.SimpleTagSupport

A base class for defining tag handlers implementing SimpleTag. The SimpleTagSupportclass is a utility class intended to be used as the base class for new simple tag handlers. The SimpleTagSupport class implements the SimpleTag interface and adds additional convenience methods including getter methods for the properties in SimpleTag.

• javax.servlet.jsp.tagext.SimpleTag

Interface for defining Simple Tag Handlers.

Simple Tag Handlers differ from Classic Tag Handlers in that instead of supporting

doStartTag() and doEndTag(), the SimpleTag interface provides a simple doTag() method, which is called once and only once for any given tag invocation. All tag logic, iteration, body evaluations, etc. are to be performed in this single method. Thus, simple tag handlers have the equivalent power of BodyTag, but with a much simpler lifecycle and interface.

Page 11: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

11

SimpleTag Lifecycle

1. A new tag handler instance is created each time by the container by calling the provided zero-args constructor. Unlike classic tag handlers, simple tag handlers are never cached and reused by the JSP container.

2. The setJspContext() and setParent() methods are called by the container. The setParent() method is only called if the element is nested within another tag invocation.

3. The setters for each attribute defined for this tag are called by the container.

4. If a body exists, the setJspBody() method is called by the container to set the body of this tag, as a JspFragment. If the action element is empty in the page, this method is not called at all.

5. The doTag() method is called by the container. All tag logic, iteration, body evaluations, etc. occur in this method.

6. The doTag() method returns and all variables are synchronized.

Page 12: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

12

2. TLD File• Once you have defined a tag handler, your next task is to identify this class to the server and to associate it with a

particular XML tag name. • This task is accomplished by means of a TLD file in XML format.

<taglib . . .><tag><name>hello</name><tag-class>com.yusuf.MyHelloTag</tag-class><body-content>empty</body-content></tag></taglib>

description: This optional element allows the developer to document the purpose of the custom tagname: This required element defines the name of the tag as it will be referred to by the JSP pagetag-class: This required element identifies the fully qualified name of the implementing tag handler classbody-content: This required element tells the container how to treat the content between the opening and closing tags if any.

The value can be either empty, scriptless, tagdependent, or JSP.

1. empty means that no content is allowed to appear in the body of the tag. This would mean that the declared tag can only appear as <prefix:tag></prefix:tag> without any spaces between the opening and closing tags. or <prefix:tag/>2. scriptless means that the tag body is allowed to have JSP content as long as it doesn’t contain any scripting elements like <%…%> or <%=…%>. If present, the body of the tag would be processed just like any other JSP content.3. tagdependentmeans that the tag is allowed to have any type of content as its body. It is up to the developer of the tag handler to get access to that content and do something with it. For example, if you want to execute a SQL statement, providing that the SQL in the body of the tag, you would use tagdependent as the value of the body-content element.4. JSP value is provided for backward compatibility with the classic custom tag model. It is not a legal value when used with the SimpleTag.

3. JSP File that makes use of the tag

Page 13: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

13

JSTL• It’s easy to see why the standard JSP actions and JSP EL are usually not powerful

enough when it comes to implementing a complex presentation logic.

• They lack basic features such as looping and storing scoped variables, and they have limited conditional logic, among many others.

• However, the ability to create custom tags and functions more than compensates for this drawback.

• However, it would be a terrible waste of time for every developer to have to write his or her own if tags, for loop tags, and so on. This is where the JSP Standard Tag Library (JSTL) comes to the rescue.

• JSTL provides many useful tag libraries and has been universally excepted by the Java community, so much so that it became its own specification.

The most commonly used JSTL tag library is the core library.

• It contains the following tags:

– out,

– if,

– forEach,

– forTokens,

– choose,

– when,

– otherwise,

– set,

– remove,

– import,

– url,

– param,

– redirect, and

– catch.

Page 14: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

14

Installation of JSTL• Because JSTL is a specification, more than one implementation of this specification

is possible. Apache Foundation’s Jakarta Taglibs project provides a very popular implementation of JSTL

1. Download JSTL. You can download the implementation by following this URL: http://jakarta.apache.org/taglibs

2. Unzip it to a directory.

3. Copy standard.jar and jstl.jar into the WEB-INF/lib of your application.

4. Import the library into your JSP page with the taglib directive.

<%@ taglib prefix="c“ uri="http://java.sun.com/jsp/jstl/core" %>

Using JSTL

Page 15: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

15

Page 16: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

16

An example – Use JSTL to display ArrayList

Page 17: One of the best and most flexible options is the MVC …yozbek/isyg250/el_tags_jstl.pdf · Model-View-Controller architecture in which the servlet creates the data and the ... –

3/16/2009

17