1、为什么CXF设置拦截器

为了在webservice请求过程中,能动态操作请求和响应数据, CXF设计了拦截器。拦截器分类

1.按所处的位置分:服务器端拦截器,客户端拦截器

2.按消息的方向分:入拦截器,出拦截器

3.按定义者分:系统拦截器,自定义拦截器

系统拦截器:

LoggingInInterceptor(系统日志入拦截器类)

LoggingOutInterceptor(系统日志出拦截器类)

2、系统拦截器

https://www.cnblogs.com/Mrchengs/p/10562458.html依旧是这里的服务端代码进行使用

1、服务端的拦截

在发布的main方法中:

package com.cr.server;

import java.util.List;

import javax.wsdl.Message;
import javax.xml.ws.Endpoint; import org.apache.cxf.interceptor.Interceptor;import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.EndpointImpl; import com.cr.service.impl.HelloServiceImpl; import service1.DateTypeWsImpl; //发布service
public class server {
public static void main(String[] args){ String address = "http://localhost:8081/webserviceserver/helloService";
Endpoint endpoint = Endpoint.publish(address , new HelloServiceImpl()); System.out.println(endpoint);
EndpointImpl e = (EndpointImpl) endpoint;
System.out.println(e);
//服务端的日志入拦截器
List<Interceptor<? extends org.apache.cxf.message.Message>> in = e.getInInterceptors();
in.add(new LoggingInInterceptor()); List<Interceptor<? extends org.apache.cxf.message.Message>> out = e.getOutInterceptors();
out.add(new LoggingOutInterceptor());
System.out.println();
System.out.println("发布成功....");
}
}

测试结果:

----------------------------
ID:
Address: http://localhost:8081/webserviceserver/helloService?wsdl
Http-Method: GET
Content-Type:
Headers: {Accept=[text/html, image/gif, image/jpeg, *; q=., */*; q=.2], connection=[keep-alive], Content-Type=[null], Host=[localhost:8081], User-Agent=[Java/1.8.0_101]}
--------------------------------------
三月 21, 2019 9:33:01 下午 org.apache.cxf.services.HelloServiceImplService.HelloServiceImplPort.HelloService
信息: Inbound Message
----------------------------
ID: 2
Address: http://localhost:8081/webserviceserver/helloService?wsdl
Http-Method: GET
Content-Type:
Headers: {Accept=[text/html, image/gif, image/jpeg, *; q=.2, */*; q=.], connection=[keep-alive], Content-Type=[null], Host=[localhost:], User-Agent=[Java/1.8.0_101]}
--------------------------------------
三月 , :: 下午 org.apache.cxf.services.HelloServiceImplService.HelloServiceImplPort.HelloService
信息: Inbound Message
----------------------------
ID:
Address: http://localhost:8081/webserviceserver/helloService?wsdl=HelloService.wsdl
Http-Method: GET
Content-Type:
Headers: {Accept=[text/html, image/gif, image/jpeg, *; q=., */*; q=.2], connection=[keep-alive], Content-Type=[null], Host=[localhost:8081], User-Agent=[Java/1.8.0_101]}
--------------------------------------
三月 21, 2019 9:33:02 下午 org.apache.cxf.services.HelloServiceImplService.HelloServiceImplPort.HelloService
信息: Inbound Message
----------------------------
ID: 4
Address: http://localhost:8081/webserviceserver/helloService?wsdl=HelloService.wsdl
Http-Method: GET
Content-Type:
Headers: {Accept=[text/html, image/gif, image/jpeg, *; q=.2, */*; q=.], connection=[keep-alive], Content-Type=[null], Host=[localhost:], User-Agent=[Java/1.8.0_101]}
--------------------------------------
三月 , :: 下午 org.apache.cxf.services.HelloServiceImplService.HelloServiceImplPort.HelloService
信息: Inbound Message
----------------------------
ID:
Address: http://localhost:8081/webserviceserver/helloService?wsdl=HelloService.wsdl
Http-Method: GET
Content-Type:
Headers: {Accept=[text/html, image/gif, image/jpeg, *; q=., */*; q=.2], connection=[keep-alive], Content-Type=[null], Host=[localhost:8081], User-Agent=[Java/1.8.0_101]}
--------------------------------------
三月 21, 2019 9:33:11 下午 org.apache.cxf.services.HelloServiceImplService.HelloServiceImplPort.HelloService
信息: Inbound Message
----------------------------
ID: 6
Address: http://localhost:8081/webserviceserver/helloService
Encoding: UTF-8
Http-Method: POST
Content-Type: text/xml; charset=UTF-8
Headers: {Accept=[application/soap+xml, application/dime, multipart/related, text/*], Cache-Control=[no-cache], connection=[close], Content-Length=[330], content-type=[text/xml; charset=UTF-8], Host=[localhost:8081], Pragma=[no-cache], SOAPAction=[""], User-Agent=[IBM Web Services Explorer]}
Payload: <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:q0="http://service.cr.com/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<q0:sayHello>
<arg0>1</arg0>
</q0:sayHello>
</soapenv:Body>
</soapenv:Envelope> --------------------------------------
webservice sercer...
name:1
三月 21, 2019 9:33:11 下午 org.apache.cxf.services.HelloServiceImplService.HelloServiceImplPort.HelloService
信息: Outbound Message
---------------------------
ID: 6
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:sayHelloResponse xmlns:ns2="http://service.cr.com/"><return>hello:1</return></ns2:sayHelloResponse></soap:Body></soap:Envelope>
--------------------------------------

2、客户端的拦截

package cn.com.client;

import java.util.List;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.interceptor.Interceptor;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.message.Message; import com.cr.service.HelloService;
import com.cr.service.impl.HelloServiceImplService; public class client {
public static void main(String[] args){ HelloServiceImplService factory = new HelloServiceImplService();
HelloService hello = factory.getHelloServiceImplPort(); //发送请求的客户端对象
Client client = ClientProxy.getClient(hello);
//添加日志出拦截器的集合
List<Interceptor<? extends Message>> out = client.getOutInterceptors();
out.add(new LoggingOutInterceptor()); //添加日志出拦截器的集合
List<Interceptor<? extends Message>> in = client.getInInterceptors();
in.add(new LoggingInInterceptor()); String res = hello.sayHello("mr");
System.out.println("end:"+res);
} }
---------------------------
ID:
Address: http://localhost:8081/webserviceserver/helloService
Encoding: UTF-
Http-Method: POST
Content-Type: text/xml
Headers: {Accept=[*/*], SOAPAction=[""]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:sayHello xmlns:ns2="http://service.cr.com/"><arg0>mr</arg0></ns2:sayHello></soap:Body></soap:Envelope>
--------------------------------------
三月 21, 2019 9:59:28 下午 org.apache.cxf.services.HelloServiceImplService.HelloServiceImplPort.HelloService
信息: 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=[Thu, 21 Mar 2019 13:59:28 GMT], Server=[Jetty(9.4.14.v20181114)], transfer-encoding=[chunked]}
Payload: <soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><ns2:sayHelloResponse xmlns:ns2="http://service.cr.com/"><return>hello:mr</return></ns2:sayHelloResponse></soap:Body></soap:Envelope>
--------------------------------------
end:hello:mr
首先是从客户端发送请求给服务器,先是发出请求给服务器被拦截(客户端出拦截器),服务器返回响应数据后又被客户端拦截器拦截(客户端入拦截器)
服务器接收到客户端请求后,该请求先是被拦截(服务器入拦截器),接着服务器接收请求并执行后,将数据发回给客户端又被拦截(服务器出拦截器)

3、自定义拦截器

案例:使用自定义拦截器,实现用户名和密码的权限,即访问权限控制!

    需要的拦截器:客户端的出拦截器和服务器的入拦截器

说明:自定义拦截器都从AbstractPhaseIntercepter继承

问题:为什么客户端需要设置拦截器?

