Hotel WS Client Web Page.

Introduction To Spring WS Client

Spring-WS provides a client-side Web service API that allows for consistent, XML-driven access to
Web services. It also caters for the use of marshallers and unmarshallers so that your service tier code can deal exclusively with Java objects.The org.springframework.ws.client.core package provides the core functionality for using the clientside access API.

The WebServiceTemplate is the core class for client-side Web service access in Spring-WS. It contains methods for sending Source objects, and receiving response messages as either Source or Result.Additionally, it can marshal objects to XML before sending them across a transport, and unmarshal any response XML into an object again.

The WebServiceTemplate class uses an URI as the message destination. You can either set a defaultUri property on the template itself, or supply an URI explicitly when calling a method on the template. The URI will be resolved into a WebServiceMessageSender, which is responsible for sending the XML message across a transport layer. You can set one or more message senders using the messageSender or messageSenders properties of the WebServiceTemplate class

As mentioned earlier we will cover only HTTP  transport only.
HTTP transports
There are two implementations of the WebServiceMessageSender interface for sending messages via HTTP. The default implementation is the HttpUrlConnectionMessageSender, which uses the facilities provided by Java itself. The alternative is the CommonsHttpMessageSender, which uses the Jakarta Commons HttpClient [http://jakarta.apache.org/commons/httpclient/]. To use the HTTP transport, either set the defaultUri to something like http://example.com/services,
or supply the uri parameter for one of the methods.

  <bean id="hotelServiceWSTestClient" class="com.example.ws.clientImpl.HotelServiceWSTestClient">
    <property name="defaultUri" value="http://localhost:8080/springhoteroombookingws/HotelService" />
        <property name="marshaller" ref="marshaller" />
        <property name="unmarshaller" ref="marshaller" />
        <property name="messageFactory" ref="messageFactory" />
        <property name="messageSender">
            <bean
                class="org.springframework.ws.transport.http.HttpUrlConnectionMessageSender">
            </bean>
        </property>
      </bean>


In addition to a message sender, the WebServiceTemplate requires a Web service
message factory. There are two message factories for SOAP: SaajSoapMessageFactory and
AxiomSoapMessageFactory. If no message factory is specified (via the messageFactory property),
Spring-WS will use the SaajSoapMessageFactory by default.



Sending and receiving a WebServiceMessage :
The WebServiceTemplate contains many convenience methods to send and receive web service
messages. There are methods that accept and return a Source and those that return a Result.
Additionally, there are methods which marshal and unmarshal objects to XML. 


Please note that the WebServiceTemplate class is thread-safe once configured (assuming that all of it's
dependencies are thread-safe too, which is the case for all of the dependencies that ship with Spring-
WS), and so multiple objects can use the same shared WebServiceTemplate instance if so desired.
The WebServiceTemplate exposes a zero argument constructor and messageFactory/messageSender
bean properties which can be used for constructing the instance (using a Spring container or plain Java
code). Alternatively, consider deriving from Spring-WS's WebServiceGatewaySupport convenience
base class, which exposes convenient bean properties to enable easy configuration. (You do not have
to extend this base class... it is provided as a convenience class only.) 


Sending and receiving POJOs - marshalling and unmarshalling :
In order to facilitate the sending of plain Java objects, the WebServiceTemplate has a number
of send(..) methods that take an Object as an argument for a message's data content. The
method marshalSendAndReceive(..) in the WebServiceTemplate class delegates the conversion
of the request object to XML to a Marshaller, and the conversion of the response XML to an
object to an Unmarshaller. 



BookingResponse response = new BookingResponse();
              
               System.out.println(getWebServiceTemplate().getDefaultUri());
              
      
             response = (BookingResponse)getWebServiceTemplate().marshalSendAndReceive(request);
             System.out.println(response.getBookingNumber()); 



Below are the screen shots,code for this project



When you run this client you will se this page and when you click book button it will call our Hotel Room Booking Web Services.


 Now it will call WS and return booking number.

 

Code for the Hotel Room Booking WS Client.

We created Spring MVC project in STS for this Client Application.

1) web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
<!-- Processes application requests -->
    <servlet>
        <servlet-name>hotel-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>
        </init-param> -->   
        <load-on-startup>1</load-on-startup>
    </servlet>
       
    <servlet-mapping>
        <servlet-name>hotel-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
   
        <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/hotel-dispatcher-servlet.xml</param-value>
    </context-param>
   
     <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>WEB-INF/conf/log4j.xml</param-value>
    </context-param>
     <context-param>
        <param-name>webAppRootKey</param-name>
        <param-value>HotelWebServiceClient</param-value>
    </context-param>
  
   
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
    </listener>
    <listener>
        <listener-class>
                      org.springframework.web.context.ContextLoaderListener
                </listener-class>
    </listener>


 <filter>
   
    <filter-name>LoggerFilter</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>LoggerFilter</filter-name>
    <servlet-name>hotel-dispatcher</servlet-name>
  
   
