Java and J2EE Tutorials, Jsp and Servlet Tutorials, Spring MVC, Solr, XML, JSON Examples, Hibernate & Struts 2 Hello World projects



Thursday, 25 April 2013

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;


@Endpoint
public 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;

@Repository
public 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;

@Service
public 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. We will also come to know How to check a Web Service output without using a client application.










Thanks for reading !
Being Java Guys Team

Download "Spring Web Service Example project" from "SkyDrive"





13 comments:

  1. Thanks for uploading useful tutorial.how can i build war using maven? i am not able to generate war file

    ReplyDelete
    Replies
    1. Hi, thanks for your appreciation

      Creating war with maven is easy, infact this is the thing maven is build for.

      Do one thing, download project from upper link and import it in Eclipse, then go for Maven Build and apply command war:war. Look in target folder for your .war file.

      You can also check http://maven.apache.org/plugins/maven-war-plugin/for more info .

      Delete
  2. Hi i did workout as per your tutorial eventually i can not get wsdl "http://localhost:8080/spring-server-final/endpoints/GetUserService.wsdl" 404 exception occurred.mean time i downloaded your source code from skydrive and tested same things happened.things done
    1.after mvn install take war from target and pasted into the webapps of tomcat folder.
    2. then start the server "bash startup.sh"

    ReplyDelete
    Replies
    1. this problem is fixed by configuring .war file to be deployed.

      Delete
  3. Hi,

    When I run this example in eclipse with Tomcat6, http://localhost:8080/spring-server-final/ diplay nothing, just a blanc empty page.

    But when I type :

    http://localhost:8080/spring-server-final/endpoints/SaveUserService.wsdl
    I got an xml file displayed in the browser.

    http://localhost:8080/spring-server-final/endpoints/GetUserService.wsdl
    I got an xml file displayed in the browser.

    Is there anything missing ?
    thanks, your help is appreciated.

    ReplyDelete
  4. Guys why dont you just use GitHub to host your code?? #JustAsking.

    ReplyDelete
  5. hello friend , I made client for your webservice and it is running well . then I tried to make client for my own spring webservice which is configured very like to yours , but client is not working . I have integer and float fields in my xsd file . where can I send you my client , so that you provide it for this webservice and same time I send you my project . I say my and your projects are like brothers , but my client is refusing to cooperate with me . I don't already know what to think . write me at devdevc@hotmail.com , I send you client for this webservice

    ReplyDelete
  6. does fields names matter against database tables fields? I mean : if in database table customers filed is named firstname , i have anyway to tell CustomersFirstname /like you have / ? or I can name say fName in my xsd? I think my problem is in this xsd file :






























































































    this xsd produces wsdl , but validation doesn't happen when sending request ...
    I think something has to be changed

    ReplyDelete
    Replies
    1. just study more , try more , everything gonna be ok

      Delete
  7. Hi,

    When I run this example in eclipse with Tomcat6, http://localhost:8080/spring-server-final/ display nothing, just a blank empty page.

    But when I type :

    http://localhost:8080/spring-server-final/endpoints/SaveUserService.wsdl
    I got an xml file displayed in the browser.

    http://localhost:8080/spring-server-final/endpoints/GetUserService.wsdl
    I got an xml file displayed in the browser.

    Is there anything missing ?
    please help on this

    ReplyDelete
  8. can you provide the client to invoke the service

    ReplyDelete
  9. Hi,

    Thank you for this post :).
    I want to change the generated url "http://localhost:8080" to "http:192.168.25.23:9812".

    Can you help me please

    ReplyDelete

Like Us on Facebook


Like Us On Google+



Contact

Email: neel4soft@gmail.com
Skype: neel4soft