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

Cookies - JavaServer

Cookies provide web developers with a tool for personalizing web pages.

Cookies

 

Cookies provide web developers with a tool for personalizing web pages. A cookie is a piece of data typically stored in a text file on the user’s computer. A cookie maintains in-formation about the client during and between browser sessions. The first time a user visits the website, the user’s computer might receive a cookie; this cookie is then reactivated each time the user revisits that site. The aim is to create an anonymous record containing data that is used to personalize the user’s future visits to the site. For example, cookies in a shop-ping application might store unique identifiers for users. When a user adds items to an on-line shopping cart or performs another task resulting in a request to the web server, the server receives a cookie from the client containing the user’s unique identifier. The server then uses the unique identifier to locate the shopping cart and perform any necessary pro-cessing.

 

In addition to identifying users, cookies also can indicate clients’ shopping prefer-ences. When a web server receives a request from a client, the server can examine the cookie(s) it sent to the client during previous communications, identify the client’s pref-erences and immediately display products of interest to the client.

 

Every HTTP-based interaction between a client and a server includes a header con-taining information either about the request (when the communication is from the client to the server) or about the response (when the communication is from the server to the client). When a page receives a request, the header includes information such as the request type (e.g., GET or POST) and any cookies that have been sent previously from the server to be stored on the client machine. When the server formulates its response, the header infor-mation contains any cookies the server wants to store on the client computer and other information, such as the MIME type of the response.

The expiration date of a cookie determines how long the cookie remains on the client’s computer. If you do not set an expiration date for a cookie, the web browser main-tains the cookie for the duration of the browsing session. Otherwise, the web browser maintains the cookie until the expiration date occurs. When the browser requests a resource from a web server, cookies previously sent to the client by that web server are returned to the web server as part of the request formulated by the browser. Cookies are deleted when they expire.

Using Cookies to Provide Book Recommendations

The next web application shows how to use cookies. The example contains two pages. In the first page (Figs. 26.17 and 26.19), users select a favorite programming language from a group of radio buttons and submit the form to the web server for processing. The web server responds by creating a cookie that stores the selected language and the ISBN num-ber for a recommended book on that topic. The server then renders new components in the browser that allow the user either to select another favorite programming language or to view the second page in our application (Figs. 26.20–26.21), which lists recommended books pertaining to the programming language(s) that the user selected. When the user clicks the hyperlink, the cookies previously stored on the client are read and used to form the list of book recommendations.

 

The JSP file in Fig. 26.17 contains a Radio Button Group (lines 26–30) with the options Java, C++, Visual Basic 2005, Visual C# 2005 and Internet & Web (set in the page bean). Recall that you can set the display and value Strings of radio buttons by right clicking the Radio Button Group and selecting Configure Default Options…. The user selects a programming language by clicking a radio button. When the user presses Submit, the web application creates a cookie containing the selected language. This cookie is added to the HTTP response header and sent to the client as part of the response.

 

 

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

 

2

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

 

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

 

5    <jsp:root version = "1.2"

 

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">

 

<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:hyperlink actionExpression =

41        "#{Options.languagesLink_action}" binding =

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

43        rendered = "false" style = "left: 24px; top: 72px;

44        position: absolute" text =

45        "Click here to choose another language."/>

46        <webuijsf:hyperlink actionExpression =

47        "#{Options.recommendationsLink_action}" binding =

48        "#{Options.recommendationsLink}" id =

49        "recommendationsLink" rendered = "false" style =

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

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

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

53        </webuijsf:form>

 

54        </webuijsf:body>

 

55        </webuijsf:html>

 

56        </webuijsf:page>

 

57        </f:view>

 

58        </jsp:root>



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

 

When the user clicks Submit, the webuijsf:staticText, webuijsf:radioButton Group and webuijsf:button elements used to select a language are hidden, and a webuijsf:staticText and two webuijsf:hyperlink elements are displayed. One webuijsf:staticText and both webuijsf:hyperlinks initially have their rendered properties set to false (lines 37, 43, and 49). This indicates that these components are not vis-ible the first time the page loads, as we want the user’s first view of the page to include only the components for selecting a programming language and submitting the selection.

 

