Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | jsp:useBean Action - JavaServer Pages (JSP) Standard Actions

Chapter: Internet & World Wide Web HOW TO PROGRAM - JavaServer Pages (JSP): Bonus for Java™ Developers

| Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail |

jsp:useBean Action - JavaServer Pages (JSP) Standard Actions

This action creates a Java object or locates an existing object for use in the JSP.

Standard Actions


We continue our JSP discussion with the JSP standard actions (Fig. 31.5). These actions provide JSP implementors with access to several of the most common tasks performed in a JSP, such as including content from other resources, forwarding requests to other resourc-es and interacting with JavaBeans. JSP containers process actions at request time. Actions are delimited by <jsp:action>and </jsp:action>, where action is the standard action name. In cases where nothing appears between the starting and ending tags, the XML emp-ty element syntax <jsp:action /> can be used. Figure 31.5 summarizes the JSP standard actions. We use the actions in the next several subsections.


4. <jsp:useBean> Action


Action <jsp:useBean> enables a JSP to manipulate a Java object. This action creates a Java object or locates an existing object for use in the JSP. Figure 31.16 summarizes action <jsp:useBean>’s attributes. If attributes class and beanName are not spec-ified, the JSP container attempts to locate an existing object of the type specified in at-tribute type. Like JSP implicit objects, objects specified with action <jsp:useBean> have pagerequestsession or application scope that indicates where they can be used in a Web application. Objects with page scope are accessible only to the page in which they are defined. Multiple JSP pages potentially can access objects with other scopes. For example, all JSPs that process a single request can access an object with request scope.

Many Web sites today place rotating advertisements on their Web pages. Each visit to one of these pages typically results in a different advertisement being displayed in the user’s Web browser. Typically, clicking an advertisement takes you to the Web site of the company that placed the advertisement. Our first example of <jsp:useBean> demonstrates a simple advertisement rotator bean that cycles through a list of five advertisements. In this example, the advertisements are covers for some of our books. Clicking a cover takes you to the Amazon.com Web site where you can read about and possibly order the book.