</filter-mapping>

</web-app>


 2)hotel-dispatcher-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
 xmlns:mvc="http://www.springframework.org/schema/mvc"
 xmlns:sws="http://www.springframework.org/schema/web-services"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
 http://www.springframework.org/schema/mvc
 http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
 http://www.springframework.org/schema/context
 http://www.springframework.org/schema/context/spring-context-3.0.xsd
 http://www.springframework.org/schema/web-services
http://www.springframework.org/schema/web-services/web-services-2.0.xsd">

  <mvc:annotation-driven/>


    <context:component-scan base-package="com.example.ws" />
     <!-- <mvc:default-servlet-handler/>
       <mvc:resources mapping="/resources/**" location="/resources/" />
     
 -->
   
<bean id="LoggerFilter" class="com.example.ws.filter.LoggerFilter"/>
   
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/views/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
   


     <bean
    class="org.springframework.ws.soap.server.endpoint.SoapFaultAnnotationExceptionResolver" />

  <bean id="hotelServiceWSTestClient" class="com.example.ws.clientImpl.HotelServiceWSTestClient">
    <property name="defaultUri" value="http://localhost:8080/springhoteroombookingws/HotelService" />
        <property name="marshaller" ref="marshaller" />
        <property name="unmarshaller" ref="marshaller" />
        <property name="messageFactory" ref="messageFactory" />
        <property name="messageSender">
            <bean
                class="org.springframework.ws.transport.http.HttpUrlConnectionMessageSender">
            </bean>
        </property>
      </bean>

<bean id="messageFactory" class="org.springframework.ws.soap.saaj.SaajSoapMessageFactory" />
<bean id="marshaller" class="org.springframework.oxm.jaxb.Jaxb2Marshaller">
<property name="contextPath" value="com.example.hotelservices"/>
 </bean>

</beans> 


3) HotelService.xsd: Using JAXB ,generate the JAXB classes.This step will be same as we did during writting WS.XSD will be same.

4)BookingController

package com.example.ws.controller;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.context.ContextLoader;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.servlet.ModelAndView;

import com.example.hotelservices.BookingForm;
import com.example.ws.clientImpl.HotelServiceWSTestClient;

@Controller
public class BookingController {

    private static Logger log = Logger.getLogger(BookingController.class.getName());
   
    @RequestMapping("/start")
    public ModelAndView start(HttpServletRequest request) {
      
        MDC.put("sessionID", request.getSession().getId());
        log.debug("start method entered..."+request.getSession().getId());
        //log.debug("login called...redirecting login page....");
        log.debug("start method exiting...");
        return new ModelAndView("booking", "bookingForm", new BookingForm());
    }
   
    @RequestMapping("/bookingComplete")
                  
    public ModelAndView booking(@Valid @ModelAttribute("bookingForm") BookingForm booking,BindingResult result ) {
      
   
        log.debug("booking method entered..."+booking.getFirstName());
        String firstName = booking.getFirstName();

      
        if (result.hasErrors()) {
            return new ModelAndView("booking", "bookingForm", booking);
        }
      
        WebApplicationContext wbctx =  ContextLoader.getCurrentWebApplicationContext();
        HotelServiceWSTestClient    hotelServiceWSTestClient = (HotelServiceWSTestClient)wbctx.getBean("hotelServiceWSTestClient");
        String bookingNumber = hotelServiceWSTestClient.bookHotelRoom(booking);
        log.debug("bookingNumber..."+bookingNumber);
        booking.setBookingNumber(bookingNumber);
        log.debug("booking method exiting..."+booking.getFirstName());
        return new ModelAndView("confirm", "bookingForm", booking);
    }


}