The first hyperlink (lines 40–45) requests this page, and the second (lines 46–52) requests Recommendations.jsp. The url property is not set for the first link; we discuss this momentarily. The second link’s url property is set to /faces/Recommendations.jsp. Recall that earlier in the chapter, we set a url property to a remote website ( http://  www.deitel.com). To set this property to a page within the current application, you can click the ellipsis button next to the url property in the Properties window to open a dialog. You can then use this dialog to select a page within your project as the link’s destination.

 

 

Adding and Linking to a New Web Page

Setting the url property to a page in the current application requires that the destination page already exists. To set the url property of a link to Recommendations.jsp, you must first create this page. Right click the Web Pages node in the Projects window and select New > Page… from the menu that appears. In the New Page dialog, change the name of

 

the page to Recommendations and click Finish to create the files Recommendations.jsp and Recommendations.java. (We discuss the contents of these files shortly.) Once the Recommendations.jsp file exists, you can select it as the url value for recommendationsLink. For Options.jsp, rather than setting the languagesLink’s url property, we will add an action handler for this component to the page bean. The action handler will enable us to show and hide components of the page without redirecting the user to another page. Specifying a destination url would override the component’s action handler and redirect the user to the specified page, so it is important that we do not set the url property in this case. Since we use this link to reload the current page, we simply return null from the action handler, causing Options.jsp to reload.

 

To add an action handler to a hyperlink that should also direct the user to another page, you must add a rule to the Page Navigation file (Fig. 26.18). To edit this file, right


click anywhere in the Visual Designer and select Page Navigation. Click Options.jsp in the navigation designer to display its components that might cause the page to request another page. Locate the link whose navigation rule you would like to set (recommenda-tionsLink in this case) and drag it to the destination page. Now the link can direct the user to a new page (Recommendations.jsp) without overriding its action handler. Editing the Page Navigation file is also useful when you would like action elements that cannot specify a url property, such as buttons, to direct users to another page. You’ll configure a link from Recommendations.asp to Options.jsp later in this section.

 

Figure 26.19 contains the code that writes a cookie to the client machine when the user selects a programming language. The file also determines which components appear on the page, displaying either the components for choosing a language or the links for nav-igating the application, depending on the user’s actions.

 

1    // Fig. 26.19: Options.java

 

2    // Page bean that stores user's language selection as a client cookie.

 

3    package sessiontrackingcookies;

4

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

 

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

 

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

 

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

 

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

 

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

 

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

 

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

 

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

 

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

 

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

 

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

 

 

5      import java.util.Properties;

 

6      import javax.faces.FacesException;

 

7      import javax.servlet.http.Cookie;

 

8      import javax.servlet.http.HttpServletResponse;

22   21 public class Options extends AbstractPageBean

23   {

 

24         private int __placeholder;

25

26         private void _init() throws Exception

27         {

 

languageRadioGroupDefaultOptions.setOptions(

29        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" )

38                      } // end array initializer

 

39                ); // end call to setOptions

 

40         } // end method _init

41

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

 

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

44

200  private Properties books = new Properties();

 

201

202      // Construct a new page bean instance and initialize the prperties

 

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

 

204      public Options()

205      {

 

206             // initialize the Properties object of values to be stored as

207             // cookies.

 

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

 

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

 

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

 

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

 

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

 

213      } // end Options constructor

214

1             // To save space, we omitted the code in lines 215-257. The complete

 

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

217

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

 

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

 

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

 

9             public String submitButton_action()

10          {

 

11                String msg = "Welcome to Cookies! You ";

264

9                    // if the user made a selection

 

10                if ( languageRadioGroup.getSelected() != null )

11                {

 

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

 

msg += "selected " + language.replace( '-', ' ' ) + ".";

18                      // get ISBN number of book for the given language

 

19                      String ISBN = books.getProperty( language );

273

21                      // create cookie using language-ISBN name-value pair

 

22                      Cookie cookie = new Cookie( language, ISBN );

276

1                          // add cookie to response header to place it on user's machine

 

2                          HttpServletResponse response =

 

3                                 ( HttpServletResponse ) getExternalContext().getResponse();

 

4                          response.addCookie( cookie );

5                    } // end if

6                    else

 

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

284

6                    responseText.setValue( msg );

 

7                    languageRadioGroup.setRendered( false );

 

8                    instructionText.setRendered( false );

 

9                    submitButton.setRendered( false );

 

10                responseText.setRendered( true );

 

11                languagesLink.setRendered( true );

 

12                recommendationsLink.setRendered( true );

 

13                return null; // reloads the page

 

14          } // end method submitButton_action

294

1             // redisplay the components for selecting a language

 

2             public String languagesLink_action()

3             {

 

4                    responseText.setRendered( false );

 

5                    languagesLink.setRendered( false );

 

6                    recommendationsLink.setRendered( false );

 

7                    languageRadioGroup.setRendered( true );

 

8                    instructionText.setRendered( true );

 

9                    submitButton.setRendered( true );

 

10                return null;

 

11          } // end method languagesLink_action

 

12   } // end class Options

 

