2
我的問題可能是愚蠢的,但我在Web服務的世界是新的,我找到了一個教程,但我有一些懷疑。它使用Apache CXF
。我有Calculator
類擁有所有的資源,CalculatorStartUp
將啓動服務器,並Client
類,我有更多的客戶端。 貝婁是代碼:Apache CXF客戶端訪問多個資源
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) + "";
}
}
服務器:
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();
}
}
客戶:
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);
}
我的問題是:
爲什麼有兩個客戶端?如果我爲
mul
和div
資源編寫一些資源,該怎麼辦?我是否需要添加更多資源..爲什麼要爲每個資源編寫客戶端?必須有一種方法可以只創建一個可以訪問特定資源的客戶端。我看到,在創建Web客戶端時,您可以傳遞提供者或提供者列表。任何人都可以解釋這些供應商代表什麼?
我將不勝感激任何幫助!