5)HotelServiceWSTestClient
package com.example.ws.clientImpl;

import java.util.GregorianCalendar;

import javax.xml.datatype.DatatypeConfigurationException;
import javax.xml.datatype.DatatypeFactory;

import org.springframework.ws.client.core.WebServiceTemplate;
import org.springframework.ws.client.core.support.WebServiceGatewaySupport;

import com.example.hotelservices.Address;
import com.example.hotelservices.Booking;
import com.example.hotelservices.BookingForm;
import com.example.hotelservices.BookingRequest;
import com.example.hotelservices.BookingResponse;
import com.example.hotelservices.Customer;
import com.example.hotelservices.Name;
import com.example.hotelservices.RoomBooked;
import com.example.hotelservices.RoomType;



public class HotelServiceWSTestClient extends WebServiceGatewaySupport  {
   
    private WebServiceTemplate webServiceTemplate;
   
     private static DatatypeFactory df = null;
        static {
            try {
                df = DatatypeFactory.newInstance();
            } catch (DatatypeConfigurationException dce) {
                throw new IllegalStateException(
                    "Exception while obtaining DatatypeFactory instance", dce);
            }
        } 
    public String bookHotelRoom(BookingForm bookingform)
    {
        String bookingNumber ="";
        try{
            BookingRequest request = new BookingRequest();
            Booking booking = new Booking();
           
           
            GregorianCalendar gc = (GregorianCalendar) GregorianCalendar.getInstance();
           
               booking.setBookingdate( df.newXMLGregorianCalendar(gc));
       
               GregorianCalendar checkingingc = (GregorianCalendar) GregorianCalendar.getInstance();
              
               checkingingc.set(Integer.parseInt(bookingform.getCheckinDate().substring(6, 10)),Integer.parseInt(bookingform.getCheckinDate().substring(0, 2)), Integer.parseInt(bookingform.getCheckinDate().substring(3, 5)));
               booking.setCheckindate(df.newXMLGregorianCalendar(checkingingc));
              
               GregorianCalendar checkingoutgc = (GregorianCalendar) GregorianCalendar.getInstance();
               checkingoutgc.set(Integer.parseInt(bookingform.getCheckoutDate().substring(6, 10)),Integer.parseInt(bookingform.getCheckoutDate().substring(0, 2)), Integer.parseInt(bookingform.getCheckoutDate().substring(3, 5)));
               booking.setCheckoutdate(df.newXMLGregorianCalendar(checkingoutgc));
              
               Customer cust = new Customer();
              
               Name name =new Name();
               name.setFirstName(bookingform.getFirstName());
               name.setLastName(bookingform.getLastName());
               cust.setName(name);
              
               Address addre = new Address();
               addre.setAddressLine1(bookingform.getAddressLine1());
               addre.setAddressLine2(bookingform.getAddressLine2());
               addre.setCity(bookingform.getCity());
               addre.setEmail(bookingform.getEmail());
               addre.setMobile(bookingform.getMobile());
               addre.setState(bookingform.getState());
               addre.setPhoneLandLine(bookingform.getPhoneLandLine());
               addre.setZip(bookingform.getZip());
               cust.setAddressPrimary(addre);
              
              
               booking.setCustomer(cust);
              
               RoomBooked room = new RoomBooked();
               room.setName(bookingform.getAddressLine1());
               room.setQuantity(Double.parseDouble(bookingform.getQuantity()));
              
               if(bookingform.getRoomtype().equalsIgnoreCase("SemiDeluxe"))
               room.setType(RoomType.SEMI_DELUXE);
               if(bookingform.getRoomtype().equalsIgnoreCase("Standard"))
               room.setType(RoomType.STANDARD);
               if(bookingform.getRoomtype().equalsIgnoreCase("Deluxe"))
               room.setType(RoomType.DELUXE);
               if(bookingform.getRoomtype().equalsIgnoreCase("Luxury"))
               room.setType(RoomType.LUXURY);
               if(bookingform.getRoomtype().equalsIgnoreCase("HoneymoonSuite"))
               room.setType(RoomType.HONEYMOON_SUITE);
              
               booking.setRoomBooked(room);
              
              
              
               request.setBooking(booking);
               BookingResponse response = new BookingResponse();
              
               System.out.println(getWebServiceTemplate().getDefaultUri());
              
      
             response = (BookingResponse)getWebServiceTemplate().marshalSendAndReceive(request);
             System.out.println(response.getBookingNumber());
              bookingNumber = response.getBookingNumber();
           
        }catch(Exception ee)
        {
            ee.printStackTrace();
        }
        return bookingNumber;
    }
   
   
}

 6)index.jsp


