Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Session Tracking with the SessionBean Object - JavaServer

Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Server Technologies - JavaServer™ Faces Web Applications

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

Session Tracking with the SessionBean Object - JavaServer

You can also perform session tracking with the SessionBean class that is provided in each web application created with Netbeans.

Session Tracking with the SessionBean Object

 

You can also perform session tracking with the SessionBean class that is provided in each web application created with Netbeans. When a web page in the project is requested, a SessionBean object is created. Properties of this object can be accessed throughout a browser session by invoking the method getSessionBean on the page bean. To demon-strate session-tracking techniques using the SessionBean, we modified the page bean files in Figs. 26.19 and 26.21 so that they use the SessionBean to store the user’s selected languages. We begin with the updated Options.jsp file (Fig. 26.23). Figure 26.26 pre-sents the SessionBean.java file, and Fig. 26.27 presents the modified page bean file for

Options.jsp.

 

The Options.jsp file in Fig. 26.23 is similar to that presented in Fig. 26.17 for the cookies example. Lines 40–48 define two webuijsf:staticText elements that were not present in the cookies example. The first element displays the text "Number of selections so far:". The second element’s text attribute is bound to property numSelections in the SessionBean (line 48). We discuss how to bind the text attribute to a SessionBean prop-erty momentarily.

 

1          <?xml version = "1.0" encoding = "UTF-8"?>

 

2

3          <!-- Fig. 26.23: Options.jsp -->

 

4          <!-- JSP file that allows the user to select a programming language -->

 

5          <jsp:root version = "1.2"

 

6          xmlns:f = "http://java.sun.com/jsf/core"

 

7          xmlns:h = "http://java.sun.com/jsf/html"

 

8          xmlns:jsp = "http://java.sun.com/JSP/Page"

 

9          xmlns:webuijsf = "http://www.sun.com/webui/webuijsf">

 

10        <jsp:directive.page contentType = "text/html;charset=UTF-8"

 

11        pageEncoding = "UTF-8"/>

 

12        <f:view>

 

13        <webuijsf:page binding = "#{Options.page1}" id = "page1">

 

14        <webuijsf:html binding = "#{Options.html1}" id = "html1">

 

15        <webuijsf:head binding = "#{Options.head1}" id = "head1">

 

 

16        <webuijsf:link binding = "#{Options.link1}" id = "link1"

17        url = "/resources/stylesheet.css"/>

18        </webuijsf:head>

 

19        <webuijsf:body binding = "#{Options.body1}" id = "body1"

 

                       

20        style = "-rave-layout: grid">

21        <webuijsf:form binding = "#{Options.form1}" id = "form1">

22        <webuijsf:staticText binding = "#{Options.instructionText}"

23        id = "instructionText" style = "font-size: 18px;

24        left: 24px; top: 24px; position: absolute"

25        text = "Select a programming language:"/>

26        <webuijsf:radioButtonGroup binding =

27        "#{Options.languageRadioGroup}" id =

28        "languageRadioGroup" items =

29        "#{Options.languageRadioGroupDefaultOptions.options}"

30        style = "left: 24px; top: 48px; position: absolute"/>

31        <webuijsf:button actionExpression =

32        "#{Options.submitButton_action}" binding =

33        "#{Options.submitButton}" id = "submitButton" style =

34        "left: 23px; top: 192px; position: absolute;

35        width: 100px" text = "Submit"/>

36        <webuijsf:staticText binding = "#{Options.responseText}"

37        id = "responseText" rendered = "false" style =

38        "font-size: 18px; left: 24px; top: 24px;

39        position: absolute"/>

40        <webuijsf:staticText binding = "#{Options.selectionsText}"

41        id = "selectionsText" rendered = "false" style =

42        "position: absolute; left: 24px; top: 72px" text =

43        "Number of selections so far:"/>

44        <webuijsf:staticText binding =

45        "#{Options.selectionsValueText}" id =

46        "selectionsValueText" rendered = "false" style =

47        "left: 168px; top: 72px; position: absolute"

48                    text = "#{SessionBean1.numSelections}"           />

49        <webuijsf:hyperlink actionExpression =

50        "#{Options.languagesLink_action}" binding =

51        "#{Options.languagesLink}" id = "languagesLink"

52        rendered = "false" style = "left: 24px; top: 120px;

53        position: absolute"

54        text = "Click here to choose another language."/>

55        <webuijsf:hyperlink actionExpression =

56        "#{Options.recommendationsLink_action}" binding =

57        "#{Options.recommendationsLink}" id =

58        "recommendationsLink" rendered = "false" style =

59        "left: 24px; top: 144px; position: absolute"

