Home | | Internet & World Wide Web HOW TO PROGRAM | | Internet Programming | | Web Programming | Consuming a Database-Driven Web Service from a Web Application

Chapter: Internet & World Wide Web HOW TO PROGRAM - Rich Internet Application Server Technologies - Web Services

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

Consuming a Database-Driven Web Service from a Web Application

Our prior examples accessed web services from desktop applications created in Netbeans.

Consuming a Database-Driven Web Service from a  Web Application

 

Our prior examples accessed web services from desktop applications created in Netbeans. However, we can just as easily use them in web applications created with Netbeans. In fact, because web-based businesses are becoming increasingly prevalent, it is common for web applications to consume web services. In this section, we present an airline reservation web service that receives information regarding the type of seat a customer wishes to reserve and makes a reservation if such a seat is available. Later in the section, we present a web appli-cation that allows a customer to specify a reservation request, then uses the airline reserva-tion web service to attempt to execute the request.

 

1. Configuring Java DB in Netbeans and Creating the Reservation Database

 

In this example, our web service uses a Reservation database containing a single table named Seats to locate a seat matching a client’s request. To build the Reservation data-base, review the steps presented in Section 27.2.1 for building the AddressBook database. This chapters examples directory contains a SQL script to build the Seats table and pop-ulate it with sample data. The sample data is shown in Fig. 28.15.


Creating the Reservation Web Service

 

You can now create a web service that uses the Reservation database (Fig. 28.16). The airline reservation web service has a single web method—reserve (lines 26–78)—which searches the Seats table to locate a seat matching a user’s request. The method takes two arguments—a String representing the desired seat type (i.e., "Window", "Middle" or "Aisle") and a String representing the desired class type (i.e., "Economy" or "First"). If it finds an appropriate seat, method reserve updates the database to make the reservation and returns true; otherwise, no reservation is made, and the method returns false. Note that the statements at lines 34–39 and lines 44–48 that query and update the database use objects of JDBC types ResultSet and PreparedStatement.

Our database contains four columns—the seat number (i.e., 110), the seat type (i.e., Window, Middle or Aisle), the class type (i.e., Economy or First) and a column containing either 1 (true) or 0 (false) to indicate whether the seat is taken. Lines 34–39 retrieve the seat numbers of any available seats matching the requested seat and class type. This state-ment fills the resultSet with the results of the query

 

SELECT "NUMBER" FROM "SEATS"

WHERE ("TAKEN" = 0) AND ("TYPE" = type) AND ("CLASS" = class)

 

The parameters type and class in the query are replaced with values of method reserve’s seatType and classType parameters. When you use the Netbeans tools to create a data-base table and its columns, the Netbeans tools automatically place the table and column names in double quotes. For this reason, you must place the table and column names in double quotes in the SQL statements that interact with the Reservation database.

 

If resultSet is not empty (i.e., at least one seat is available that matches the selected criteria), the condition in line 42 is true and the web service reserves the first matching seat number. Recall that ResultSet method next returns true if a nonempty row exists, and positions the cursor on that row. We obtain the seat number (line 44) by accessing resultSet’s first column (i.e., resultSet.getInt(1)—the first column in the row).

Then lines 45–48 configure a PreparedStatement and execute the SQL:

 

UPDATE "SEATS"

 

SET "TAKEN" = 1

WHERE ("NUMBER" = number)

 

which marks the seat as taken in the database. The parameter number is replaced with the value of seat. Method reserve returns true (line 49) to indicate that the reservation was successful. If there are no matching seats, or if an exception occurred, method reserve re-turns false (lines 52, 57, 62 and 75) to indicate that no seats matched the user’s request.

 

1     // Fig. 28.16: Reservation.java

 

2     // Airline reservation web service.

 

3     package com.deitel.iw3htp4.ch28.reservation;

4              

7     import java.sql.Connection;

 

8     import java.sql.PreparedStatement;

 

9     import java.sql.DriverManager;

 

10  import java.sql.ResultSet;

 

11  import java.sql.SQLException;

 

12    import javax.jws.WebService;

 

13    import javax.jws.WebMethod;

 

14    import javax.jws.WebParam;

13

10    @WebService( name = "Reservation", serviceName = "ReservationService" )

 

11    public class Reservation

