文档章节

java1234 webservice 第5 课 自定义拦截器

 小南风
发布于 2016/08/02 13:57
字数 1144
阅读 9
收藏 1

1.server端main方法

package com.java1234.webservice.impl;





import javax.xml.ws.Endpoint;

import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.JaxWsServerFactoryBean;

import com.java1234.interceptor.MyInterceptor;
import com.java1234.webservice.HelloWorld;

public class Server {

	public static void main(String[] args) {
		System.out.println("web service start");
		HelloWorld implementor=new HelloWorldImpl();
		String address="http://192.168.244.1/helloWorld";
		// Endpoint.publish(address, implementor); // jdk实现 暴露webservice接口
		
		
		JaxWsServerFactoryBean factoryBean=new JaxWsServerFactoryBean();
		factoryBean.setAddress(address); // 设置暴露地址
		factoryBean.setServiceClass(HelloWorld.class); // 接口类
		factoryBean.setServiceBean(implementor); // 设置实现类
		
		factoryBean.getInInterceptors().add(new LoggingInInterceptor());//添加in拦截器,
		factoryBean.getOutInterceptors().add(new LoggingOutInterceptor());//添加out的拦截器
		/*
		 * 自定义拦截器, 权限认证
		 */
		factoryBean.getInInterceptors().add(new MyInterceptor());
		
		factoryBean.create(); // 创建webservice接口
		
		
		System.out.println("web service started");
	}
}

拦截器的实现

package com.java1234.interceptor;

import java.util.List;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.common.security.UsernameToken;
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;
import org.w3c.dom.NodeList;

public class MyInterceptor extends    AbstractPhaseInterceptor<SoapMessage> {

	public MyInterceptor() {
		super(Phase.PRE_INVOKE);  //在调用方法之前,调用自定义拦截器

	}

	public void handleMessage(SoapMessage message) throws Fault {
		
		List<Header> headers = message.getHeaders();
		if(headers==null && headers.size()==0){
			throw new Fault(new IllegalArgumentException("没有头,抛出异常"));
		}
		Header  firstHeader =  headers.get(0);
		Element ele=(Element ) firstHeader.getObject();
		
		 NodeList uList=  ele.getElementsByTagName("userName");
		NodeList pList= ele.getElementsByTagName("password");
		 if(uList.getLength()!=1){
			throw new Fault(new IllegalArgumentException("用户名格式不对!"));

		 }
		 if(uList.getLength()!=1){
				throw new Fault(new IllegalArgumentException("密码格式不对!"));

		}
		 String username=uList.item(0).getTextContent();
		 String password=pList.item(0).getTextContent();
		
		 if(!username.equals("java1234")  || !password.equals("123456") ){
				throw new Fault(new IllegalArgumentException("用户密码错误!"));
		 }
		
		
	}

}

 

2.客户端 main方法

package com.java1234.webservice;

import java.util.List;

import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;

import com.java1234.interceptor.AddHeaderInterceptor;

public class Client {
	
	 public static void main(String[] args) {
		HelloWorldService service=new HelloWorldService();
		HelloWorld helloWorld=service.getHelloWorldPort();
		
		
		
		org.apache.cxf.endpoint.Client client= ClientProxy.getClient(helloWorld);
		
		
		client.getOutInterceptors().add(new AddHeaderInterceptor("java1234","123456")); // 添加自定义拦截器
		
		client.getInInterceptors().add(new LoggingInInterceptor());//添加
		client.getOutInterceptors().add(new LoggingOutInterceptor());
		
		
		
		/*
		 *数据只能传输List<T>,不能传输map,所以map的key放入T中,便可以轻松传输! 
		 */
		MyRoleArray arry = helloWorld.getRoles();
		 List<MyRole>   roleList= arry.item;
		
		 for(int i=0; i<roleList.size();i++){
			 
			 MyRole my=roleList.get(i);
			 System.out.println(my.key+":");
			 for(Role r:my.value){
				 System.out.println(r.getId()+","+r.getRoleName());
			 }
			 System.out.println("========================");
		 }
		 
		
		
		
	}

}

 

拦截器的实现:

package com.java1234.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 AddHeaderInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

	private String userName;
	private String password;
	
	public AddHeaderInterceptor(String userName,String password) {
		super(Phase.PREPARE_SEND); // 准备发送SOAP消息的时候调用拦截器
		this.userName=userName;
		this.password=password;
	}

	public void handleMessage(SoapMessage message) throws Fault {
		List<Header> headerList=message.getHeaders();
		
		Document doc=DOMUtils.createDocument();
		//创建作者节点
		Element ele=doc.createElement("authHeader");
		
		//创建一个节点
		Element uElement=doc.createElement("userName");
		uElement.setTextContent(userName);  
		
		Element pElement=doc.createElement("password");
		pElement.setTextContent(password);
		
		ele.appendChild(uElement);
		ele.appendChild(pElement);
		
		
		//////////////////   aaa_QName 暂时可以自定义
		headerList.add(new Header(new QName("aaa_QName"),ele));
		
	}
	
	

}

控制台:显示