The Rotator bean (Fig. 31.17) has three methods: getImagegetLink and nextAd. Method getImage returns the image file name for the book cover image. Method getLink returns the hyperlink to the book at Amazon.com. Method nextAd updates the Rotator so the next calls to getImage and getLink return information for a different advertisement. Methods getImage and getLink each represent a read-only JavaBean property—image and link, respectively. Rotator keeps track of the current advertise-ment with its selectedIndex variable, which is updated by invoking method nextAd.


    // Fig. 10.17: Rotator.java

    // A JavaBean that rotates advertisements.

    package com.deitel.advjhtp1.jsp.beans;

    public class Rotator {

    private String images[] = { "images/jhtp3.jpg",

    "images/xmlhtp1.jpg", "images/ebechtp1.jpg",

"images/iw3htp1.jpg", "images/cpphtp3.jpg" };

private String links[] = {

"http://www.amazon.com/exec/obidos/ASIN/0130125075/" +


"http://www.amazon.com/exec/obidos/ASIN/0130284173/" +


"http://www.amazon.com/exec/obidos/ASIN/013028419X/" +


"http://www.amazon.com/exec/obidos/ASIN/0130161438/" +


"http://www.amazon.com/exec/obidos/ASIN/0130895717/" +

             "deitelassociatin" };


             private int selectedIndex = 0;

      // returns image file name for current ad

      public String getImage()


      return images[ selectedIndex ];


      // returns the URL for ad's corresponding Web site

      public String getLink()


      return links[ selectedIndex ];


      // update selectedIndex so next calls to getImage and

      // getLink return a different advertisement

      public void nextAd()


      selectedIndex = ( selectedIndex + 1 ) % images.length;





Fig. 31.17  Rotator bean that maintains a set of advertisements



Lines 7–8 of JavaServer Page adrotator.jsp (Fig. 31.18) obtain a reference to an instance of class Rotator. The id for the bean is rotator. The JSP uses this name to manipulate the bean. The scope of the object is session, so that each individual client will see the same sequence of ads during their browsing session. When adro-tator.jsp receives a request from a new client, the JSP container creates the bean and stores it in JSP that client’s session (an HttpSession object). In each request to this JSP, line 22 uses the rotator reference created in line 7 to invoke the Rotator bean’s nextAd method. Thus, each request will receive the next advertisement maintained by the Rotator bean. Lines 29–34 define a hyperlink to the Amazon.com site for a partic-ular book. Lines 29–30 introduce action <jsp:getProperty> to obtain the value of the Rotator bean’s link property. Action <jsp:getProperty> has two attributes—name and property—that specify the bean object to manipulate and the property to get. If the JavaBean object uses standard JavaBean naming conventions, the method used to obtain the link property value from the bean should be getLink. Action <jsp:getProperty> invokes getLink on the bean referenced with rotator, converts the return value into a String and outputs the String as part of the response to the client. The link property becomes the value of the hyperlink’s href attribute. The hyperlink is represented in the resulting Web page as the book cover image. Lines 32–33 create an img element and use another <jsp:getProperty> action to obtain the Rotator bean’s image property value.


    <?xml version = "1.0"?>

    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"



    <!-- Fig. 10.18: adrotator.jsp -->


    <jsp:useBean id = "rotator" scope = "application"

    class = "com.deitel.advjhtp1.jsp.beans.Rotator" />


      <html xmlns = "http://www.w3.org/1999/xhtml">



<title>AdRotator Example</title>


             <style type = "text/css">     

             .big { font-family: helvetica, arial, sans-serif;

             font-weight: bold;   

             font-size: 2em }       



             <%-- update advertisement --%>

             <% rotator.nextAd(); %>




             <p class = "big">AdRotator Example</p>



             <a href = "<jsp:getProperty name = "rotator"

             property = "link" />">


             <img src = "<jsp:getProperty name = "rotator"

             property = "image" />" alt = "advertisement" />








Fig. 31.18 JSP adrotator.jsp uses a Rotator bean to display a different advertisement on each request to the page



Note that the link and image properties also can be obtained with JSP expressions. For example, the <jsp:getProperty> action in lines 29–30 can be replaced with the expression


<%= rotator.getLink() %>


Similarly, the <jsp:getProperty> action in lines 32–33 can be replaced with the ex-pression


<%= rotator.getImage() %>


To test adrotator.jsp in Tomcat, copy adrotator.jsp into the jsp directory created in Section 31.3. You should have copied the images directory into the jsp direc-tory when you tested Fig. 31.10. If not, you must copy the images directory there now. Copy Rotator.class into the advjhtp1 Web application’s WEB-INF\classes directory in Tomcat. [Note: This example will work only if the proper package directory structure for Rotator is defined in the classes directory. Rotator is defined in package com.deitel.advjhtp1.jsp.beans.] Open your Web browser and enter the following URL to test adrotator.jsp:




Try reloading this JSP several times in your browser to see the advertisement change with each request.


Action <jsp:setProperty> can set JavaBean property values. This action is particularly useful for mapping request parameter values to JavaBean properties. Request parameters can be used to set properties of primitive types boolean, byte, char, int, long, float and double and java.lang types String, Boolean, Byte, Character, Integer, Long, Float and Double. Figure 31.19 summarizes the

<jsp:setProperty> attributes.



Our next example is a guest book that enables users to place their first name, last name and e-mail address into a guest book database. After submitting their information, users see a Web page containing all the users in the guest book. Each person’s e-mail address is dis-played as a hyperlink that allows the user to send an e-mail message to the person. The example demonstrates action <jsp:setProperty>. In addition, the example intro-duces the JSP page directive and JSP error pages.

The  guest  book  example  consists  of  JavaBeans  GuestBean (Fig. 31.20)  and


GuestDataBean (Fig. 31.21), and JSPs guestBookLogin.jsp (Fig. 31.22), guestBookView.jsp (Fig. 31.23) and guestBookErrorPage.jsp (Fig. 31.24). Sample outputs from this example are shown in Fig. 31.25.


JavaBean GuestBean (Fig. 31.20) defines three guest properties: firstName, lastName and email. Each is a read/write property with set and get methods to manip-ulate the property.


Study Material, Lecturing Notes, Assignment, Reference, Wiki description explanation, brief detail

Copyright © 2018-2020 BrainKart.com; All Rights Reserved. Developed by Therithal info, Chennai.