JSP Syntax

There are six basic types of JSP tag elements. Table 14-3 defines each of the elements. Notice that all of the elements except the action type are enclosed in <% and %>.

Table 14-3: The Six JSP Tag Element Types

Tag Type

Description

Syntax

Action

Used to provide request time instructions to the JSP container.

<jsp:actionName attributes />

Comment

Used to place comments in your JSPs. Comments are not sent to the client in the output.

<%-- This is a comment! --%>

Declaration

Used to declare and define methods and variables that are shared by all JSP requests .

<%! Any Java delcaration %>

Directive

Used to specify translation time instructions to the JSP compiler.

<%@ Any Java directive %>

Expression

Used as a shortcut for printing values.

<%= Any Java expression %>

Scriptlets

Used to include inline Java code in our JSPs.

<% Java code; %>

JSP Directives

The first tag type we will discuss is the directive. All directives in a JSP are defined with the syntax:

 <%@ directive-name   attribute-list %> 

There are three types of JSP directives available: page, include, and taglib.

Page Directives

The page directive allows us to communicate properties at translation time. They let us specify which Java classes will be needed on the page and if a page must take part in a session. The following list describes the available page directive attributes:

  • autoFlush Can be set to true or false. When it is set to true, the buffer should be flushed when it is full.

    • autoFlush= true is the default.

  • buffer The size of the page buffer.

  • contentType The MIME type and character encoding of the output of the JSPs.

  • errorPage A relative URL to a JSP that used to handle errors for this page.

    • errorPage= error.jsp

    • This is not set by default.

  • extends The class that this JSP will extend.

    • The class must implement the javax.servlet.jsp.JspPage interface.

  • import A comma separated list of classes and packages that are to be imported. The following packages are imported by default:

    • java.lang.*

    • javax.servlet.*

    • javax.servlet.jsp.*

    • javax.servlet.http.*

  • info Informational text about this JSP.

  • isErrorPage Set to true if this page is a error handling page.

  • isThreadSafe Set to true if the JSP is thread safe and set to false if the page is not thread safe.

  • language The only valid value is java (JSP 1.2).

  • pageEncoding The character encoding of the JSP.

  • session Set to true if the page takes part in an HTTP session.

A typical page directive that sets the page s content type and imports the java.io and java.util packages might look like the following:

 <%@ page contentType="text/html;charset=windows-1252"                     import="java.io.*, java.util.*" %> 

Include Directive

The second type of directive is the include directive. This directive allows developers to include files in JSPs at translation time. This means that the contents of the included file are included when the JSP is translated into a servlet. The included file will be inserted at the point in the JSP where it is declared. The file attribute is used to specify the file that will be included. The value of the file attribute must be a valid relative URL. You cannot use run-time expressions for the file URL. The following example includes a JSP header and an HTML footer. The body of the page will be included between the include directives:

 <%@ include file="header.jsp" %>       [BODY OF PAGE HERE]. <%@ include file="footer.html" %> 

When including files, you must remember that the included files may contain HTML tags that can cause a conflict. For example, suppose the header and the JSP that is including it both contain <html> tags. Since you can only have exactly one open and one close <html> tag in a valid HTML document, the page would not render correctly. For the preceding example to render correctly, you would have to have the open <html> tag in the header and the close </html> tag in the footer.

Taglib Directive

The third directive is the taglib directive. This directive tells the JSP engine that a tag library is going to be used. The syntax for the taglib directive is covered in the Tag Libraries section later in this chapter.

The Expression Tag Syntax

 <%= %> 

allows us to place Java expressions in our JSPs. For example, if we wanted to dynamically set the value of an HTML form field, we could do the following:

 <input type="text" name="favoriteCar"             value=<%= request.getAttribute("myFavoriteCar ") %>> 

This would draw a text field and populate it with the current value that the request parameter named myFavoriteCar is set to.

Declaration Elements

The declaration element:

 <!% %> 

allows us to declare variables and methods in our JSPs. The variables we declare are shared among all JSP requests, so you will not want to store elements that are tied to a request or session in a declaration. For example, if you stored your user information in a variable that was declared in a declaration, you will have issues with users suddenly seeing another users information. User information is best stored in the session scope. The various JSP scopes are discussed earlier in this chapter, in the section JSP Scopes. Any valid Java declaration is valid inside the declaration tags. The example below is a simple example:

 <%!      int requestCount = 0;      public boolean isSet(String value) {                         boolean valSet = false;           if(value != null && !"".equals(value)) {                valSet = true;           }                         return valSet;      } %> 

Scriptlet Tags

The scriptlet JSP tag:

 <% %> 

