在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方法的也总结一下。

原文地址:https://www.cnblogs.com/zr520/p/5338945.html