[JAX-WS] Simple webservice and client

1. Create a new Dynamic Web Project LibraryWS.
2. Create a package webservice
3. Create a class BookWebService

package webservice;
import java.util.ArrayList;
import java.util.List;
import javax.jws.WebMethod;
import javax.jws.WebService;
@WebService
public class BookWebService {
	List<Book> allBooks = new ArrayList<>();
	@WebMethod
	public List<Book> getAllBooks() {
		return allBooks;
	}
	@WebMethod
	public void addBook (Book book) {
		this.allBooks.add(book);
	}
}

4. Create a class Book

package webservice;
public class Book {
	private String title;
	private int pages;
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	public int getPages() {
		return pages;
	}
	public void setPages(int pages) {
		this.pages = pages;
	}
	@Override
	public String toString() {
		return "Book [title=" + title + ", pages=" + pages + "]";
	}
}

5. Run on Server (Glassfish!).
6. You should be able to access the service here:
http://localhost:8080/LibraryWs/BookWebServiceService
7. Go to http://localhost:8080/LibraryWs/BookWebServiceService?wsdl for the wsdl (copy this URL)
8. Create a new Simple Java Project LibraryClient
9. Go to command line to a tmp folder and type:

wsimport -keep http://localhost:8080/LibraryWs/BookWebServiceService?wsdl

10. Copy the generated folder webservice into eclipse under src so that you get the package webservice
11. Create the MainClient class in eclipse:

package root;
import java.util.List;
import javax.xml.ws.WebServiceRef;
import webservice.Book;
import webservice.BookWebService;
import webservice.BookWebServiceService;
public class MainClient {
	@WebServiceRef(wsdlLocation="http://localhost:8080/LibraryWs/BookWebServiceService?wsdl")
	private static BookWebServiceService service;
	public static void main(String[] args) {
		MainClient cl = new MainClient();
		cl.start();
	}
	public void start() {
		service = new BookWebServiceService();
		BookWebService port = service.getBookWebServicePort();
		System.out.println("All books: "+port.getAllBooks());
		Book book = new Book();
		book.setTitle("Journey");
		book.setPages(233);
		port.addBook(book);
		System.out.println("All books: "+port.getAllBooks());
	}
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s