<jsp:forward page="start.html"></jsp:forward> 

7)booking.jsp
 <%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>



<style>
.error {
    color: #ff0000;
    font: italized;
}

.errorblock {
    color: #000;
    background-color: #ffEEEE;
    border: 3px solid #ff0000;
    padding: 8px;
    margin: 16px;
}
</style>

<body>


<br>

<form:form method="post" commandName="bookingForm" modelAttribute="bookingForm" action="${pageContext.request.contextPath}/bookingComplete.html">

    <table width ="600" height="500" align="center" bgcolor="#ffffff">
     <tr>
        <td colspan="2" align="center">
            <h2>Booking Form</h2>
        </td>
    </tr>
    <tr>
        <td><form:label path="firstName"><strong>First Name</strong></form:label></td>
        <td><form:input path="firstName" /><br><form:errors path="firstName" cssClass="error" /></td>
    </tr>
  
    <tr>
        <td><form:label path="lastName"><strong>Last Name</strong></form:label></td>
        <td><form:input path="lastName"  /><br><form:errors path="lastName" cssClass="error" /></td>
    </tr>
    <tr>
        <td><form:label path="addressLine1"><strong>Address Line1</strong></form:label></td>
      <td><form:input path="addressLine1"  /><br><form:errors path="addressLine1" cssClass="error" /></td>
    </tr>
     <tr>
        <td><form:label path="addressLine2"><strong>Address Line2</strong></form:label></td>
       <td><form:input path="addressLine2"  /><br><form:errors path="addressLine2" cssClass="error" /></td>
    </tr>
   
   
     <tr>
        <td><form:label path="city"><strong>City</strong></form:label></td>
        <td><form:input path="city" /><br><form:errors path="city" cssClass="error" /></td>
    </tr>
  
     <tr>
        <td><form:label path="state"><strong>State</strong></form:label></td>
        <td><form:select path="state">
        <form:option value="" label="--- Select ---"/>
           <form:option value="Alabama" label="Alabama"/>
          <form:option value="Alaska" label="Alaska"/>
          <form:option value="Arizona" label="Arizona"/>
          <form:option value="Arkansas" label="Arkansas"/>
          <form:option value="California" label="California"/>
          <form:option value="Colorado" label="Colorado"/>
          <form:option value="Connecticut" label="Connecticut"/>
          <form:option value="Delawar" label="Delawar"/>
          <form:option value="Florida" label="Florida"/>
          <form:option value="Georgia" label="Georgia"/>
          <form:option value="Hawaii" label="Hawaii"/>
          <form:option value="Idaho" label="Idaho"/>
          <form:option value="Illinois" label="Illinois"/>
          <form:option value="Indiana" label="Indiana"/>
          <form:option value="Iowa" label="Iowa"/>
          <form:option value="Kansas" label="Kansas"/>
          <form:option value="Kentucky" label="Kentucky"/>
          <form:option value="Louisiana" label="Louisiana"/>
          <form:option value="Maine" label="Maine"/>
          <form:option value="Maryland" label="Maryland"/>
          <form:option value="Massachusetts" label="Massachusetts"/>
          <form:option value="Michigan" label="Michigan"/>
          <form:option value="Minnesota" label="Minnesota"/>
          <form:option value="Mississippi" label="Mississippi"/>
          <form:option value="Missouri" label="Missouri"/>
          <form:option value="Montana" label="Montana"/>
          <form:option value="Nebraska" label="Nebraska"/>
          <form:option value="Nevada" label="Nevada"/>
          <form:option value="New Hampshire" label="New Hampshire"/>
          <form:option value="New Jersey" label="New Jersey"/>
          <form:option value="New Mexico" label="New Mexico"/>
          <form:option value="New York" label="New York"/>
          <form:option value="North Carolina" label="North Carolina"/>
          <form:option value="North Dakota" label="North Dakota"/>
          <form:option value="Ohio" label="Ohio"/>
          <form:option value="Oklahoma" label="Oklahoma"/>
          <form:option value="Oregon" label="Oregon"/>
          <form:option value="Pennsylvania" label="Pennsylvania"/>
          <form:option value="Rhode Island" label="Rhode Island"/>
          <form:option value="South Carolina" label="South Carolina"/>
          <form:option value="South Dakota" label="South Dakota"/>        
          <form:option value="Tennessee" label="Tennessee"/>
          <form:option value="Texas" label="Texas"/>
          <form:option value="Utah" label="Utah"/>        
          <form:option value="Vermont" label="Vermont"/>
          <form:option value="Virginia" label="Virginia"/>
          <form:option value="Washington" label="Washington"/>
          <form:option value="Washington,D.C." label="Washington,D.C."/>
          <form:option value="West Virginia" label="West Virginia"/>
          <form:option value="Wisconsin" label="Wisconsin"/>
           <form:option value="Wyoming" label="Wyoming"/>
  
        </form:select>
            
    </tr>
  
       <tr>
        <td><form:label path="zip"><strong>Zip</strong></form:label></td>
        <td><form:input path="zip" /><br><form:errors path="zip" cssClass="error" /></td>
    </tr>
  
    <tr>
        <td><form:label path="email"><strong>Email</strong></form:label></td>
        <td><form:input path="email" /> <br><form:errors path="email" cssClass="error" /></td>
    </tr>
  
     <tr>
        <td><form:label path="mobile"><strong>Mobile</strong></form:label></td>
        <td><form:input path="mobile" /> <br><form:errors path="mobile" cssClass="error" /></td>
    </tr>
  
      <tr>
        <td><form:label path="phoneLandLine"><strong>Phone LandLine</strong></form:label></td>
        <td><form:input path="phoneLandLine" /> <br><form:errors path="phoneLandLine" cssClass="error" /></td>
    </tr>
   
     <tr>
        <td><form:label path="roomtype"><strong>Room Type</strong></form:label></td>
        <td><form:select path="roomtype">
      
           <form:option value="Standard" label="Standard"/>
          <form:option value="Deluxe" label="Deluxe"/>
          <form:option value="SemiDeluxe" label="SemiDeluxe"/>
          <form:option value="Luxury" label="Luxury"/>
          <form:option value="HoneymoonSuite" label="HoneymoonSuite"/>
        </form:select>
        </tr>
         <tr>
        <td><form:label path="quantity"><strong># of Rooms(To be Booked)</strong></form:label></td>
        <td><form:input path="quantity" /> <br><form:errors path="quantity" cssClass="error" /></td>
    </tr>
  
     <tr>
        <td><form:label path="checkinDate"><strong>Check In</strong></form:label></td>
        <td><form:input path="checkinDate" />  @ 1.00 PM (MM/DD/YYYY) <br><form:errors path="checkinDate" cssClass="error" /></td>
    </tr>
       <tr>
        <td><form:label path="checkoutDate"><strong>Check Out</strong></form:label></td>
        <td><form:input path="checkoutDate" /> @ 11.00 AM (MM/DD/YYYY) <br><form:errors path="checkoutDate" cssClass="error" /></td>
    </tr>
    <tr>
           <td colspan="2" align="center">
            <input type="submit" value="Book"/>
        </td>
    </tr>
  
</table>

</form:form>

8) confirm.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<html>




<body>
<form:form method="post" commandName="bookingForm" modelAttribute="bookingForm" >

<br>

<table width ="600" height="500" align="center" bgcolor="#ffffff">
     <tr>
        <td colspan="2" align="center">
            <h2>Thanks for Booking in our Hotel.Your booking number is :<form:input path="bookingNumber" size ="40" readonly="true"/>
           
           
            </h2>
        </td>
    </tr>
    </table>
    </form:form>
    </body> 

 

 

No comments:

Post a Comment