Use WebService in spring (restful style)

Source: Internet
Author: User
Tags soap

We generally use WebService to make remote calls, probably in two ways, one of which is simple and straightforward in the rest style.

Record down as notes:

Development Service side:

The specific grammar does not say anything, this online too much, and just look at the code basically understand, the following is the direct code:

Package Com.web.webservice.rs;import Java.util.iterator;import java.util.list;import javax.ws.rs.get;import Javax.ws.rs.path;import Javax.ws.rs.produces;import Org.slf4j.logger;import Org.slf4j.loggerfactory;import Org.springframework.beans.factory.annotation.autowired;import Com.google.common.collect.lists;import Com.web.module.index.model.dao.userdao;import Com.web.module.index.model.entity.User;/** * * * @author HOTUSM **/@Path ("/test") Public classUserService {Private StaticFinal Logger Logger=loggerfactory.getlogger (userservice.class);  Public StaticFinal String application_xml_utf_8 ="application/xml; Charset=utf-8"; @AutowiredPrivateUserdao Userdao; /** * * @Produces means the data format returned * @Consumes represents the accepted format type * @GET represents the requested type * @return * * <a href ="http://www.ibm.com/developerworks/cn/web/wa-jaxrs/"> Blog</a>*/@GET @Path ("/list") @Produces ("Application/json")     PublicList<user>list () {list<User> users=lists.newarraylist (); Iterable<User> iters =Userdao.findall (); Iterator<User> iterator =Iters.iterator ();  while(Iterator.hasnext ()) {Users.add (Iterator.next ()); }                returnusers; }        /** * * * Show link on webpage * @return*/@GET @Path ("/page") @Produces ("text/html")     PublicString page () {return "<a href= ' http://www.baidu.com ' > Baidu </a>"; }    }

This style and Springmvc is so much like, so a look basically understand.

Here is the configuration file:

<?xml version="1.0"encoding="UTF-8"? ><beans xmlns="Http://www.springframework.org/schema/beans"Xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"Xmlns:jaxrs="Http://cxf.apache.org/jaxrs"xsi:schemalocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http//Cxf.apache.org/jaxrshttp://cxf.apache.org/schemas/jaxrs.xsd"><import resource="Classpath*:meta-inf/cxf/cxf.xml"/> <import resource="Classpath*:meta-inf/cxf/cxf-extension-soap.xml"/> <import resource="Classpath*:meta-inf/cxf/cxf-servlet.xml"/> <jaxrs:server id="Rsservice"address="/jaxrs">
<!--where you can add some configuration, such as interceptors, and so on <jaxrs:serviceBeans> <refbean="Iuserservice"/> </jaxrs:serviceBeans> <jaxrs:providers> <beanclass="Com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider"/> </jaxrs:providers> </jaxrs:server> <bean id="Iuserservice" class="Com.web.webservice.rs.UserService"></bean></beans>

Once this is written, startup discovery is not available because we also need to configure Discovery ws in Web. xml:

Xml

    <servlet>        <Servlet-name>Cxfservlet</Servlet-name>        <Servlet-class>Org.apache.cxf.transport.servlet.CXFServlet</Servlet-class>        <Load-on-startup>2</Load-on-startup>    </servlet>    <!--This is set under RS to see the WS interface, so the service is behind this -    <servlet-mapping>        <Servlet-name>Cxfservlet</Servlet-name>        <Url-pattern>/rs/*</Url-pattern>    </servlet-mapping>

Note that when we do this now, we just need to enter $CTX/RS so the WS service below will see.

In fact, the use of spring is very simple. We only need to configure the above file, the most difficult is the logical part.

To develop the service side of WS:

1: Configuration XML file

<?XML version= "1.0" encoding= "UTF-8"?><Beansxmlns= "Http://www.springframework.org/schema/beans"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd" >        <BeanID= "Resttemplate"class= "Org.springframework.web.client.RestTemplate">
<!--set some properties, you can see the source--< Propertyname= "Requestfactory"> <Beanclass= "Org.springframework.http.client.SimpleClientHttpRequestFactory"> < Propertyname= "ReadTimeout"value= "30000"/> </Bean> </ Property> </Bean></Beans>

After configuring the client's configuration file, we can directly inject the resttemplate into the place we need to use, this class is spring to help me abstract out, there are many ways for us to use, in fact, the encapsulation of a layer, if not like, complete can self-encapsulation of a, Then inject:

Source:

protected<T>T doexecute (URI URL, HttpMethod method, Requestcallback requestcallback, Responseextractor<T> responseextractor)throwsrestclientexception {assert.notnull (URL,"' URL ' must not is null"); Assert.notnull (method,"' method ' must not being null"); Clienthttpresponse Response=NULL; Try{clienthttprequest Request=createrequest (URL, method); if(Requestcallback! =NULL) {requestcallback.dowithrequest (request); } Response=Request.execute (); if(!Geterrorhandler (). Haserror (response))            {Logresponsestatus (method, URL, response); }            Else{handleresponseerror (method, URL, response); }            if(Responseextractor! =NULL) {                returnResponseextractor.extractdata (response); }            Else {                return NULL; }        }        Catch(IOException ex) {Throw NewResourceaccessexception ("I/O error on" + method.name () + "Request for \" "+ URL +" \ ":" +ex.getmessage (), ex); }        finally {            if(Response! =NULL) {response.close (); }        }    }

The following is an example of a client invocation (with Springtest)

@RunWith (Springjunit4classrunner.class) @ContextConfiguration (Locations={"Classpath*:/spring-context.xml", "Classpath*:/spring-mq-provider.xml", "Classpath*:/spring-mq-consumer.xml", " Classpath*:/spring-jaxrs-service.xml "," Classpath*:/spring-jaxrs-client.xml "}) Public classresttest {@AutowiredPrivateresttemplate resttemplate; @Value ("${rest.service.url}") String URL; @Test Public voidTest () {//resttemplate=new resttemplate ();String str = Resttemplate.getforobject (url+ "Test/list", String.class); }}

Basically this will buy us to use.

Next time you're free. A summary of the SOAP method is also available.

Use WebService in spring (restful style)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.