60        text = "Click here to get book recommendations."

61        url = "/faces/Recommendations.jsp"/>

62        </webuijsf:form>

63        </webuijsf:body>

64        </webuijsf:html>

65        </webuijsf:page>

66        </f:view>

67        </jsp:root>




Fig. 26.23 | JSP file that allows the user to select a programming language

 

 

Adding Properties to the SessionBean

In this example, we use session tracking to store not only the user’s selected languages, but also the number of selections made. To store this information in the SessionBean, we add properties to the SessionBean class.

 

To add a property that will store the number of selections so far, right click the SessionBean1 node in the Outline window and select Add > Property to display the New Property Pattern dialog (Fig. 26.24). This dialog allows you to add primitive, String or primitive type-wrapper (e.g., Integer, Double) properties to the SessionBean. Add an int property named numSelections and click OK to accept the default settings for this prop-erty. Open the SessionBean file, and at the bottom of the source code you’ll see a new property definition, a get method and set method for numSelections.

 

Property numSelections is manipulated in the page bean file to store the number of languages the user selected. To display the value of this property in the selectionsValue-Text element in the JSP file, right click the element in the Outline window and select Bind to Data…. In the Bind to Data dialog (Fig. 26.25), select the Bind to an Object tab, locate property numSelections under the SessionBean1 node and click OK. The Static Text ele-ment will now always display the value of SessionBean1’s numSelections property. If the





property’s value changes, the text changes as well, so that you need not programmatically set the text in the page bean file.

 

Now that we’ve added a property to store the number of selections in the SessionBean1, we must add a second property to store the selections themselves. We’d like to store selections as key/value pairs of the selected language and the ISBN number of a related book, similar to the way selections were stored using cookies. To do this, we add a Properties object named selectedLanguages to the SessionBean. We manually added this property to the SessionBean file, but you can add it using the New Property dialog in Fig. 26.24. Simply type java.util.Properties in the Type drop-down list’s field, con-figure the property and click OK. The modified SessionBean file (after the two properties have been added) is displayed in Fig. 26.26.


1    // Fig. 26.26: SessionBean.java

 

2    // SessionBean file for storing language selections.

 

3    package sessiontrackingsessions;

4

5    import com.sun.rave.web.ui.appbase.AbstractSessionBean;

 

6    import javax.faces.FacesException;

7

8    public class SessionBean1 extends AbstractSessionBean

9    {

 

10         // To save space, we omitted the code in lines 10-52. The complete

 

11         // source code is provided with this chapter's examples.

12

1             // holds value of property numSelections

 

2             private int numSelections;

55

7             // returns value of numSelections

 

8             public int getNumSelections()

9             {

 

10                return this.numSelections;

 

11         } // end method getNumSelections

12          

12         // sets new value of numSelections

 

13         public void setNumSelections(int numSelections)

14         {

 

15                this.numSelections = numSelections;

 

16         } // end method setNumSelections

67

20         // holds value of property selectedLanguages

 

21         private java.util.Properties selectedLanguages =

 

22                new java.util.Properties();

71

1             // returns selectedLanguages

 

2             public java.util.Properties getSelectedLanguages()

3             {

 

4                   return this.selectedLanguages;

 

5             } // end method getSelectedLanguages

77

1             // sets new value of property selectedLanguages

 

2             public void setSelectedLanguages(

 

3                   java.util.Properties selectedLanguages )

4             {

 

5                   this.selectedLanguages = selectedLanguages;

 

6             } // end method setSelectedLanguages

 

7      } // end class SessionBean1

 

Fig. 26.26 | SessionBean file for storing language selections.

 

 

Line 54 declares the numSelections property, and lines 57–60 and 63–66 declare its get and set methods, respectively. This portion of the code was generated automatically when we used the New Property dialog. Lines 69–70 define the Properties object selectedLanguages that will store user selections. Lines 73–76 and 79–83 are the get and set methods for this property.

 

Manipulating SessionBean Properties in a Page Bean File

 

The page bean file for the Options.jsp page is displayed in Fig. 26.27. Because much of this example is identical to the preceding one, we concentrate on the new features.

 

6    // Fig. 26.27: Options.java

 

7    // Page bean that stores language selections in a SessionBean property.

 

8    package sessiontrackingsessions;

4

1    import com.sun.rave.web.ui.appbase.AbstractPageBean;

 

2    import com.sun.webui.jsf.component.Body;

 

3    import com.sun.webui.jsf.component.Button;

 

4    import com.sun.webui.jsf.component.Form;

 

5    import com.sun.webui.jsf.component.Head;

 

