WebService 是一个应用程序向外界暴露出一个能通过Web进行调用的API,也就是说能用编程的方法通过 Web来调用这个应用程序。
当然就应该通过认证才能够进行访问。
下面自定义账户的拦截器
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.apache.log4j.Logger; import org.w3c.dom.Element; public class AccountInterceptor extends AbstractPhaseInterceptor<SoapMessage> { private static Logger logger = Logger.getLogger(AccountInterceptor.class); public AccountInterceptor() { super(Phase.PRE_PROTOCOL); } /*
Head格式
<Envelope> <head> <geek> <username>xfzhang</username> <password>123456</password> </geek> <head> <Body> <sayHello> <arg0>BOB</arg0> <sayHello> </Body> </Envelope> */ @Override public void handleMessage(SoapMessage message) { Header header = message.getHeader(new QName("geek")); System.out.println("通过"); if (header != null) { Element atguiguEle = (Element) header.getObject(); System.out.println(atguiguEle); String name = atguiguEle.getElementsByTagName("username").item(0).getTextContent();//获取name String password = atguiguEle.getElementsByTagName("password").item(0).getTextContent();//获取密码 if ("admin".equals(name) && "admin".equals(password)) { logger.info("name:"+name+"\t"+"password"+password+" 通过拦截器"); System.out.println("Server 通过拦截器...."); return; } logger.error("name:"+name+"\t"+"password"+password+" 没有通过拦截器"); } // 不能通过 logger.error("没有通过拦截器"); System.out.println("Server 没有通过拦截器...."); throw new Fault(new RuntimeException("请求需要一个正确的用户名和密码!")); } }
Out日志拦截器
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.apache.log4j.Logger; import org.w3c.dom.Element; public class LogInterceptor extends AbstractPhaseInterceptor<SoapMessage> { private static Logger logger = Logger.getLogger(LogInterceptor.class); public LogInterceptor() { super(Phase.PRE_PROTOCOL); } @Override public void handleMessage(SoapMessage message) { logger.info("Out拦截器"); } }
发布
import javax.xml.ws.Endpoint; import org.apache.cxf.jaxws.EndpointImpl; public class TestWebService { public static void main(String[] args) { EndpointImpl endpoint = (EndpointImpl) Endpoint.publish("http://localhost:11111/Service/HelloWorld", new HelloWordImpl()); // 添加账户控制拦截器 endpoint.getInInterceptors().add(new LogInterceptor()); // 添加日志拦截器 endpoint.getOutInterceptors().add(new LogInterceptor()); System.out.println("成功"); } }