Creating a web service implementation class

JAX-WS annotations were added in Java EE 5.0. Using these annotations, we can turn any Java class (including POJOs) into a web service. Use the @Webservice annotation to make any Java class a web service. This annotation can be used either on an interface or on a Java class. If a Java class is annotated with @Webservice, then all public methods in the class are exposed in the web service. If a Java interface is annotated with @Webservice, then the implementation class still needs to be annotated with @Webservice and with the endpointInterface attribute and its value as the interface name.

Before we create the web service implementation class, let's create a few helper classes. The first one is the Course data transfer object. This is the same class that we created in previous chapters. Create the Course class in the packt.jee.eclipse.ws.soap package:

package packt.jee.eclipse.ws.soap; 
 
public class Course { 
  private int id; 
  private String name; 
  private int credits; 
 
  //Setters and getters follow here 
} 

Let's now create the web service implementation class CourseManagementService in the packt.jee.eclipse.ws.soap package:

package packt.jee.eclipse.ws.soap; 
 
import java.util.ArrayList; 
import java.util.List; 
 
import javax.jws.WebService; 
 
@WebService 
public class CourseManagementService { 
 
  public List<Course> getCourses() { 
    //Here courses could be fetched from database using, 
    //for example, JDBC or JDO. However, to keep this example 
    //simple, we will return hardcoded list of courses 
 
    List<Course> courses = new ArrayList<Course>(); 
 
    courses.add(new Course(1, "Course-1", 4)); 
    courses.add(new Course(2, "Course-2", 3)); 
 
    return courses; 
  } 
 
  public Course getCourse(int courseId) { 
    //Here again, we could get course details from database using 
    //JDBC or JDO. However, to keep this example 
    //simple, we will return hardcoded course 
 
    return new Course(1,"Course-1",4); 
  } 
} 

CourseManagementService has the following two methods: getCourses and getCourse. To keep the example simple, we have hardcoded the values, but you can very well fetch data from a database, for example, using the JDBC or JDO APIs that we have discussed earlier in this book. The class is annotated with @WebService, which tells the JAX-WS implementation to treat this class as a web service. All methods in this class will be exposed as web service operations. If you want a specific method to be exposed, you could use @WebMethod.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.234.28