6      import com.sun.webui.jsf.component.Html;

 

7      import com.sun.webui.jsf.component.Hyperlink;

 

8      import com.sun.webui.jsf.component.Link;

 

9      import com.sun.webui.jsf.component.Page;

 

10   import com.sun.webui.jsf.component.RadioButtonGroup;

 

11   import com.sun.webui.jsf.component.StaticText;

 

12   import com.sun.webui.jsf.model.SingleSelectOptionsList;

 

13   import java.util.Properties;

 

14   import javax.faces.FacesException;

 

15   import javax.servlet.http.Cookie;

 

16   import javax.servlet.http.HttpServletResponse;

21

5      public class Options extends AbstractPageBean

6      {

 

7             private int __placeholder;

25

1             private void _init() throws Exception

2             {

 

3                    languageRadioGroupDefaultOptions.setOptions(

 

new com.sun.webui.jsf.model.Option[] {

30        new com.sun.webui.jsf.model.Option( "Java", "Java" ),

31        new com.sun.webui.jsf.model.Option( "C++", "C++" ),

32        new com.sun.webui.jsf.model.Option( "Visual Basic 2005",

33        "Visual Basic 2005" ),

34        new com.sun.webui.jsf.model.Option( "Visual C# 2005",

35        "Visual C# 2005" ),

36        new com.sun.webui.jsf.model.Option( "Internet & Web",

37        "Internet & Web")

11                      } // end array initializer

 

12                ); // end call to setOptions

 

13         } // end method _init

41

14         // To save space, we omitted the code in lines 42-225. The complete

 

15         // source code is provided with this chapter's examples.

44

1             // Construct a new page bean instance and initialize the properties

 

2             // that map languages to ISBN numbers of recommended books.

 

3             public Options()

{

1                    // initialize the Properties object of values to be stored

 

2                    // in the session

 

3                    books.setProperty( "Java", "0132222205" );

 

4                    books.setProperty( "C++", "0136152503" );

 

5                    books.setProperty( "Visual Basic 2005", "0131869000" );

 

6                    books.setProperty( "Visual C# 2005", "0131525239" );

 

7                    books.setProperty( "Internet & Web", "0131752421" );

 

8             } // end Options constructor

238

9             // To save space, we omitted the code in lines 239-281. The complet

 

10          // source code is provided with this chapter's examples.

241

15          // Action handler for the Submit button. Checks whether a language

 

16          // was selected and, if so, registers a cookie for that language and

 

17          // sets the responseText to indicate the chosen language.

 

18          public String submitButton_action()

19          {

 

20                String msg = "Welcome to sessions!  You ";

288

23                // if the user made a selection

 

24                if ( getLanguageRadioGroup().getSelected() != null )

25                {

 

26                      String language = languageRadioGroup.getSelected().toString();

 

27                      msg += "selected " + language + ".";

294

1                          // get ISBN number of book for the given language.

 

2                          String ISBN = books.getProperty( language );

297

8                          // add the selection to the SessionBean's Properties object

 

9                           Properties selections = getSessionBean1().getSelectedLanguages();

 

10                      Object result = selections.setProperty( language, ISBN );

301

1                          // increment numSelections in the SessionBean and update

 

2                          // selectedLanguages if user has not made this selection before

3                          if ( result == null )

4                          {

 

5                                 int numSelected = getSessionBean1().getNumSelections();

 

6                                 getSessionBean1().setNumSelections( ++numSelected );

7                          } // end if

8                    } // end if

9                    else

 

10                      msg += "did not select a language.";

312

5                    responseText.setValue( msg );

 

6                    languageRadioGroup.setRendered( false );

 

7                    instructionText.setRendered( false );

 

8                    submitButton.setRendered( false );

 

9                    responseText.setRendered( true );

 

10                selectionsText.setRendered( true );

 

11                selectionsValueText.setRendered( true );

 

12                languagesLink.setRendered( true );

 

recommendationsLink.setRendered( true );

322             return null; // reloads the page

 

323      } // end method submitButton_action

324      

1             // redisplay the components for selecting a language

 

2             public String languagesLink_action()

3             {

 

4                    responseText.setRendered( false );

 

5                    selectionsText.setRendered( false );

 

6                    selectionsValueText.setRendered( false );

 

7                    languagesLink.setRendered( false );

 

8                    recommendationsLink.setRendered( false );

 

9                    languageRadioGroup.setRendered( true );

 

10                instructionText.setRendered( true );

 

11                submitButton.setRendered( true );

 

12                return null;

 

13          } // end method languagesLink_action

338

15          // forwards user to Recommendations.jsp

 

16          public String recommendationsLink_action()

17          {

 

18                return "case1";

 

19          } // end method recommendationsLink_action

 

20   } // end class Options

 

