Java WebService - Create your first web service in Java

By: Emiley J Emailed: 1642 times Printed: 2111 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

If you are tasked to develop a web service in Java, you will probably try to google around and check how to get started. If you are a beginner in Web Services, you will surely get confused with the various tools, terms, acronyms, technologies related to Java based web services. In reality, it is NOT that complex. The problem usually lies in the fact that there is no complete tutorial for a beginner. Of course you can find some on the web, but they normally tend to use complex acronyms and steps that will confuse the beginner. Therefore this tutorial will help you to create your first Java web service using just the command prompt and JDK.

Here are the pre-requisites that you need to have.

  • Download and install the latest JDK (jdk 1.7)
  • Create two environment variables in your system JAVA_HOME -> Point to your jdk installation folder. In PATH environment variable, if you have previous jdk paths, remove it and add the /bin
That's it. You are ready to develop your first Java WebService.

Now open the command prompt and create a folder named "javasamples" ( md javasamples )
Next cd javasamples to goto that folder. Now create another folder named "one" ( md one )
Next create a file named TimeServer.java ( notepad TimserServer.java )
Copy the below code in that file and save it.

package javasamples.one;  // time server

import javax.jws.WebService;
import javax.jws.WebMethod;
import javax.jws.soap.SOAPBinding;
import javax.jws.soap.SOAPBinding.Style;

/**
 *  The annotation @WebService signals that this is the
 *  SEI (Service Endpoint Interface). @WebMethod signals 
 *  that each method is a service operation.
 *
 *  The @SOAPBinding annotation impacts the under-the-hood
 *  construction of the service contract, the WSDL
 *  (Web Services Definition Language) document. Style.RPC
 *  simplifies the contract and makes deployment easier.
*/


@WebService
@SOAPBinding(style = Style.RPC) // more on this later
public interface TimeServer {
    @WebMethod String getTimeAsString();
    @WebMethod long getTimeAsElapsed();
}

Next create a file named TimeServerImpl.java ( notepad TimserServerImpl.java )
Copy the below code in that file and save it.

package javasamples.one; 
import java.util.Date;
import javax.jws.WebService;

/**
 *  The @WebService property endpointInterface links the
 *  SIB (this class) to the SEI (javasamples.one.TimeServer).
 *  Note that the method implementations are not annotated
 *  as @WebMethods.
*/

@WebService(endpointInterface = "javasamples.one.TimeServer")

public class TimeServerImpl implements TimeServer {

    public String getTimeAsString() { return new Date().toString(); }
    public long getTimeAsElapsed() { return new Date().getTime(); }

}