12    {

 

13          private static final String DATABASE_URL =

 

14                 "jdbc:derby://localhost:1527/Reservation";

 

15          private static final String USERNAME = "iw3htp4";

 

16          private static final String PASSWORD = "iw3htp4";

 

17          private Connection connection;

 

18          private PreparedStatement lookupSeat;

 

19          private PreparedStatement reserveSeat;

24

1             // a WebMethod that can reserve a seat

 

2             @WebMethod( operationName = "reserve" )

 

3             public boolean reserve( @WebParam( name = "seatType" ) String seatType,

 

4                    @WebParam( name = "classType" ) String classType )

5             {

6                    try

7                    {

 

8                          connection = DriverManager.getConnection(

5                                 DATABASE_URL, USERNAME, PASSWORD );

 

lookupSeat = connection.prepareStatement(

"SELECT \"NUMBER\" FROM \"SEATS\" WHERE (\"TAKEN\" = 0) " +

8     "AND (\"LOCATION\" = ?) AND (\"CLASS\" = ?)" );

 

9                          lookupSeat.setString( 1, seatType );

 

10                       lookupSeat.setString( 2, classType );

 

ResultSet resultSet = lookupSeat.executeQuery();

 

40

41        // if requested seat is available, reserve it

 

42        if ( resultSet.next() )

43        {

 

            int seat =         resultSet.getInt( 1 );               

44                                           

45        reserveSeat = connection.prepareStatement(             

46        "UPDATE       \"SEATS\" SET \"TAKEN\"=1 WHERE \"NUMBER\"=?" );                      

47        reserveSeat.setInt( 1, seat );               

48        reserveSeat.executeUpdate();

49        return true;

 

50        } // end if

51

52        return false;

 

53        } // end try

 

54        catch ( SQLException e )

55        {

 

56        e.printStackTrace();

 

57        return false;

 

58        } // end catch

 

59        catch ( Exception e )

60        {

 

61        e.printStackTrace();

 

62        return false;

 

63        } // end catch

 

64        finally

65        {

66        try

67        {

 

           

68        lookupSeat.close();

69        reserveSeat.close();

70        connection.close();

 

71        } // end try

 

72        catch ( Exception e )

73        {

74        e.printStackTrace();

 

75        return false;

 

76        } // end catch

 

77        } // end finally

 

78        } // end WebMethod reserve

 

79        } // end class Reservation

Fig. 28.16 | Airline reservation web service.

 

2. Creating a Web Application to Interact with the Reservation Web Service

 

This section presents a ReservationClient web application that consumes the Reserva-tion web service. The application allows users to select seats based on class ("Economy" or "First") and location ("Aisle", "Middle" or "Window"), then submit their requests to the airline reservation web service. If the database request is not successful, the application in-structs the user to modify the request and try again. The application presented here was built using the techniques presented in Chapters 26–27. We assume that you’ve already read those chapters, and thus know how to build a web application’s GUI, create event handlers and add properties to a web application’s session bean (Section 27.2.1).

 

Reserve.jsp

 

Reserve.jsp (Fig. 28.17) defines two DropDownLists and a Button. The seatTypeDrop-Down (lines 26–31) displays all the seat types from which users can select. The classType-DropDownList (lines 32–37) provides choices for the class type. Users click the reserveButton (lines 38–42) to submit requests after making selections from the Drop-DownLists. The page also defines three Labels—instructionLabel (lines 22–25) to dis-play instructions, errorLabel (lines 43–47) to display an appropriate message if no seat matching the user’s selection is available and successLabel (lines 48–51) to indicate a suc-cessful reservation. The page bean file (Fig. 28.18) attaches event handlers to seatType-DropDown, classTypeDropDown and reserveButton.

 

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

 

2

1     <!-- Fig. 28.17 Reserve.jsp -->

 

2    <!-- JSP that allows a user to select a seat -->

 

3    <jsp:root version="1.2"

 

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

 

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

 

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

 

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

 

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

 

9                   pageEncoding="UTF-8"/>

 

<f:view>

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

 

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

 

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

 

 

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

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

18        </webuijsf:head>

 

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

 

 

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

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

22        <webuijsf:label binding="#{Reserve.instructionLabel}"

23        id="instructionLabel" style="left: 24px; top: 24px;

24        position: absolute" text="Please select the seat type

25        and class to reserve:"/>

26        <webuijsf:dropDown binding="#{Reserve.seatTypeDropDown}"

27        id="seatTypeDropDown" items=

28        "#{Reserve.seatTypeDropDownDefaultOptions.options}"

29        style="left: 310px; top: 21px; position: absolute"

30        valueChangeListenerExpression=

31        "#{Reserve.seatTypeDropDown_processValueChange}"/>

32        <webuijsf:dropDown binding="#{Reserve.classTypeDropDown}"

33        id="classTypeDropDown" items=

34        "#{Reserve.classTypeDropDownDefaultOptions.options}"

35        style="left: 385px; top: 21px; position: absolute"

36        valueChangeListenerExpression=

37        "#{Reserve.classTypeDropDown_processValueChange}"/>

38        <webuijsf:button actionExpression=

39        "#{Reserve.reserveButton_action}" binding=

40        "#{Reserve.reserveButton}" id="reserveButton" style=

41        "height: 20px; left: 460px; top: 21px; position:

42        absolute; width: 100px" text="Reserve"/>

43        <webuijsf:label binding="#{Reserve.errorLabel}"

44        id="errorLabel" rendered="false" style="color: red;

45        left: 24px; top: 48px; position: absolute" text="This

46        type of seat is not available. Please modify your

47        request and try again."/>

48        <webuijsf:label binding="#{Reserve.successLabel}"