client
八月 02, 2016 1:52:55 下午 org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean buildServiceFromWSDL
信息: Creating Service {http://webservice.java1234.com/}HelloWorldService from WSDL: http://192.168.244.1/helloWorld?wsdl
八月 02, 2016 1:52:56 下午 org.apache.cxf.services.HelloWorldService.HelloWorldPort.HelloWorld
信息: Outbound Message
---------------------------
ID: 1
Address: http://192.168.244.1/helloWorld
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><authHeader><userName>java1234</userName><password>123456</password></authHeader></soap:Header><soap:Body><ns2:getRoles xmlns:ns2="http://webservice.java1234.com/"/></soap:Body></soap:Envelope>
--------------------------------------
八月 02, 2016 1:52:56 下午 org.apache.cxf.services.HelloWorldService.HelloWorldPort.HelloWorld
信息: 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=[Tue, 02 Aug 2016 05:52:56 GMT], Server=[Jetty(9.2.11.v20150529)], transfer-encoding=[chunked]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:getRolesResponse xmlns:ns2="http://webservice.java1234.com/"><return><item><key>jack</key><value><id>3</id><roleName>程序员</roleName></value></item><item><key>java1234</key><value><id>1</id><roleName>技术总监</roleName></value><value><id>2</id><roleName>架构师</roleName></value></item></return></ns2:getRolesResponse></soap:Body></soap:Envelope>
--------------------------------------
jack:
3,程序员
========================
java1234:
1,技术总监
2,架构师
========================

 

server
八月 02, 2016 2:02:03 下午 org.apache.cxf.services.HelloWorldService.HelloWorldPort.HelloWorld
信息: Inbound Message
----------------------------
ID: 9
Address: http://192.168.244.1/helloWorld?wsdl
Http-Method: GET
Content-Type: text/xml
Headers: {Accept=[*/*], Cache-Control=[no-cache], connection=[keep-alive], content-type=[text/xml], Host=[192.168.244.1], Pragma=[no-cache], User-Agent=[Apache CXF 3.1.5]}
--------------------------------------
八月 02, 2016 2:02:04 下午 org.apache.cxf.services.HelloWorldService.HelloWorldPort.HelloWorld
信息: Inbound Message
----------------------------
ID: 10
Address: http://192.168.244.1/helloWorld
Encoding: UTF-8
Http-Method: POST
Content-Type: text/xml; charset=UTF-8
Headers: {Accept=[*/*], Cache-Control=[no-cache], connection=[keep-alive], Content-Length=[276], content-type=[text/xml; charset=UTF-8], Host=[192.168.244.1], Pragma=[no-cache], SOAPAction=[""], User-Agent=[Apache CXF 3.1.5]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Header><authHeader><userName>java1234</userName><password>123456</password></authHeader></soap:Header><soap:Body><ns2:getRoles xmlns:ns2="http://webservice.java1234.com/"/></soap:Body></soap:Envelope>
--------------------------------------
传入的信息是message:{javax.xml.ws.wsdl.port={http://webservice.java1234.com/}HelloWorldPort, org.apache.cxf.service.model.MessageInfo=[MessageInfo INPUT: {http://webservice.java1234.com/}getRoles], org.apache.cxf.message.Message.PROTOCOL_HEADERS={Accept=[*/*], Cache-Control=[no-cache], connection=[keep-alive], Content-Length=[276], content-type=[text/xml; charset=UTF-8], Host=[192.168.244.1], Pragma=[no-cache], SOAPAction=[""], User-Agent=[Apache CXF 3.1.5]}, org.apache.cxf.interceptor.LoggingMessage.ID=10, HTTP_CONTEXT_MATCH_STRATEGY=stem, http.service.redirection=null, org.apache.cxf.request.url=http://192.168.244.1/helloWorld, javax.xml.ws.wsdl.interface={http://webservice.java1234.com/}HelloWorld, org.apache.cxf.request.uri=/helloWorld, HTTP.REQUEST=(POST /helloWorld)@8729297 org.eclipse.jetty.server.Request@8532d1, org.apache.cxf.transport.https.CertConstraints=null, HTTP.CONFIG=null, Accept=*/*, org.apache.cxf.headers.Header.list=[org.apache.cxf.binding.soap.SoapHeader@cb68d8], org.apache.cxf.message.Message.BASE_PATH=/helloWorld, org.apache.cxf.message.Message.PATH_INFO=/helloWorld, schema-validation-enabled=NONE, org.apache.cxf.continuations.ContinuationProvider=org.apache.cxf.transport.http_jetty.continuations.JettyContinuationProvider@50623e, javax.xml.ws.wsdl.service={http://webservice.java1234.com/}HelloWorldService, org.apache.cxf.message.Message.IN_INTERCEPTORS=[org.apache.cxf.transport.https.CertConstraintsInterceptor@101e5eb], org.apache.cxf.binding.soap.SoapVersion=org.apache.cxf.binding.soap.Soap11@19dc697, org.apache.cxf.message.Message.ENCODING=UTF-8, org.apache.cxf.message.Message.QUERY_STRING=null, HTTP.RESPONSE=HTTP/1.1 200 
Date: Tue, 02 Aug 2016 06:02:04 GMT

, org.apache.cxf.security.SecurityContext=org.apache.cxf.transport.http.AbstractHTTPDestination$2@161e60b, org.apache.cxf.configuration.security.AuthorizationPolicy=null, org.apache.cxf.async.post.response.dispatch=true, org.apache.cxf.request.method=POST, javax.xml.ws.wsdl.operation={http://webservice.java1234.com/}getRoles, org.apache.cxf.transport.Destination=org.apache.cxf.transport.http_jetty.JettyHTTPDestination@2bbfbc, org.apache.cxf.message.MessageFIXED_PARAMETER_ORDER=false, javax.xml.ws.wsdl.description=http://192.168.244.1:80/helloWorld?wsdl, http.base.path=http://192.168.244.1, org.apache.cxf.service.model.BindingMessageInfo=org.apache.cxf.service.model.BindingMessageInfo@38e338, HTTP.CONTEXT=ServletContext@o.e.j.s.h.ContextHandler@1dc0fec{/,null,AVAILABLE}, Content-Type=text/xml; charset=UTF-8}
八月 02, 2016 2:02:04 下午 org.apache.cxf.services.HelloWorldService.HelloWorldPort.HelloWorld
信息: Outbound Message
---------------------------
ID: 10
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:getRolesResponse xmlns:ns2="http://webservice.java1234.com/"><return><item><key>jack</key><value><id>3</id><roleName>程序员</roleName></value></item><item><key>java1234</key><value><id>1</id><roleName>技术总监</roleName></value><value><id>2</id><roleName>架构师</roleName></value></item></return></ns2:getRolesResponse></soap:Body></soap:Envelope>
--------------------------------------

 

 

本文转载自:

粉丝 4
博文 162
码字总数 59007
作品 0
私信 提问
【CXF】- 拦截器 Interceptor

CXF拦截器 拦截动态操作请求和响应数据 拦截器分类 位置:服务器端拦截器,客户端拦截器 消息方向:入拦截器 出拦截器 定义者:系统拦截器 自定义拦截器:LoggingInInteceptor ①:创建webse...

ZeroneLove
03/02
0
0
SpringBoot | 第三十四章:CXF构建WebService服务

前言 上一章节,讲解了如何使用构建服务。其实,创建的方式有很多的,今天来看看如何使用来构建及调用服务。 一点知识 何为Apache-CXF 是一个开源的框架,帮助您利用编程 API 来构建和开发S...

oKong
2018/11/12
0
0
cxf拦截器客户端访问问题

我在项目中使用cxf作为webservice对外使用,为了安全原因我需要在项目中添加用户名密码验证,我的项目是java写的我从网上查了都是自定义拦截器,然后定义用户名密码。我想问的是,如果是其他...

电脑小童
2014/06/17
169
3
CXF和spring编写的WebService

• 为什么设计拦截器? 1. 为了在webservice请求过程中,能动态操作请求和响应数据, CXF设计了拦截器. • 拦截器分类: 2. 按所处的位置分:服务器端拦截器,客户端拦截器 3. 按消息的方向分:...

sxl01890
2016/04/17
54
0
CXF 服务器端怎么将 soap 头信息给客户端?

请教个问题,CXF 服务器端怎么将 soap 头信息给客户端? 我们的项目 用的 cxf webService 跟 android IOS,客户端交互,IOS端要求要返回头信息给他们,来判读数据,之前我用输出拦截器做了,是...

yl1688
2013/08/19
873
1

没有更多内容

加载失败,请刷新页面

加载更多

利用mybatis generator生成实体类、Mapper接口以及对应的XML文件

项目中通常会遇到数据的持久化,如果是采用mybatis的orm,就会涉及到生成xml的问题,刚好mybatis官网提供了这么个插件MyBatis Generator,效果简直是棒呆。 1. 首先需要在build.gradle文件中...

啊哈关关
今天
2
0
SpringSocial相关的知识点

使用SprigSocial开发第三方登录 核心类 ServiceProvider(AbstractOauth2ServiceProvider):主要负责实现server提供商(例如QQ,微信等共有的东西),默认实现类是AbstractOauth2ServiceProvider...

chendom
今天
1
0
Java并发之AQS详解

一、概述   谈到并发,不得不谈ReentrantLock;而谈到ReentrantLock,不得不谈AbstractQueuedSynchronizer(AQS)!   类如其名,抽象的队列式的同步器,AQS定义了一套多线程访问共享资源...

群星纪元
昨天
2
0
Fabric-sdk-java最新教程

Fabric Java SDK是Fabric区块链官方提供的用于Java应用开发的SDK,全称为Fabric-sdk-java,网上可用资料不多,本文列出了精心整理的针对Fabric Java SDK的最新精选教程。 如果希望快速掌握F...

汇智网教程
昨天
2
0
react 子组件监听props 变化

componentWillReceiveProps //已经被废弃 getDerivedStateFromProps// 推荐使用//如果条件不存在必须要返回null static getDerivedStateFromProps(props, current_stat...

一箭落旄头
昨天
3
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部