因为客户端拦截器能得到客户端的用户名和密码,并且将用户名和密码设置到请求头中

这样服务器接收请求时才能获取到用户名和密码,并且根据得到的用户名和密码来做出验证!

关于客户端的拦截器设置:

新建拦截类:

AddUserInterceptor.java 
package com.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.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.w3c.dom.Document;
import org.w3c.dom.Element; import com.sun.org.apache.xml.internal.utils.DOMHelper;
import com.sun.xml.internal.ws.message.DOMHeader; public class AddUserInterceptor extends AbstractPhaseInterceptor<SoapMessage> { private String name;
private String pwd; //Phase.class可以查看相关的值
public AddUserInterceptor(String name,String pwd) {
super(Phase.PRE_PROTOCOL);//准备初始化拦截
this.name=name;
this.pwd=pwd;
} /*
<Envelope>
<head>
<cr>
<name>name</name>
<pwd>pwd</pwd>
</cr>
</head>

<body>
//...
</body>
</Envelope> */ @Override
public void handleMessage(SoapMessage msg) throws Fault {
List<Header> header = msg.getHeaders(); /*
<head>
<cr>
<name>name</name>
<pwd>pwd</pwd>
</cr>
</hean>
*/
Document document = DOMHelper.createDocument();
Element cr = document.createElement("cr");//创建标签<cr></cr>
Element name = document.createElement("name");//创建标签<name></name>
name.setTextContent(this.name);
cr.appendChild(name);//将name加入到cr标签中 Element pwd = document.createElement("pwd");
pwd.setTextContent(this.pwd);
cr.appendChild(pwd);
     //设置《cr》标签的cr
header.add(new Header(new QName("cr"), cr)); System.out.println("clinet.....");
}
}

在客户端的使用

package cn.com.client;

import java.util.List;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.frontend.ClientProxy;
import org.apache.cxf.interceptor.Interceptor;
import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.message.Message; import com.cr.service.HelloService;
import com.cr.service.impl.HelloServiceImplService;
import com.interceptor.AddUserInterceptor; public class client3 {
public static void main(String[] args){ HelloServiceImplService factory = new HelloServiceImplService();
HelloService hello = factory.getHelloServiceImplPort(); //发送请求的客户端对象
Client client = ClientProxy.getClient(hello);
//添加日志出拦截器的集合
List<Interceptor<? extends Message>> out = client.getOutInterceptors();
out.add(new AddUserInterceptor("cr", "123"
)); String res = hello.sayHello("mr");
System.out.println("end:"+res);
}
}

关于服务器端的拦截类:

package 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; public class CheckUserInterceptor extends AbstractPhaseInterceptor<SoapMessage>{ public CheckUserInterceptor() {
super(Phase.PRE_PROTOCOL);//准备初始化拦截
} @Override
public void handleMessage(SoapMessage msg) throws Fault { Header header = msg.getHeader(new QName("cr"));
if(header!=null){
//取出数据
Element e =(Element) header.getObject();
       //取出name标签的值
String name = e.getElementsByTagName("name").item().getTextContent();
       //取出pwd标签的值
String pwd = e.getElementsByTagName("pwd").item().getTextContent();
if("cr".equals(name) && "".equals(pwd)){
System.out.println("用户密码正确...");
return;
}
//没有通过
System.out.println("不正确...");
throw new Fault(new RuntimeException("请求需要正确的账户...."));
}
}
}

发布类中:

package com.cr.server;

import java.util.List;

import javax.wsdl.Message;
import javax.xml.ws.Endpoint; import org.apache.cxf.interceptor.Interceptor;import org.apache.cxf.interceptor.LoggingInInterceptor;
import org.apache.cxf.interceptor.LoggingOutInterceptor;
import org.apache.cxf.jaxws.EndpointImpl; import com.cr.service.impl.HelloServiceImpl; import interceptor.CheckUserInterceptor;
import service1.DateTypeWsImpl; //发布service
public class server2 {
public static void main(String[] args){ String address = "http://localhost:8081/webserviceserver/helloService";
Endpoint endpoint = Endpoint.publish(address , new HelloServiceImpl()); System.out.println(endpoint);
EndpointImpl e = (EndpointImpl) endpoint;
System.out.println(e);
//服务端的日志入拦截器
List<Interceptor<? extends org.apache.cxf.message.Message>> in = e.getInInterceptors();
in.add(new CheckUserInterceptor());

System.out.println("发布成功....");
}
}