Fig. 26.27 | Page bean that stores language selections in a SessionBean property.

 

The submitButton’s action handler (lines 285–323) stores the user’s selections in the SessionBean and increments the number of selections made, if necessary. Line 299 retrieves from the SessionBean the Properties object that contains the user’s selections. Line 300 adds the current selection to the Properties object. Method setProperty returns the value previously associated with the new key, or null if this key was not already stored in the Properties object. If adding the new property returns null, then the user has made a new selection. In this case, lines 306–307 increment the numSelections prop-erty in the SessionBean. Lines 313–321 and the languaguesLink action handler (lines 326–337) control the components that are displayed, just as in the cookies examples.

 

Displaying Recommendations Based on Session Values

As in the cookies example, this application provides a link to Recommendations.jsp, which displays a list of book recommendations based on the user’s language selections. Since this JSP is identical to the version in Fig. 26.20, we show only the sample output of this page in Fig. 26.28.

 

Page Bean That Creates Book Recommendations from a SessionBean Property

 

Figure 26.29 presents the page bean for Recommendations.jsp. Again, much of it is sim-ilar to the page bean used in the cookies example. We discuss only the new features.

 


 

22// Fig. 26.29: Recommendations.java

 

23// Page bean that displays book recommendations based on a SessionBean

 

24// property.

 

25package sessiontrackingsessions;

5

1    import com.sun.rave.web.ui.appbase.AbstractPageBean;

 

2    import com.sun.webui.jsf.component.Body;

 

3    import com.sun.webui.jsf.component.Form;

 

4    import com.sun.webui.jsf.component.Head;

 

5      import com.sun.webui.jsf.component.Html;

 

6      import com.sun.webui.jsf.component.Hyperlink;

 

7      import com.sun.webui.jsf.component.Label;

 

8      import com.sun.webui.jsf.component.Link;

 

9      import com.sun.webui.jsf.component.Listbox;

 

10   import com.sun.webui.jsf.component.Page;

 

11   import com.sun.webui.jsf.model.DefaultOptionsList;

 

12   import com.sun.webui.jsf.model.Option;

 

13   import java.util.Enumeration;

 

14   import java.util.Properties;

 

15   import javax.faces.FacesException;

21

6      public class Recommendations extends AbstractPageBean

7      {

 

8             // To save space, we omitted the code in lines 24-177. The complete

 

9             // source code is provided with this chapter's examples.

26

1             // displays the book recommendations in the Listbox

 

2             public void prerender()

3             {

 

4                    // retrieve user's selections and number of selections made

 

5                    Properties languages = getSessionBean1().getSelectedLanguages();

 

Enumeration selectionsEnum = languages.propertyNames();

184     int numSelected = getSessionBean1().getNumSelections();

 

185

186     Option [] recommendations;

 

187

12                  // if at least one selection was made

13                  if ( numSelected > 0 )

14                  {

 

15                        recommendations = new Option[ numSelected ];

16           

18                        for ( int i = 0; i < numSelected; i++ )

19                        {

 

20                              String language = (String) selectionsEnum.nextElement();

 

recommendations[ i ] = new Option( language +

197      " How to Program.  ISBN#: " +                     

198      languages.getProperty( language ) );  

1                           } // end for

2                     } // end if

3                    else

4                    {

 

5                          recommendations = new Option[ 1 ];

 

6                          recommendations[ 0 ] = new Option(

 

7                                 "No recommendations. Please select a language." );

8                    } // end else

207

1                    recommendationsListbox.setItems( recommendations );

 

2             } // end method prerender

210

7             // To save space, we omitted the code in lines 211-229. The complete

 

8             // source code is provided with this chapter's examples.

213

13          // redirects user to Options.jsp

 

14          public String optionsLink_action()

15          {

 

16                return "case1"; // returns to Options.jsp

 

17          } // end method optionsLink_action

 

18   } // end class Recommendations

 

Fig. 26.29 | Displays book recommendations based on a SessionBean property.

 

Line 182 retrieves the Properties object containing the user’s selections from the SessionBean, and line 183 gets an enumeration of all of the keys in that Properties object. Line 184 retrieves the number of selections made from the SessionBean. If any selections were made, line 191 constructs an appropriately sized Option array to display the selections in the webuijsf:listBox element of Recommendations.jsp. Lines 193–199 add each of the user’s selections to this Option array. Line 195 gets the next key from the enumeration of keys, and lines 196–198 add a recommendation to the Option array.

 


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


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