Fig. 26.19 | Page bean that stores the user’s language selection in a client cookie.

As mentioned previously, the _init method handles component initialization. Since this page contains a RadioButtonGroup object that requires initialization, method _init (lines 26–40) constructs an array of Option objects to be displayed by the buttons.

 

Lines 208–212 in the constructor initialize a Properties object—a data structure that stores String key/value pairs. The application uses the key to store and retrieve the associated value in the Properties object. In this example, the keys are Strings con-taining the programming language names, and the values are Strings containing the ISBN numbers for the recommended books. Class Properties provides method set-Property, which takes as arguments a key and a value. A value that is added via method setProperty is placed in the Properties at a location determined by the key. The value for a specific Properties entry can be determined by invoking the method getProperty on the Properties object with that value’s key as an argument.

Clicking Submit invokes the event handler submitButton_action (lines 261–293), which displays a message indicating the selected language in the responseText element and adds a new cookie to the response. If a language was selected (line 266), the selected item is retrieved (line 268). Line 269 adds the selected language to the results message.

 

Line 272 retrieves the ISBN for the selected language from the books Properties objectc. Then line 275 creates a new Cookie object (in package javax.servlet.http), using the selected language as the cookie’s name and a corresponding ISBN as the cookie’s value. This cookie is added to the HTTP response header in lines 278–280. An object of class HttpServletResponse (from package javax.servlet.http) represents the response.

 

This object can be accessed by invoking the method getExternalContext on the page bean, then invoking getResponse on the resulting object. If a language was not selected, line 283 sets the results message to indicate that no selection was made.

 

Lines 285–291 control the appearance of the page after the user clicks Submit. Line 285 sets the responseText to display the String msg. Since the user has just submitted a language selection, the components used to collect the selection are hidden (lines 286– 288) and responseText and the links used to navigate the application are displayed (lines 289–291). The action handler returns null at line 292, which reloads Options.jsp.

 

Lines 296–305 contain the languagesLink’s event handler. When the user clicks this link, responseText and the two links are hidden (lines 298–300), and the components that allow the user to select a language are redisplayed (lines 301–303). The method returns null at line 304, causing Options.jsp to reload.

 

Displaying Book Recommendations Based on Cookie Values

After clicking Submit, the user may request a book recommendation. The book recom-mendations hyperlink forwards the user to Recommendations.jsp (Fig. 26.20) to display recommendations based on the user’s language selections.

 

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

 

2

6     <!-- Fig. 26.20: Recommendations.jsp -->

 

7    <!-- Displays book recommendations using cookies -->

 

8    <jsp:root version = "1.2"

 

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

 

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

 

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

 

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

 

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

 

14               pageEncoding = "UTF-8"/>

 

15         <f:view>

 

16         <webuijsf:page binding = "#{Recommendations.page1}" id = "page1">

 

17               <webuijsf:html binding = "#{Recommendations.html1}" id = "html1">

 

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

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

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

18        </webuijsf:head>    

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

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

21        <webuijsf:form binding = "#{Recommendations.form1}"         

22        id = "form1">

23        <webuijsf:label binding =  

24        "#{Recommendations.recommendationsLabel}" for =

25        "recommendationsListbox" id = "recommendationsLabel"

26        style = "font-size: 18px; left: 24px; top: 24px;

27        position: absolute" text = "Recommendations"/>

28        <webuijsf:listbox binding =           

29        "#{Recommendations.recommendationsListbox}" id =

30        "recommendationsListbox" items = "#{Recommendations.

31        recommendationsListboxDefaultOptions.options}"

32        style = "height: 96px; left: 24px; top: 48px;         

33        position: absolute; width: 360px"/>          

34        <webuijsf:hyperlink actionExpression = 

35        "#{Recommendations.optionsLink_action}" binding =

