Spring Web Services - Part 2 (Endpoint annotation and Database configuration)

Welcome to second part of 'Java Web Services using Spring' tutorial series. In this part of spring web services tutorial we will learn some important concepts related to endpoint annotation and configurations. In our previous discussions we came across What are Web Services, than we started creating a Simple Web Service in Spring. We covered creation of JAXB classes in previous discussion and covered 2 steps out of 4. In this particular blog we we came across how to configure endpoints in spring web services and will cover rest two steps of creating web services on Spring. Lets continue from step 3.

To begin with Creating Spring Web Services and know about initial 2 steps Click Here.

Step 3 : Create an Endpoint, Service and Dao layer classes for the application.

In java web services development spring provides a number of inbuild capabilities and that is the reason, recent days java web services are well known as spring web services and those are marely developing in spring itself. Now its time to create a Endpoint Class to our application so that a message receiving and sending contact point can be implemented.

\src\main\java\com\javaguys\webservices\endpoints\Endpoints.java

Endpoints are the core of Spring Web Services server-side support. A simple Java class can be used as endpoint by adding @Endpoint annotation to it. An Endpoint class can have any number of methods, these methods have a variety of annotations like @PayloadRoot. Annotations(mostly @PayloadRoot) applied to methods identifies which request message relates to which method. Endpoints accepts request messages as xml and interprets them to call a related service method. @PayloadRoot identifies that the method is responsible to handle an incoming requests and its attributes 'localpart' and 'namespace' identifies the request that will be handled. To know more about Endpoints Click Here.
package com.javaguys.webservices.endpoints;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ws.server.endpoint.annotation.Endpoint;
import org.springframework.ws.server.endpoint.annotation.PayloadRoot;
import org.springframework.ws.server.endpoint.annotation.RequestPayload;
import org.springframework.ws.server.endpoint.annotation.ResponsePayload;
import com.javaguys.services.UserService;
import com.javaguys.webservices.getUserServices.GetUserRequest;
import com.javaguys.webservices.getUserServices.GetUserResponse;
import com.javaguys.webservices.saveUserServices.SaveUserRequest;
import com.javaguys.webservices.saveUserServices.SaveUserResponse;

@Endpointpublic
class UserServiceEndpoints {
   private static final String GET_TARGET_NAMESPACE = "http://com/javaguys/webservices/getUserServices";
   private static final String SAVE_TARGET_NAMESPACE = "http://com/javaguys/webservices/saveUserServices";
   @Autowired
   private UserService userService;

   @PayloadRoot(localPart = "GetUserRequest", namespace = GET_TARGET_NAMESPACE)
   public @ResponsePayload GetUserResponse getUserDetails(@RequestPayload GetUserRequest request) {
      System.out.println("Get User !");
      GetUserResponse response = new GetUserResponse();
      response.setUserDetails(userService.getUserDetails(request.getUserId()));
      return response;
   }

   @PayloadRoot(localPart = "SaveUserRequest", namespace = SAVE_TARGET_NAMESPACE)
   public @ResponsePayload SaveUserResponse saveUserDetails(@RequestPayload SaveUserRequest request) {
      System.out.println("Save User !");
      SaveUserResponse response = new SaveUserResponse();
      response.setUserId(userService.saveUserDetails(request.getUserDetails()));
      return response;
   }

   public void setUserService(UserService userService_i) {
      this.userService = userService_i;
   }
}

In java part of web development spring is most commonly used framework as of today and that's the reason one can see spring with web services in java world. Now add dao layer classes to the application, and some database configurations to save and retrieve data.

\src\main\java\com\javaguys\dao\UserDao.java



package com.javaguys.dao;

import com.blog.javaguys.user.User;

public interface UserDao {
public User getUserDetails(String userId);
public String saveUserDetails(User user);
}


\src\main\java\com\javaguys\dao\UserDaoImpl.java

Here we have used @Repository annotation, this makes the class auto-detected through classpath scanning. @Repository clarifies its role by marking the specific class as a Data Access Object.
package com.javaguys.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.springframework.stereotype.Repository;
import com.blog.javaguys.user.User;

@Repositorypublic
class UserDaoImpl implements UserDao {
   public User getUserDetails(String userId) {
      User user = new User();
      String connectionURL = "jdbc:mysql://localhost:3306/userDB";
      Connection con = null;
      try {
         Class.forName("com.mysql.jdbc.Driver");
         con = DriverManager.getConnection(connectionURL, "root", "root");
         Statement stmt = con.createStatement();
         ResultSet rs = stmt.executeQuery("select * from user where id=" + userId);
         while (rs.next()) {
            user.setUserId(rs.getString("id"));
            user.setUserGender(rs.getString("gender"));
            user.setUserName(rs.getString("name"));
            user.setUserStatus(rs.getString("status"));
         }
      } catch (SQLException e) {
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            con.close();
         } catch (SQLException e) {
            e.printStackTrace();
         }
      }
      return user;
   }

   public String saveUserDetails(User user) {
      String connectionURL = "jdbc:mysql://localhost:3306/userDB";
      Connection con = null;
      try {
         Class.forName("com.mysql.jdbc.Driver");
         con = DriverManager.getConnection(connectionURL, "root", "root");
         Statement stmt = con.createStatement();
         int i = stmt.executeUpdate("insert into user values ('" + user.getUserId() + "','" + user.getUserName()
               + "','" + user.getUserGender() + "','" + user.getUserStatus() + "')");
         System.out.println("Succeded !");
      } catch (SQLException e) {
         e.printStackTrace();
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            con.close();
         } catch (SQLException e) {
            e.printStackTrace();
         }
      }
      return user.getUserId();
   }
}

