用CXF编写基于spring的web service 并添加cxf日志拦截器和自定义拦截器

 编码实现
1.Server端
–创建spring的配置文件beans.xml,在其中配置SEI

–在web.xml中,配置上CXF的一些核心组件


新建web项目,cxf 的jar包全部放入lib下

javaBean

package com.me.cxf.Bean;

public class Order {
	private int id;
	private String name;
	private double price;

	
	public Order(int id, String name, double price) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}
	public Order(){
		
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	@Override
	public String toString() {
		return "Order [id=" + id + ", name=" + name + ", price=" + price + "]";
	}

}

SEI接口

package com.me.cxf.ws;

import javax.jws.WebMethod;
import javax.jws.WebService;

import com.me.cxf.Bean.Order;

@WebService
public interface OrderWS {
  @WebMethod
  public Order getOrderById(int id);
}

SEI接口实现

package com.me.cxf.ws;

import javax.jws.WebService;

import com.me.cxf.Bean.Order;

@WebService
public class OrderWSImpl implements OrderWS {
    
	public OrderWSImpl(){
		System.out.println("OrderWSImpl()");
	}
	@Override
	public Order getOrderById(int id) {
	    System.out.println("server getOrderById() "+id);
		return new Order(id, "笔记本", 10);
	}

}

spring配置文件

<?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:jaxws="http://cxf.apache.org/jaxws"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://cxf.apache.org/jaxws http://cxf.apache.org/jaxws">
  
  
  <!-- 引cxf的一些核心配置 -->
   <import resource="classpath:META-INF/cxf/cxf.xml" /> <!-- cxf 3.16只加载cxf.xml就行,旧的版本可能要加载以下两个配置文件 -->
   <!-- <import resource="classpath:META-INF/cxf/cxf-extension-soap.xml" /><!--  -->
   <import resource="classpath:META-INF/cxf/cxf-servlet.xml" /> --> 
   
   <jaxws:endpoint 
     id="orderWS" 
     implementor="com.me.cxf.ws.OrderWSImpl" 
     address="/orderws">
    </jaxws:endpoint>
     
</beans>

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>WS_CXF_spring_server</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
    <!-- 配置beans.xml -->
  <context-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:spring.xml</param-value>
   </context-param>
   
   <!-- 
   		应用启动的一个监听器
    -->
   <listener>
      <listener-class>
         org.springframework.web.context.ContextLoaderListener
      </listener-class>
   </listener>
   
   <!-- 
   		所有请求都会先经过cxf框架
    -->
   <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>/*</url-pattern>
    </servlet-mapping>
</web-app>

浏览器访问

http://localhost:8081/WS_CXF_spring_server/orderws?wsdl



2.Client端
–生成客户端代码
–创建客户端的spring配置文件beans-client.xml,并配置

–编写测试类请求web service


新建web项目

使用cxf工具包生成客户端代码


刷新项目


spring配置文件

<?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:jaxws="http://cxf.apache.org/jaxws"
   xsi:schemaLocation="http://www.springframework.org/schema/beans 
   	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://cxf.apache.org/jaxws http://cxf.apache.org/jaxws">
	
	<jaxws:client id="orderClient" 
		serviceClass= "com.me.cxf.ws.OrderWS" 
		address= "http://localhost:8081/WS_CXF_spring_server/orderws">
	</jaxws:client>
</beans>

测试代码

package com.me.cxf.ws.test;

import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.me.cxf.ws.Order;
import com.me.cxf.ws.OrderWS;

public class Spring_client_ws_Test {
	public static void main(String[] args) {
		ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(new String[]  {"client_spring.xml"});
		OrderWS orderWS = (OrderWS) context.getBean("orderClient");
		Order order = orderWS.getOrderById(24);
		System.out.println(order);
	}
}


1.2) 编码实现拦截器
•使用日志拦截器,实现日志记录
–LoggingInInterceptor
–LoggingOutInterceptor
•使用自定义拦截器,实现用户名与密码的检验
–服务器端的in拦截器
–客户端的out拦截器
–xiaoming/123456


客户端自定义拦截器

package com.me.ws.cxf.Interceptor;

import java.util.List;

import javax.xml.namespace.QName;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.helpers.DOMUtils;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element;

public class AddUserInterceptor extends AbstractPhaseInterceptor<SoapMessage>{

	private String name;
	private String password;
	
	public AddUserInterceptor(String name,String password) {
		super(Phase.PRE_PROTOCOL);//准备协议化时拦截
		// TODO Auto-generated constructor stub
		this.name = name;
		this.password =password;
		System.out.println("AddUserInterceptor ");
	}
	/*
 	<Envelope>
 		<head>
 			<authUser>
 				<name>xiaoming</name>
 				<password>123456</password>
 			</authUser>
 		<head>
 		<Body>
 			<sayHello>
 				<arg0>xiaoming</arg0>
 			<sayHello>
 		</Body>
 	</Envelope>
 */
	@Override
	public void handleMessage(SoapMessage message) throws Fault {
		List<Header> headers = message.getHeaders();
		/*<authUser>
			<name>xiaoming</name>
			<password>123456</password>
		</authUser>	*/	
		
		Document document = DOMUtils.createDocument(); 
		Element rootEle = document.createElement("authUser");
		Element nameEle = document.createElement("name");
		nameEle.setTextContent(name);
		rootEle.appendChild(nameEle);
		Element passwordEle = document.createElement("password");
		passwordEle.setTextContent(password);
		rootEle.appendChild(passwordEle);
		
		headers.add(new Header(new QName("authUser"), rootEle));
		System.out.println("client HandMessage()....");
		
	}

}