36        "#{Recommendations.optionsLink}" id = "optionsLink"

37        style = "left: 24px; top: 168px; position: absolute"

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

39        </webuijsf:form>

 

40        </webuijsf:body>

 

41        </webuijsf:html>

 

42        </webuijsf:page>

 

43        </f:view>

 

44        </jsp:root>



Recommendations.jsp contains a Label (lines 23–27), a Listbox (lines 28–33) and a Hyperlink (lines 34–38). The Label displays the text Recommendations at the top of the page. A Listbox component displays a list of options from which a user can make multiple selections. The Listbox in this example displays the recommendations created by the Recommendations.java page bean (Fig. 26.21), or the text "No Recommendations. Please select a language." The Hyperlink allows the user to return to Options.jsp to select additional languages. You can configure this hyperlink using the Page Navigation file as described earlier in this section.

 

Page Bean That Creates Book Recommendations from Cookies

 

In Recommendations.java (Fig. 26.21), method prerender (lines 180–210) retrieves the cookies from the client, using the request object’s getCookies method (lines 183–185).

 

An object of class HttpServletRequest (from package javax.servlet.http) represents the request. This object can be obtained by invoking method getExternalContext on the page bean, then invoking getRequest on the resulting object. The call to getCookies re-turns an array of the cookies previously written to the client. Cookies can be read by an application only if they were created by a server in the domain in which the application is running—a web server cannot access cookies created by servers in other domains. For ex-ample, a cookie created by a web server in the deitel.com domain cannot be read by a web server in any other domain.

 

 

17// Fig. 26.21: Recommendations.java

 

18// Displays book recommendations based on cookies storing user's selected

 

19// programming languages.

 

20package sessiontrackingcookies;

5

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

 

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

 

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

 

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

 

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

 

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

 

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

 

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

 

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

 

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

 

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

 

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

 

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

 

35  import javax.faces.FacesException;

 

36  import javax.servlet.http.Cookie;

 

37  import javax.servlet.http.HttpServletRequest;

2

1      public class Recommendations extends AbstractPageBean

2      {

 

3            private int __placeholder;

26

6            private void _init() throws Exception

7            {

 

8                   recommendationsListboxDefaultOptions.setOptions(

 

9                         new com.sun.webui.jsf.model.Option[] {} );

10         }

 

9             32// To save space, we omitted the code in lines 33-178. The complete

 

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

35

21          // displays the book recommendations in the Listbox

 

22          public void prerender()

23          {

 

24                // retrieve client's cookies

 

25                HttpServletRequest request =

 

26                      ( HttpServletRequest ) getExternalContext().getRequest();

 

27                Cookie [] cookies = request.getCookies();

186

23                // if there are cookies, store the corresponding books and ISBN

 

24                // numbers in an array of Options

 

25                Option [] recommendations;

190

191             if ( cookies.length > 1 )

192             {

 

193                   recommendations = new Option[ cookies.length - 1 ];

194      

195                   for ( int i = 0; i < cookies.length - 1; i++ )

196                   {

 

197                           String language = cookies[ i ].getName().replace( '-', ' ' );

 

198                         recommendations[ i ] = new Option( language +

199             " How to Program.  ISBN#: " + cookies[ i ].getValue() );

 

200                   } // end for

201             } // end if

202             else

203             {

 

204                   recommendations = new Option[ 1 ];

 

205                   recommendations[ 0 ] = new Option(

 

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

207             } // end else

208

209             recommendationsListbox.setItems( recommendations );

 

210      } // end method prerender

211

212      // To save space, we omitted the code in lines 212-230. The complete

 

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

214

231      // redirects user to Options.jsp

 

232      public String optionsLink_action()

233      {

 

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

 

235      } // end method optionsLink_action

 

236    } // end class Recommendations

 

Fig. 26.21 | Page bean that displays book recommendations based on cookies storing user’s selected languages.

 

 

Line 191 determines whether at least one cookie exists. Lines 195–200 add the infor-mation in the cookie(s) to an Option array. Arrays of Option objects can be displayed as a list of items in a Listbox component. The loop retrieves the name and value of each cookie, using the control variable to determine the current value in the cookie array. If no language was selected, lines 204–206 add to an Options array a message instructing the user to select a language. Line 209 sets recommendationsListBox to display the resulting Options array.

 

We summarize commonly used Cookie methods in Fig. 26.22.




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


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