49        id="successLabel" rendered="false" style="left: 24px;

50        top: 24px; position: absolute"

51        text="Your reservation has been made. Thank you!"/>

52        </webuijsf:form>

 

53        </webuijsf:body>

 

54        </webuijsf:html>

 

55        </webuijsf:page>

 

56        </f:view>

 

57        </jsp:root>



Fig. 28.17 | JSP that allows a user to select a seat.

 

Reserve.java

 

Figure 28.18 contains the page bean code that provides the logic for Reserve.jsp. As dis-cussed in Section 26.5.2, the class that represents the page’s bean extends AbstractPage-Bean. When the user selects a value in one of the DropDownLists, the corresponding event handler—classTypeDropDown_processValueChange (lines 262–267) or seatTypeDrop-Down_processValueChange (lines 270–275)—is called to set the session properties seat Type and classType, which we added to the web application’s session bean. The values of these properties are used as the arguments in the call to the web service’s reserve method. When the user clicks Reserve in the JSP, the event handler reserveButton_action (lines 278–311) executes. Lines 282–284 use the proxy object (created in lines 38–39) to invoke the web service’s reserve method, passing the selected seat type and class type as argu-ments. If reserve returns true, lines 288–293 hide the GUI components in the JSP and display the successLabel (line 292) to thank the user for making a reservation; otherwise, lines 297–302 ensure that the GUI components remain displayed and display the error-Label (line 302) to notify the user that the requested seat type is not available and instruct the user to try again.

 

5    // Fig. 28.18: Reserve.java

 

6    // Page scope backing bean class for seat reservation client

 

7    package com.deitel.iw3htp4.ch28.reservationclient;

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.DropDown;

 

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

 

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

 

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

 

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

 

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

 

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

 

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

 

12   import javax.faces.FacesException;

 

import javax.faces.event.ValueChangeEvent;

18        import reservationservice.ReservationService;

 

19        import reservationservice.Reservation;

20

21        public class Reserve extends AbstractPageBean

22        {

 

23        private int __placeholder;

 

24        private ReservationService reservationService; // reference to service

 

25        private Reservation reservationServiceProxy; // reference to proxy

26

27        private void _init() throws Exception

28        {

 

29        seatTypeDropDownDefaultOptions.setOptions(

 

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

 

                       

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

32        new    com.sun.webui.jsf.model.Option( "Middle", "Middle" ),

33        new com.sun.webui.jsf.model.Option( "Window", "Window" ) } );

 

34        classTypeDropDownDefaultOptions.setOptions(

 

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

36        new com.sun.webui.jsf.model.Option( "Economy", "Economy" ),

 

37        new com.sun.webui.jsf.model.Option( "First", "First" ) } );

 

38        reservationService = new ReservationService();

 

39        reservationServiceProxy = reservationService.getReservationPort();

 

40        } // end method

41

42        // Lines 42-260 of the autogenerated code have been removed to save

 

43        // space. The complete code is available in this example’s folder.

44       

261     // store selected class in session bean

 

262     public void classTypeDropDown_processValueChange(

 

263     ValueChangeEvent event )

264     {

 

265     getSessionBean1().setClassType(

 

266     ( String ) classTypeDropDown.getSelected() );

 

267     } // end method classTypeDropDown_processValueChange

268    

269     // store selected seat type in session bean

 

270     public void seatTypeDropDown_processValueChange(

 

271     ValueChangeEvent event )

272     {

 

273     getSessionBean1().setSeatType(

 

274     ( String ) seatTypeDropDown.getSelected() );

 

275     } // end method seatTypeDropDown_processValueChange

276    

277     // invoke the web service when the user clicks Reserve button

 

278     public String reserveButton_action()

279     {

280     try

281     {

 

282     boolean reserved = reservationServiceProxy.reserve(

 

283     getSessionBean1().getSeatType(),

 

284     getSessionBean1().getClassType() );

285

1                          if ( reserved ) // display successLabel; hide all others

2                          {

 

3                                 instructionLabel.setRendered( false );

 

4                                 seatTypeDropDown.setRendered( false );

 

5                                 classTypeDropDown.setRendered( false );

 

6                                 reserveButton.setRendered( false );

 

7                                 successLabel.setRendered( true );

 

8                                 errorLabel.setRendered( false );

9                          } // end if

 

10                      else // display all but successLabel

11                      {

 

12                             instructionLabel.setRendered( true );

 

13                             seatTypeDropDown.setRendered( true );

 

14                             classTypeDropDown.setRendered( true );

 

15                             reserveButton.setRendered( true );

 

16                             successLabel.setRendered( false );

 

17                             errorLabel.setRendered( true );

18                      } // end else

19                } // end try

 

20                catch ( Exception e )

21                {

 

22                      e.printStackTrace();

 

23                } // end catch

309

5                    return null;

 

6             } // end method reserveButton_action

 

7       } // end class Reserve

 

Fig. 28.18 | Page scope backing bean class for seat reservation client.


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


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