在JavaScript和Java中默认是否支持REST,还是需要安装新软件?

时间:2010-08-07 21:46:59

标签: java javascript rest

我是否需要安装新软件以使用JavaScript和Java的REST服务?

3 个答案:

答案 0 :(得分:2)

除了Web服务器之外,您不需要任何其他内容。 REST的基本观点是:

  • 每个“资源”都有一个URI(读取“URL”)地址
  • 每个资源都可以处理四种基本的HTTP方法:GET,PUT,POST,DELETE

因此,假设您有一个客户记录,并且记录带有ID号。您可能会使用类似

的URL标识客户
http://example.com/customer/124c41

该URL上的GET将为您提供显示信息; PUT会更新它;一个POST会创建它(大多数人实际上使用POST,正式你想要PUT)和DELETE删除它。

你有责任处理确切的实施,但这就是模型。

答案 1 :(得分:1)

不,你没有。只能使用Javascript中的任何URL访问仅使用GET和POST HTTP谓词的REST服务。最常见的是,您将使用AJAX访问REST服务并对响应执行某些操作。

答案 2 :(得分:1)

另一件需要考虑的事情是客户方。

您可以使用标准Java SE API:

private void updateCustomer(Customer customer) {
    try {
        URL url = new URL("http://www.example.com/customers");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setInstanceFollowRedirects(false);
        connection.setRequestMethod("PUT");
        connection.setRequestProperty("Content-Type", "application/xml");

        OutputStream os = connection.getOutputStream();
        jaxbContext.createMarshaller().marshal(customer, os);
        os.flush();

        connection.getResponseCode();
        connection.disconnect();
    } catch(Exception e) {
        throw new RuntimeException(e);
    }
}

或者您可以使用JAX-RS实现(如Jersey)提供的REST客户端API。这些API更易于使用,但在类路径上需要额外的jar。

WebResource resource = client.resource("http://www.example.com/customers");
ClientResponse response = resource.type("application/xml");).put(ClientResponse.class, "<customer>...</customer.");
System.out.println(response);