\src\main\java\com\javaguys\services\UserService.java

package com.javaguys.services;

import com.blog.javaguys.user.User;

public interface UserService {
   public User getUserDetails(String userId);

   public String saveUserDetails(User user);
}

\src\main\java\com\javaguys\services\UserServiceImpl.java

Now this is the time to face actual part of java web services or we can say spring web services, finally the time comes over we will use the term service. Here we have used @Service annotation, this makes the class auto-detected through classpath scanning. @Service is a specialization of @Component, the reason behind using @Service rather than @Component is that it follows industrial best practices and makes a clear view that the class is used as a Service.
package com.javaguys.services;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.blog.javaguys.user.User;
import com.javaguys.dao.UserDao;

@Servicepublic
class UserServiceImpl implements UserService {
   @Autowired
   private UserDao userDao;

   public User getUserDetails(String userId) {
      return userDao.getUserDetails(userId);
   }

   public String saveUserDetails(User user) {
      return userDao.saveUserDetails(user);
   }

   public void setUserDao(UserDao userDao) {
      this.userDao = userDao;
   }
}


Step 4 : Create spring-configurations and entries in web.xml

Create WEB-INF under webapp folder and add web.xml and spring-config.xml files there as follows.

\src\main\webapp\WEB-INF\web.xml

This is the entry point of the application, we have declared an servlet for MessageDispatcherServlet it tells the container that all requests associated with '/endpoints' will be handled by Spring itself.
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
   <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>   /WEB-INF/config/spring-config.xml  </param-value>
   </context-param>
   <listener>
      <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
   </listener>
   <servlet>
      <servlet-name>webservices</servlet-name>
      <servlet-class>org.springframework.ws.transport.http.MessageDispatcherServlet</servlet-class>
      <init-param>
         <param-name>transformWsdlLocations</param-name>
         <param-value>true</param-value>
      </init-param>
      <init-param>
         <param-name>contextConfigLocation</param-name>
         <param-value></param-value>
      </init-param>
      <load-on-startup>1</load-on-startup>
   </servlet>
   <servlet-mapping>
      <servlet-name>webservices</servlet-name>
      <url-pattern>*.wsdl</url-pattern>
   </servlet-mapping>
   <servlet-mapping>
      <servlet-name>webservices</servlet-name>
      <url-pattern>/endpoints/*</url-pattern>
   </servlet-mapping>
</web-app>

\src\main\webapp\WEB-INF\config\spring-config.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: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/web-services       http://www.springframework.org/schema/web-services/web-services-2.0.xsd       http://www.springframework.org/schema/context       http://www.springframework.org/schema/context/spring-context-3.0.xsd">
   <context:component-scan  base-package="com.javaguys.services,com.javaguys.webservices,com.javaguys.dao," />
   <sws:annotation-driven />
   <!-- Our test service bean --> 
   <bean id="GetUserService"  class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition"  lazy-init="true">
      <property name="schemaCollection">
         <bean    class="org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection">
            <property name="inline" value="true" />
            <property name="xsds">
               <list>
                  <value>schemas/GetUserServiceOperations.xsd</value>
               </list>
            </property>
         </bean>
      </property>
      <property name="portTypeName" value="GetUserService" />
      <property name="serviceName" value="GetUserService" />
      <property name="locationUri" value="/endpoints" />
   </bean>
   <bean id="SaveUserService"  class="org.springframework.ws.wsdl.wsdl11.DefaultWsdl11Definition"  lazy-init="true">
      <property name="schemaCollection">
         <bean    class="org.springframework.xml.xsd.commons.CommonsXsdSchemaCollection">
            <property name="inline" value="true" />
            <property name="xsds">
               <list>
                  <value>schemas/SaveUserServiceOperations.xsd</value>
               </list>
            </property>
         </bean>
      </property>
      <property name="portTypeName" value="SaveUserService" />
      <property name="serviceName" value="SaveUserService" />
      <property name="locationUri" value="/endpoints" />
   </bean>
</beans>
Run the project on Server, if everything goes right you will get a welcome page as shown below, click one of the link provided to see the WSDL of related service.


This part of tutorial can be concluded saying that, java web services are commonly developing in spring these days and this is turning the story of java web services to spring web services. Here we are all done with creating a working Spring Web Service application, in our next tutorial we will test the Web Service and come to know how to create Web Services Client.