在spring中使用webservice(Restful風格)


我們一般都會用webservice來做遠程調用,大概有兩種方式,其中一種方式rest風格的簡單明了。

記錄下來作為筆記:

開發服務端:

具體的語法就不講什么了,這個網上太多了,而且只要看一下代碼基本上都懂,下面是直接貼代碼:

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 class UserService {
    
    private static final Logger logger=LoggerFactory.getLogger(UserService.class);
    
    public static final String APPLICATION_XML_UTF_8 = "application/xml; charset=UTF-8";
    @Autowired
    private UserDao userDao;
    
    /**
     * 
     * @Produces 表示返回的數據格式 
     * @Consumes 表示接受的格式類型
     * @GET 表示請求的類型
     * @return
     * 
     * <a href="http://www.ibm.com/developerworks/cn/web/wa-jaxrs/"> BLOG</a>
     */
    @GET
    @Path("/list")
    @Produces("application/json")
    public List<User> list(){
        List<User> users=Lists.newArrayList();
        Iterable<User> iters = userDao.findAll();
        Iterator<User> iterator = iters.iterator();
        while(iterator.hasNext()){
            users.add(iterator.next());
        }
        
        return users;
    }
    
    /**
     * 
     * 在網頁上顯示鏈接
     * @return
     */
    @GET
    @Path("/page")
    @Produces("text/html")
    public String page(){
        
        return "<a href='http://www.baidu.com'>百度</a>";
    }
    
}

這個風格和springmvc實在太像了,所以一看基本上就懂了。

下面是配置文件:

<?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/jaxrs http://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">
      <!--在其中可以添加一些配置,比如攔截器等等的--> <jaxrs:serviceBeans> <ref bean="iuserService"/> </jaxrs:serviceBeans> <jaxrs:providers> <bean class="com.fasterxml.jackson.jaxrs.json.JacksonJaxbJsonProvider"/> </jaxrs:providers> </jaxrs:server> <bean id="iuserService" class="com.web.webservice.rs.UserService"></bean> </beans>

寫好這些之后,啟動發現並不能夠使用,這是因為我們還需要在web.xml中配置發現ws:

web.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>
    <!-- 這樣設置在rs下面才能看到ws的界面,所以的服務都在這個后面 -->
    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/rs/*</url-pattern>
    </servlet-mapping>

注意我們現在這樣做以后,我們只要輸入$ctx/rs那么下面所以的ws服務都能看到了。

其實使用spring的話,是非常的簡單的。我們只需要配置一下上面的文件,最難的還是邏輯部分。

開發ws的服務端:

1:配置xml文件

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="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">
    
    <bean id="restTemplate" class="org.springframework.web.client.RestTemplate">
  <!--設置一些屬性,具體的可以看源碼--> <property name="requestFactory"> <bean class="org.springframework.http.client.SimpleClientHttpRequestFactory"> <property name="readTimeout" value="30000"/> </bean> </property> </bean> </beans>

配置好了客戶端的配置文件以后,我們就可以直接將restTemplate注入到我們需要使用的地方中去,這個類是spring幫我抽象出來的,里面有很多方法供我們的使用,其實就是封裝了一層,如果不喜歡,完成可以自己封裝一個,然后注入:

源碼:

protected <T> T doExecute(URI url, HttpMethod method, RequestCallback requestCallback,
            ResponseExtractor<T> responseExtractor) throws RestClientException {

        Assert.notNull(url, "'url' must not be null");
        Assert.notNull(method, "'method' must not be 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) {
                return responseExtractor.extractData(response);
            }
            else {
                return null;
            }
        }
        catch (IOException ex) {
            throw new ResourceAccessException("I/O error on " + method.name() +
                    " request for \"" + url + "\":" + ex.getMessage(), ex);
        }
        finally {
            if (response != null) {
                response.close();
            }
        }
    }

下面是一個客戶端調用的例子(用的是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 class RestTest {

    @Autowired
    private RestTemplate restTemplate;

    @Value("${rest.service.url}")
    String url;
    @Test
    public void test(){
        //restTemplate=new RestTemplate();
        String str = restTemplate.getForObject(url+"test/list", String.class);
        
    }
}

 

基本上這些就能購我們使用了。

下次有空吧soap方法的也總結一下。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM