本文介绍了Servlet 与 RESTful的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

今天我读到了 Restful 服务.基本上我的理解是,Restful webservices 将在 HTTP 请求方法上工作,而不是普通的 webservice 将在 SOAP 请求上工​​作.

Today I read about Restful services. Basically what I understand that is Restful webservices will work on HTTP request methods rather than normal webservice will work on SOAP request.

Restful 服务需要什么,因为普通的 servlet 也可以在 HTTP 方法上工作?

What is the need for Restful services as normal servlet can also work on the HTTP methods?

推荐答案

RESTful 与其说是一种不同的技术,不如说是一种架构风格.从服务器的角度来看,它被设计为完全无状态和基于每个请求的自包含(即有没有会话).从客户端的角度来看,它更像是一种通过带有(自记录)路径参数而不是请求参数的 URL 获取不同格式信息的方式.

RESTful is more an architecture style than a different technology. In server perspective, it is designed to be entirely stateless and self-contained on a per-request basis (i.e. there are no sessions). In client perspective, it's more a way of getting information in different formats via URLs with (self-documenting) path parameters instead of request parameters.

当然,您可以使用普通的 vanilla servlet 做到这一点,但它会引入一些样板代码来收集路径参数并生成所需的响应.JAX-RS 只是一个方便且自包含的 API,它消除了您自己编写所有样板代码的需要,从而产生最少且更多的自文档化代码.

Surely you can do this with a plain vanilla servlet, but it would introduce some boilerplate code to gather the path parameters and to generate the desired response. JAX-RS is just a convenient and self-containing API which removes the need for writing all the boilerplate code yourself, resulting in minimal and more self-documenting code.

假设您有一个 JAXB 实体作为模型,如下所示:

Assuming that you've a JAXB entity as model as below:

@XmlRootElement
public class Data {

    @XmlElement
    private Long id;

    @XmlElement
    private String value;

    // ...

    @Override
    public String toString() {
        return String.format("Data[id=%d,value=%s]", id, value);
    }

}

还有一个 JAX-RS 资源如下:

And a JAX-RS resource as below:

@Path("data")
public class DataResource {

    @EJB
    private DataService service;

    @GET 
    @Path("text/{id}")
    @Produces(MediaType.TEXT_PLAIN)
    public String getAsText(@PathParam("id") Long id) {
        return String.valueOf(service.find(id));
    }

    @GET 
    @Path("xml/{id}")
    @Produces(MediaType.APPLICATION_XML)
    public Data getAsXml(@PathParam("id") Long id) {
        return service.find(id);
    }

    @GET 
    @Path("json/{id}")
    @Produces(MediaType.APPLICATION_JSON)
    public Data getAsJson(@PathParam("id") Long id) {
        return service.find(id);
    }

}

然后您就可以通过以下方式获得所需内容的正确格式:

Then you'd already get the desired content in proper format by:

就是这样.尝试对单个普通的 Servlet 执行相同的操作 :) 请注意 SOAP 本质上通过 HTTP.它基本上是基于 HTTP 的额外 XML 层,而不是不同的网络协议.

That's it. Try to do the same with a single plain vanilla Servlet :) Please note that SOAP essentially also goes over HTTP. It's basically an extra XML layer over HTTP, not a different network protocol.

这篇关于Servlet 与 RESTful的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-11 20:32