Factorial Web Services Example
Here we will show you how you can develop a webservice that calculates the factorial. We will also write the code to call the webservice.
NetBeans provides the wizard to help the developer to create, deploy and test the webservices application very quickly.
In this project we will make a web service program for factorial calculation.
Then develop a Java Client file instead of Servlet or Jsp
Take a new web project.Give it the name Java-WebService
Select the Glassfish Server
Right Click on the project and select the New Web Service
Now give the Web Service Name as factorial
It will create a web service in design view
Click on the Add Operation
Now in the fig give the name as fact1
Return type as String
Give one parameter name x
Data type as int
Click on ok
This will create the Web Service code with the
name as factorial and method name as fact1
This will be having the annotation as
@Webservice ,@Webmethod and @Webparam
Now click on the source view
Here make some modification in the business logic for factorial calculation
package pack1;
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;
@WebService()
public class factorial {
int fact=1;
@WebMethod(operationName = "fact1")
public String fact1(@WebParam(name = "x") int x) {
for (int y=1;y<=x;y++){
fact=fact*y;
}
return "factorial of "+x +" is "+fact;
}
}
Now build it
Deploy it on the server
After deployment it can be tested
So Right Click on it .
Select the Test Web Service
It will run the web service on the server and displayed in the browser
Here give the value 4 in the text box and click on fact1
It will display the calculated factorial with the SOAP request and SOAP response
Now we will make a new project for the Client
Take a new Java Application project
Give the name as Java-webservice-Client
Now Right Click on this client project
Select NewàWebService Client
In the Dialog box give the WSDL url.
Copy it from the browser and paste here
0
It will generate the client environment variables in the project
Now take a new Java class named Client.java
Right Click in it and then select
Web Service Client Resources àcall Web Service Operation
1
Now select the WebService name->Web Service port nameàWeb Service Operation Name
2
Click on Ok .
It generates the code
In this code give int x=5;
Now run this file .It will run the file call the web service and
Print the result as the factorial .
package pack1;
public class Client1 {
public static void main(String[] args) {
try {
pack1.FactorialService service = new pack1.FactorialService();
pack1.Factorial port = service.getFactorialPort();
int x = 5;
java.lang.String result = port.fact1(x);
System.out.println("Result = "+result);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
3