Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
617 views
in Technique[技术] by (71.8m points)

jakarta ee - Servlet vs RESTful

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.

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

Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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.

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);
    }

}

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:

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.

See also:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...