is used to put Java code inline in our JSPs. While this is not desirable, as it increases page complexity, sometimes it is necessary. Most of the time, scriptlets can be eliminated by using tag libraries, JavaBeans, and the JSP Expression language. The following example is a loop that creates a simple select form element for a list of years ten years in the past and five years into the future.

 <select name="years"> <%       // build the option list for select      int curYear = 2004;      for(int cnt=curYear-10; cnt < curYear+5; cnt++) { %>           <option value="<%= cnt %>">                <%= cnt %>           </option> <%                          } %> </select> 
Tip  

You can use // inside scriptlets for comments just as you can in Java.

Comment Tags

Comments in JSPs can be done two ways: comments that reach the client and hidden comments. The standard HTML comment can be used in JSPs but they will reach the client. Also, if any JSP tags are inside the comments, they will still be evaluated. To comment out JSP tags, you can use the comment tag:

 <% your comment text %> 

The following example comments out a tag and places another descriptive comment in the JSP. The tag will be ignored by the JSP engine, and the comment will not reach the client:

 ... <% BJG: removed functionality as per change request 1312934 %> <%  <hr:displaySchedule startDate="${param.startDate}"/> %>   ... 

Action Directives

We have saved JSP actions for last, as they are the most useful and complex. There are six standard JSP actions and an unlimited number of custom actions. The six standard JSP actions are: useBean, getProperty, setProperty, include, forward, and plugin. All actions use the jsp: prefix and have a tag-like syntax.

The useBean Action

The <jsp:useBean> allows for the creation and access of JavaBeans located in one of the JSP scopes. A JavaBean can be placed in the page, request, session, and application scopes. The following example retrieves a JavaBean from the session that represents a user:

 <jsp:useBean id="userBean" class="mypackage.UserBean" scope="session" /> 
Note  

A JavaBean is a reusable component that can be used in any Java application development environment. JavaBeans are dropped into an application container, such as a form, and can perform functions ranging from a simple animation to complex calculations.

The id property represents the handle that will be used to refer to the user JavaBean later in the JSPs. The class property tells the JSP engine what class to use and the scope property tells us which bean should be in the session scope.

Since the UserBean class has a no argument default constructor and public accessor methods, we can use the <jsp:setProperty> and <jsp:getProperty> actions to access and mutate the values contained in the bean. The following code sets the users color preferences and displays their usernames:

 <jsp:useBean id="userBean" class="mypackage.UserBean" scope="session" /> <jsp:setProperty name="userBean" property="colorPref" param="colorPref"/> <font color=<jsp:getProperty name="userBean" property="colorPref"/>> <jsp:getProperty name="userBean" property="username"/> </font> 

The param property on the setProperty tag tells the JSP engine to load the beans property with the request parameter colorPref. This parameter would have been set most likely on a preceding form. Another great feature of the setProperty action is that you can populate the entire bean in one line. The following example sets the userBean from the request parameters:

 <jsp:setProperty name="userBean" property="*"/> 

If there is a parameter in the request that matches the name of any of the bean s properties, the JSP engine will update the userBean with the new values. If, for some reason, one of the bean s properties is not in the request, the value will be unchanged. Also, if a request parameter has more than one value, then only the first value is used. As you can see, the useBean action is very handy.

The include Action

The <jsp:include> action is similar to the include directive in that it forces the JSPs to include content from another JSPs. The include action is, however, evaluated at run time. This means you can dynamically include JSPs. Let s consider a user customization feature where the end user chooses from a list of pages to display as their page header. The JSPs can dynamically include one of many pages based on a user s preference. The following code will change the header and footer to match the user s preference:

 <jsp:useBean name="userPrefs" scope="session" class="mypackage.UserPrefsBean"/> <jsp:include page="<jsp:getProperty name="userPrefs" property="headerPage"/> . [PAGE_BODY] <jsp:include page=<jsp:getProperty name="userPrefs" property="footerPage"/>/> 

The page properties of the include actions are dynamically set using the values from the user s preferences object. The value that the page property is set to must be a relative URL to the included page and it must exist.

The forward Action

The <jsp:forward> tag forwards a request to a new JSP immediately when the action is encountered . The JSP forward tag requires that nothing has been sent back to the client s browser. The page forwarded to should handle this, as control is never returned to the forwarding page.

The plugin Action

Another JSP action is the <jsp:plugin>, which provides a mechanism to include client side JavaBeans or applets.



Oracle Application Server 10g Web Development
Oracle Application Server 10g Web Development (Oracle Press)
ISBN: 0072255110
EAN: 2147483647
Year: 2004
Pages: 192

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net