Spring+CXF restful开发WebService

1 篇文章 0 订阅
1 篇文章 0 订阅

一、Apache CXF介绍

Apache CXF官网地址:Apache CXF -- Index

Apache CXF下载地址:Apache CXF -- Download

二、Apache CXF服务器端使用

1、在web.xml中加上cxf的servlet

<!-- cxf servlet start -->
   <servlet>
        <servlet-name>CXFServlet</servlet-name>
        <servlet-class>
            org.apache.cxf.transport.servlet.CXFServlet  
        </servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>CXFServlet</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
 <!-- cxf servlet end -->

2、在spring的applicationContext.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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xmlns:jaxrs="http://cxf.apache.org/jaxrs"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://cxf.apache.org/jaxws
http://cxf.apache.org/schemas/jaxws.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"/>

<bean id="接口实现类名称" class="接口实现类" />
<!-- /demo这里的地址很重要,客户端需要通过这个地址来访问WebService -->
<jaxrs:server id="cxfServiceContainer" address="/demo">
<jaxrs:serviceBeans>
<ref bean="cxfService" />
</jaxrs:serviceBeans>
<jaxrs:extensionMappings>
<entry key="json" value="application/json" />
<entry key="xml" value="application/xml" />
</jaxrs:extensionMappings>
<jaxrs:languageMappings>
<entry key="en" value="en-gb"/>
</jaxrs:languageMappings>
</jaxrs:server>
</beans>

3、写一个接口,客户端需要复制这个接口使用

@Produces({ MediaType.APPLICATION_JSON })
public interface DemoService {
    @POST
    @Path("/test")
    public String test();
}

4、写一个接口实现类

public class CxfServiceImpl implements DemoService {}

三、Apache CXF客户端使用

一、复制 DemoService接口。

二、测试接口

String url = "http://localhost:8080/CXFService/services/demo";
DemoService service1 = JAXRSClientFactory.create(url, DemoService .class);
WebClient.client(service1 ).accept(MediaType.APPLICATION_JSON); //必须写上
System.out.println(service1 .test());//测试

四、注意点

如果在服务器端,实现类里想获取来访客户端的ip可以在实现类里写

@Context
 private MessageContext messgeContext;

再获取ip的方法里写上

HttpServletRequest request = messgeContext.getHttpServletRequest();
String ip = request.getRemoteAddr();
System.out.println("client_ip:"+ip);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值