一、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);