客户端spring配置文件修改

<?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:jaxws="http://cxf.apache.org/jaxws"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
   	http://www.springframework.org/schema/beans/spring-beans.xsd
	http://cxf.apache.org/jaxws http://cxf.apache.org/jaxws">



	<jaxws:client id="orderClient" serviceClass="com.me.cxf.ws.OrderWS"
		address="http://localhost:8081/WS_CXF_spring_server/orderws">

		<jaxws:outInterceptors>
		    <!-- 添加cxf日志出拦截器  -->
		    <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
		    <!-- 添加自定义cxf拦截器 -->
			<bean class="com.me.ws.cxf.Interceptor.AddUserInterceptor">
				<constructor-arg index="0" value="xiaoming"></constructor-arg>
				<constructor-arg index="1" value="123456"></constructor-arg>
			</bean>
		</jaxws:outInterceptors>
		
		<jaxws:inInterceptors>
		    <!-- 添加cxf日志入拦截器  -->
		    <bean class="org.apache.cxf.interceptor.LoggingInInterceptor"/> 
		</jaxws:inInterceptors>
	</jaxws:client>


</beans>

服务端

自动义拦截器

package com.me.ws.cxf.interceptor;

import javax.xml.namespace.QName;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.headers.Header;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Element;

/**
 * 检查用户的拦截器
 * @author Administrator
 *
 */
public class CheckUserInterceptor extends AbstractPhaseInterceptor<SoapMessage>{

	public CheckUserInterceptor() {
		super(Phase.PRE_PROTOCOL);
		System.out.println("CheckUserInterceptor() ");
		// TODO Auto-generated constructor stub
	}

	/*
 	<Envelope>
 		<head>
 			<authUser>
 				<name>xiaoming</name>
 				<password>123456</password>
 			</authUser>
 		<head>
 		<Body>
 			<sayHello>
 				<arg0>xiaoming</arg0>
 			<sayHello>
 		</Body>
 	</Envelope>
 */
	@Override
	public void handleMessage(SoapMessage message) throws Fault {
		Header header = message.getHeader(new QName("authUser"));
		if(header!=null){
		 Element authUser =	(Element) header.getObject();
		 String name = authUser.getElementsByTagName("name").item(0).getTextContent();
		 String password = authUser.getElementsByTagName("password").item(0).getTextContent();
		 if("xiaoming".equalsIgnoreCase(name) && "123456".equals(password)){
			 System.out.println("server 通过认证拦截器。。。");
			 return ;
		 }
		}
		//不能通过
		System.out.println("server 没有通过认证拦截器。。。");
		throw new Fault(new RuntimeException("请求输入一个正确的用户名密码"));
		
	}

}

服务端spring配置文件修改

