My question might be stupid but I am new in the world of web services and I found a tutorial but I have some doubts about it. It is using Apache CXF
. I have the Calculator
class which has all the resources, CalculatorStartUp
which will startup the server, and the Client
class where I have more clients.
Bellow is the code:
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
@Path("/calc")
public class Calculator {
@GET
@Path("/add/{a}/{b}")
@Produces(MediaType.TEXT_PLAIN)
public String addPlainText(@PathParam("a") double a, @PathParam("b") double b) {
return (a + b) + "";
}
@GET
@Path("/sub/{a}/{b}")
@Produces(MediaType.TEXT_PLAIN)
public String subPlainText(@PathParam("a") double a, @PathParam("b") double b) {
return (a - b) + "";
}
}
Server:
import org.apache.cxf.endpoint.Server;
import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
import org.apache.cxf.jaxrs.lifecycle.SingletonResourceProvider;
public class CalculatorStartUp {
public static void main(String[] args) {
JAXRSServerFactoryBean sf = new JAXRSServerFactoryBean();
sf.setResourceClasses(Calculator.class);
sf.setResourceProvider(Calculator.class,
new SingletonResourceProvider(new Calculator()));
sf.setAddress("http://localhost:9999/calcrest/");
Server server = sf.create();
}
}
Client:
import org.apache.cxf.jaxrs.client.WebClient;
public class Client {
final static String REST_URI = "http://localhost:9999/calcrest";
final static String ADD_PATH = "calc/add";
final static String SUB_PATH = "calc/sub";
final static String MUL_PATH = "calc/mul";
final static String DIV_PATH = "calc/div";
public static void main(String[] args) {
int a = 122;
int b = 34;
String s = "";
WebClient plainAddClient = WebClient.create(REST_URI);
plainAddClient.path(ADD_PATH).path(a + "/" + b).accept("text/plain");
s = plainAddClient.get(String.class);
System.out.println(s);
WebClient plainSubClient = WebClient.create(REST_URI);
plainSubClient.path(SUB_PATH).path(a + "/" + b).accept("text/plain");
s = plainSubClient.get(String.class);
System.out.println(s);
}
My questions are:
why there are two clients? what if I write some resources for the
mul
anddiv
resources? Do I need to add more resources..why write a client for each resource? there has to be a way to create only one client that can access a certain resource.I saw that when creating a web client you can pass a provider or a list of providers. Can anyone explain what those providers represent?
I would appreciate any help!