Now you can check whether everything is fine by compiling.
First go to the folder above javasamples
Next compile the two files by executing this command ( javac javasamples/one/*.java )
If there are no errors then congratulate yourself. You have just developed a webservice that returns the system time. Its a time server.

If you get a compile error, then check this solution for package javax.jws does not exist

Wait, thats not all. You have developed the webservice alright. But you need to publish it right? If you don't publish it, then nobody will be able to find it and consume it. Therefore the next step is to publish your service.

Normally, in a production system, you will publish the web service in a server such as GlassFish, Jboss, Websphere etc.. But while testing and in development, we will just create a simple java application that will publish this web service in localhost.

Go to the javasamples/one folder.
Now create a new java file named TimeServerPublisher.java ( notepad TimeServerPublisher.java )
And copy the below code into it.

package javasamples.one;

import javax.xml.ws.Endpoint;

/**
 * This application publishes the web service whose
 * SIB is javasamples.one.TimeServerImpl. For now, the 
 * service is published at network address 127.0.0.1.,
 * which is localhost, and at port number 9876, as this
 * port is likely available on any desktop machine. The
 * publication path is /one, an arbitrary name.
 * The Endpoint class has an overloaded publish method.
 * In this two-argument version, the first argument is the
 * publication URL as a string and the second argument is
 * an instance of the service SIB, in this case
 * ch01.ts.TimeServerImpl.

 * The application runs indefinitely, awaiting service requests.
 * It needs to be terminated at the command prompt with control-C
 * or the equivalent.

 * Once the applicatation is started, open a browser to the URL
 *     http://127.0.0.1:9876/one?wsdl
 *
 * to view the service contract, the WSDL document. This is an
 * easy test to determine whether the service has deployed
 * successfully. If the test succeeds, a client then can be
 * executed against the service.

*/

public class TimeServerPublisher {

    public static void main(String[ ] args) {

      // 1st argument is the publication URL
      // 2nd argument is an SIB instance

      Endpoint.publish("http://127.0.0.1:9876/one", new TimeServerImpl());

    }

}

Now you can check whether everything is fine by compiling.
First go to the folder above javasamples
Next compile the two files by executing this command ( javac javasamples/one/*.java )
If there are no errors then congratulate yourself. You have just developed a webservice that returns the system time. Its a time server.

If you get a compile error, then check this solution for package javax.jws does not exist

Finally, you need to start your TimeServerPublisher class. You can do this like ( java javamples.one.TimeServerPublisher ). That't It. You have created your first java web service and publish it. You can double check whether it works by opening your brower and going to http://127.0.0.1:9876/one


WebServices Home | All WebServices Tutorials | Latest WebServices Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.



Bookmark and Share

Comments(6)


1. View Comment

Thank you for this tutorial. Thank you all the more, for making it simple and showing how it is done right from the basics without an IDE. It helped me a lot.

View Tutorial          By: sd at 2013-09-09 05:38:52
2. View Comment

So I followed you steps with no compile errors. When I go to the URL I recive the following message:
Web Services
No JAX-WS context information available.

If I add ?wsdl at the end of the URL I do get xml returned, but no time.

How do I get the service to return the time?

Thank you,


View Tutorial          By: PointLookoutResident at 2014-10-14 19:01:11
3. View Comment

This is just the web service, if you want to consume it, you need to create a program to consume it

java javamples.one.TimeServerPublisher

Do not close the publisher and go to folder javasamples/one

run the next command:

wsimport -s . http://127.0.0.1:9876/one?wsdl

It will create a structure of java files and will compile them.

Create file javasamples/one/TimeClient.java

Copy this content inside file TimeClient.java :
import javasamples.one.TimeServer;
import javasamples.one.TimeServerImplService;

public class TimeClient {

/**
* @author Carlos Kassab
*/
public static void main(String[] args) {

TimeServerImplService timeServerService = new TimeServerImplService();
TimeServer timeServer = timeServerService.getTimeServerImplPort();
System.out.println(timeServer.getTimeAsString());
}
}

From the command window, go to folder javasamples/one
Compile program TimeClient.java: javac TimeClient.java

Run program: java TimeClient.java
You should see something like this: Fri Feb 20 11:10:57 CST 2015


View Tutorial          By: Carlos Kassab at 2015-02-20 17:18:06
4. View Comment

Thanks a ton!!! It was really very useful :)

View Tutorial          By: Ankit at 2015-05-11 12:30:41
5. View Comment

when i try to compile the two files by executing this command ( javac javasamples/one/*.java ) i get
javasamplesoneTimserServer.java:12: error: class TimeServer is public, should
be declared in a file named TimeServer.java
public interface TimeServer {
^
javasamplesoneTimserServerImpl.java:8: error: class TimeServerImpl is public,
should be declared in a file named TimeServerImpl.java
public class TimeServerImpl implements TimeServer {
^
2 errors


please help!


View Tutorial          By: Brian at 2015-08-05 12:15:37
6. View Comment

@Brian rename the file name to match the class name (in this case TimeServer.java and TimeServerIpImpl.java) and try again goodluck

View Tutorial          By: QuangQUang at 2015-09-27 14:44:37

Your name (required):


Your email(required, will not be shown to the public):


Your sites URL (optional):


Your comments:



More Tutorials by Emiley J
Password must include both numeric and alphabetic characters - Magento
What is Hadoop?
Returning multiple values from a web service
Tomcat and httpd configured in port 8080 and 80
Java Webservices using Netbeans and Tomcat
Java WebService connected to Database
How to Deploy a Java Web Service
Call a webservice in Java
Java WebService - Create your first web service in Java
package javax.jws does not exist
Getting Started with Android
HTML5 Location - getCurrentPosition() in HTML5
HTML5 Canvas - Using Canvas in HTML5
HTML5 - Introduction
HTML5 Video - Handling video in HTML5

More Tutorials in WebServices
Returning multiple values from a web service
Java Webservices using Netbeans and Tomcat
How to Deploy a Java Web Service
Java WebService connected to Database
package javax.jws does not exist
Java WebService - Create your first web service in Java
Call a webservice in Java

More Latest News
Most Viewed Articles (in WebServices )
Call a webservice in Java
Java WebService - Create your first web service in Java
Java WebService connected to Database
package javax.jws does not exist
Returning multiple values from a web service
How to Deploy a Java Web Service
Java Webservices using Netbeans and Tomcat
Most Emailed Articles (in WebServices)
Java Webservices using Netbeans and Tomcat
Java WebService connected to Database
Returning multiple values from a web service
package javax.jws does not exist
Call a webservice in Java
How to Deploy a Java Web Service
Java WebService - Create your first web service in Java