<?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:jaxws="http://cxf.apache.org/jaxws"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
		http://cxf.apache.org/jaxws http://cxf.apache.org/jaxws">
  
  
  <!-- 引cxf的一些核心配置 -->
   <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" /> --> 
   
   <jaxws:endpoint 
     id="orderWS" 
     implementor="com.me.cxf.ws.OrderWSImpl" 
     address="/orderws">
         <!-- 添加入cxf拦截器 -->
     	<jaxws:inInterceptors>
     	    <ref bean="loggingInInterceptor"/>
     		<ref bean="checkUserInterceptor"/>
     	</jaxws:inInterceptors>
     	
     	<!-- 添加出cxf拦截器 -->
     	<jaxws:outInterceptors>
     	   <ref bean="loggingOutInterceptor"/>
     	</jaxws:outInterceptors>
    </jaxws:endpoint>
    <!-- 自定义cxf拦截器 -->
    <bean id="checkUserInterceptor"  class="com.me.ws.cxf.interceptor.CheckUserInterceptor"/>
     <!-- 添加cxf日志入拦截器  -->
	<bean id="loggingInInterceptor"  class="org.apache.cxf.interceptor.LoggingInInterceptor"/> 
	<!-- 添加cxf日志出拦截器  -->
     <bean id="loggingOutInterceptor" class="org.apache.cxf.interceptor.LoggingOutInterceptor"/>
     
</beans>


重新测试

服务端

信息: Inbound Message
----------------------------
ID: 1
Address: http://localhost:8081/WS_CXF_spring_server/orderws
Encoding: UTF-8
Http-Method: POST
Content-Type: text/xml; charset=UTF-8
Headers: {Accept=[*/*], cache-control=[no-cache], connection=[keep-alive], Content-Length=[291], content-type=[text/xml; charset=UTF-8], host=[localhost:8081], pragma=[no-cache], SOAPAction=[""], user-agent=[Apache CXF 3.1.6]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><authUser><name>xiaoming</name><password>123456</password></authUser></soap:Header><soap:Body><ns2:getOrderById xmlns:ns2="http://ws.cxf.me.com/"><arg0>24</arg0></ns2:getOrderById></soap:Body></soap:Envelope>
--------------------------------------
server 通过认证拦截器。。。
server getOrderById() 24
六月 22, 2016 11:53:29 下午 org.apache.cxf.services.OrderWSImplService.OrderWSImplPort.OrderWS
信息: Outbound Message
---------------------------
ID: 1
Response-Code: 200
Encoding: UTF-8
Content-Type: text/xml
Headers: {}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:getOrderByIdResponse xmlns:ns2="http://ws.cxf.me.com/"><return><id>24</id><name>笔记本</name><price>10.0</price></return></ns2:getOrderByIdResponse></soap:Body></soap:Envelope>
--------------------------------------


客户端

信息: Loading XML bean definitions from class path resource [client_spring.xml]
AddUserInterceptor 
六月 22, 2016 11:53:21 下午 org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean buildServiceFromClass
信息: Creating Service {http://ws.cxf.me.com/}OrderWSService from class com.me.cxf.ws.OrderWS
client HandMessage()....
六月 22, 2016 11:53:23 下午 org.apache.cxf.services.OrderWSService.OrderWSPort.OrderWS
信息: Outbound Message
---------------------------
ID: 1
Address: http://localhost:8081/WS_CXF_spring_server/orderws
Encoding: UTF-8
Http-Method: POST
Content-Type: text/xml
Headers: {Accept=[*/*], SOAPAction=[""]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><authUser><name>xiaoming</name><password>123456</password></authUser></soap:Header><soap:Body><ns2:getOrderById xmlns:ns2="http://ws.cxf.me.com/"><arg0>24</arg0></ns2:getOrderById></soap:Body></soap:Envelope>
--------------------------------------
六月 22, 2016 11:53:29 下午 org.apache.cxf.services.OrderWSService.OrderWSPort.OrderWS
信息: Inbound Message
----------------------------
ID: 1
Response-Code: 200
Encoding: UTF-8
Content-Type: text/xml;charset=UTF-8
Headers: {content-type=[text/xml;charset=UTF-8], Date=[Wed, 22 Jun 2016 15:53:29 GMT], Server=[Apache-Coyote/1.1], transfer-encoding=[chunked]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:getOrderByIdResponse xmlns:ns2="http://ws.cxf.me.com/"><return><id>24</id><name>笔记本</name><price>10.0</price></return></ns2:getOrderByIdResponse></soap:Body></soap:Envelope>
--------------------------------------

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值