测试:正确的情况下:

客户端的打印:

三月 ,  :: 下午 org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean buildServiceFromWSDL
信息: Creating Service {http://impl.service.cr.com/}HelloServiceImplService from WSDL: file:/D:/myeclipse/MyEclipseProject/webservices_cxf_client/client.wsdl
clinet.....
end:hello:mr

服务端的打印;

用户密码正确...
webservice sercer...
name:mr

测试:错误的i情况下:

客户端的打印:

三月 ,  :: 下午 org.apache.cxf.wsdl.service.factory.ReflectionServiceFactoryBean buildServiceFromWSDL
信息: Creating Service {http://impl.service.cr.com/}HelloServiceImplService from WSDL: file:/D:/myeclipse/MyEclipseProject/webservices_cxf_client/client.wsdl
clinet.....
Exception in thread "main" javax.xml.ws.soap.SOAPFaultException: 请求需要正确的账户....
at org.apache.cxf.jaxws.JaxWsClientProxy.mapException(JaxWsClientProxy.java:)
at org.apache.cxf.jaxws.JaxWsClientProxy.invoke(JaxWsClientProxy.java:)
at com.sun.proxy.$Proxy35.sayHello(Unknown Source)
at cn.com.client.client3.main(client3.java:)
Caused by: org.apache.cxf.binding.soap.SoapFault: 请求需要正确的账户....

服务端的打印:

不正确...
三月 , :: 下午 org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging
警告: Interceptor for {http://impl.service.cr.com/}HelloServiceImplService has thrown exception, unwinding now
org.apache.cxf.interceptor.Fault: 请求需要正确的账户....
at interceptor.CheckUserInterceptor.handleMessage(CheckUserInterceptor.java:)
at interceptor.CheckUserInterceptor.handleMessage(CheckUserInterceptor.java:)
at org.apache.cxf.phase.PhaseInterceptorChain.doIntercept(PhaseInterceptorChain.java:)
at org.apache.cxf.transport.ChainInitiationObserver.onMessage(ChainInitiationObserver.java:)
at org.apache.cxf.transport.http.AbstractHTTPDestination.invoke(AbstractHTTPDestination.java:)
at org.apache.cxf.transport.http_jetty.JettyHTTPDestination.doService(JettyHTTPDestination.java:)
at org.apache.cxf.transport.http_jetty.JettyHTTPHandler.handle(JettyHTTPHandler.java:)
.....

6、Web Service-拦截器的更多相关文章

  1. SpringBoot 03: 常用web组件 - - - 拦截器 + Servlet + 过滤器

    常用web组件 拦截器 Servlet 过滤器 使用思想 创建自定义类 实现或者继承框架里的接口或类 将自定义类注册到框架中 使用自定义类 拦截器 说明 拦截器是SpringMVC中的一种对象,能拦截 ...

  2. dubbo白名单通过filter,spring web通过拦截器或者filter即可

    在开发中,有时候需要限制访问的权限,白名单就是一种方法.对于Java Web应用,Spring的拦截器可以拦截Web接口的调用:而对于dubbo接口,Spring的拦截器就不管用了. dubbo提供了 ...

  3. 【java web】拦截器inteceptor

    一.简介 java里的拦截器提供的是非系统级别的拦截,也就是说,就覆盖面来说,拦截器不如过滤器强大,但是更有针对性. Java中的拦截器是基于Java反射机制实现的,更准确的划分,应该是基于JDK实现 ...

  4. Java web servlet 拦截器 以登陆为例子

    以登陆为例子............... public class LoginFilter implements Filter { @Override public void destroy() { ...

  5. java 过滤器(Filter)与springMVC 拦截器(interceptor)的实现案例

    java 过滤器Filter: package com.sun.test.aircraft.filter;import javax.servlet.*;import java.io.IOExcepti ...

  6. SpringMVC拦截器-路径语法-略坑

    项目中遇到一种场景,登录拦截器需要拦截.html后缀等动态请求,但是发现语法不对头.    <mvc:interceptors>      <mvc:interceptor> ...

  7. Web Service学习之七:CXF拦截器

    一.用途 CXF拦截器类似Struts2的拦截器,后者是拦截和处理请求,前者是对发送和接收的sope消息进行处理,一般用于WS请求响应中的权限验证.日志记录,Soap消息处理,消息的压缩处理等: 这个 ...

  8. Java Web 中 过滤器与拦截器的区别

    过滤器,是在java web中,你传入的request,response提前过滤掉一些信息,或者提前设置一些参数,然后再传入servlet或者struts的 action进行业务逻辑,比如过滤掉非法u ...

  9. 解决Spring Boot 拦截器注入service为空的问题

    问题:在自定义拦截器中,使用了@Autowaire注解注入了封装JPA方法的Service,结果发现无法注入,注入的service为空 0.原因分析 拦截器加载的时间点在springcontext之前 ...

  10. web 过滤器 Filter、 Spring 拦截器 interceptor

    1.过滤器(Filter)(在web.xml中注册过滤器) 首先说一下Filter的使用地方,我们在配置web.xml时,总会配置下面一段设置字符编码,不然会导致乱码问题: <filter> ...

随机推荐

  1. 最新sublime Text3 注册激活码

    sublime build 3103注册码 Enter License -- BEGIN LICENSE --Ryan ClarkSingle User LicenseEA7E-8124792158A ...

  2. Golang把所有包括底层类库,输出到stderr的内容, 重新定向到一个日志文件里面?

    不论应用是如何部署的,我们都期望能扑捉到应用的错误日志, 解决思路: 自己写代码处理异常拦截,甚至直接在main函数中写异常拦截. stderr重定向到某个文件里 使用 syscall.Dup2 第一 ...

  3. poj 2796 Feel Good 单调队列

    Feel Good Time Limit: 3000MS   Memory Limit: 65536K Total Submissions: 8753   Accepted: 2367 Case Ti ...

  4. HDU 2639(01背包第K大)

    http://acm.hdu.edu.cn/showproblem.php?pid=2639 http://blog.csdn.net/lulipeng_cpp/article/details/758 ...

  5. Web安全相关(四):过多发布(Over Posting)

    简介 过多发布的内容相对比较简单,因此,我只打算把原文中的一些关键信息翻译一下.原文链接如下: http://www.asp.net/mvc/overview/getting-started/gett ...

  6. IAAS,SAAS,PAAS, CaaS的区别

    来源:云计算头条微信公众号  作者:   你一定听说过云计算中的三个“高大上”的你一定听说过云计算中的三个“高大上”的概念:IaaS.PaaS和SaaS,这几个术语并不好理解.不过,如果你是个吃货,还 ...

  7. High Performance MySQL笔记:count

    在SQL中使用count()好像是非常自然的事情: SELECT COUNT(*) FROM TABLE_NAME; 有时候确实会想过,count(*)和单独的count(column_name)有什 ...

  8. 用css动画写一个下红包雨的效果

    红包雨的功能相信大家都做过,不过一般都是用js计算的,闲着无聊用css的样式写了类似的,主要用的是css的transform和animation结合.大概代码逻辑: @keyframes startH ...

  9. Excel Metadata

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  10. android资源的诡异问题

    最近,新开发版本,正在处于扫BUG的阶段. 发现一个比较诡异的问题,一个控件的颜色,背景色与预先设定的值,发生不一致.其他的类型的控件有同样的设置,但是现实结果正常. 今天,专门解决这个问题. 经过各 ...