java WebService CXF Spring 自定义拦截器 附实例源码

517 阅读3分钟

java WebService CXF Spring 自定义拦截器 附实例源码

1、Web service 是什么?1. 基于 Web 的服务:服务器端整出一些资源让客户端应用访问(获取数据)2. 一个跨语言、跨平台的规范(抽象)3. 多个跨平台、跨语言的应用间通信整合的方案(实际)2、......

1、Webservice 是什么?

\1. 基于 Web 的服务:服务器端整出一些资源让客户端应用访问(获取数据)

\2. 一个跨语言、跨平台的规范(抽象)

\3. 多个跨平台、跨语言的应用间通信整合的方案(实际)

2、WebService 中的几个重要术语

WSDL:web service definition language

直译 : WebService 定义语言

\1. 对应一种类型的文件**.wsdl**

\2. 定义了 web service 的服务器端与客户端应用交互传递请求和响应数据的格式和方式

\3. 一个 web service 对应一个 唯一的 wsdl 文档

SOAP:simpleobject access protocal

直译: 简单对象访问协议

\1. 是一种简单的、基于 HTTP 和 XML 的协议, 用于在 WEB 上交换结构化的数据

\2. soap 消息:请求消息和响应消息

3 http+xml 片段

SEI:WebServiceEndPoint Interface(终端)

直译: web service 的终端接口,

\1. 就是 WebService 服务器端用来处理请求的接口

CXF:Celtix +XFire

一个 apache 的用于开发 webservice 服务器端和客户端的框架

3、WebService 的两个重要组成部分

http 协议

1. 请求的组成: 请求行 (请求方式 path http1.1)

请求头

请求体: 只有 post 请求有

2. 响应的组成 响应状态行:

响应头

响应体: 浏览器解析显示的数据

3. 请求的过程

img

** **

**Schema 约束

**

1.namespace

相当于 schema 文件的 id

2.targetNamespace 属性

用来指定 schema 文件的 namespace 的值

3.xmlns 属性

引入一个约束, 它的值是一个 schema 文件的 namespace 值

4.schemaLocation 属性

用来指定引入的 schema 文件的位置

目录结构

img

新建一个接口类

</pre><pre name="code" class="java">package com.iflyee.cxf;

import javax.jws.WebService;

public boolean vo(String username,int count);

public int getvousernameCount();
import java.util.ArrayList;

import javax.jws.WebService;

import org.dom4j.Document;

import org.dom4j.DocumentHelper;

import org.dom4j.Element;

public class Vo implements Ivo {

public int getvocount() {

public int getvousernameCount() {

public boolean vo(String username, int count) {

        Document document = DocumentHelper.createDocument();

            Element rootElement = document.addElement("modules");

            rootElement.setText("这个是module标签的文本信息");

            Element element = rootElement.addElement("module");

for (int i = 0; i < 5; i++) {

            	  Element nameElement = element.addElement("name");

                  Element valueElement = element.addElement("value");

                  Element descriptionElement = element.addElement("description");

                  nameElement.setText("名称"+i);

                  nameElement.addAttribute("language", "java"+i);

                  valueElement.setText("值"+i);

                  valueElement.addAttribute("language", "c#"+i);

                  descriptionElement.setText("描述"+i);

                  descriptionElement.addAttribute("language", "sql server"+i);

            System.out.println(document.asXML()); 

		StringBuffer str = new StringBuffer();

		APIUtils ap = new APIUtils();

		java.util.List<Object> list = new ArrayList<Object>();

for (int i = 0; i < 3; i++) {

			str.append(ap.getXMLModel(user,list));
public void setId(int id) {

public String getUserName() {

public void setUserName(String userName) {

this.userName = userName;

public String getPassword() {

public void setPassword(String password) {

this.password = password;
package com.lzw.springcxf.auth;

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;  

import org.w3c.dom.NodeList;  

public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage>{

public AuthInterceptor() {  

        System.out.println("11111111111111111111111111111111111");

public void handleMessage(SoapMessage msg) throws Fault {  

        System.out.println("==============================");

        System.out.println("=====自定义拦截器=======");  

        List<Header> headers = msg.getHeaders();  

if(headers == null || headers.size() < 1) {  

throw new Fault(new IllegalArgumentException("没有Header,拦截器实施拦截"));  

        Header firstHeader = headers.get(0);  

        Element ele = (Element) firstHeader.getObject();  

        NodeList userIdEle = ele.getElementsByTagName("userId");  

        NodeList userPassEle = ele.getElementsByTagName("userPass");  

if (userIdEle.getLength() != 1) {  

throw new Fault(new IllegalArgumentException("用户Id格式不对"));  

if (userPassEle.getLength() != 1) {  

throw new Fault(new IllegalArgumentException("用户密码格式不对"));  

        String userId = userIdEle.item(0).getTextContent();  

        String userPass = userPassEle.item(0).getTextContent();  

if (!userId.equals("lyy") || !userPass.equals("123456")) {  

throw new Fault(new IllegalArgumentException("用户和密码不正确"));  
</pre><pre code_snippet_id="1652672" snippet_file_name="blog_20160419_7_751113" name="code" class="java">package jp.co.service;

public interface TestService {

<span style="white-space:pre">			</span>public String SayHello();
</pre><pre code_snippet_id="1652672" snippet_file_name="blog_20160419_9_4894787" name="code" class="java">package jp.co.service.impl;

import jp.co.service.TestService;

public class TestServiceImpl implements TestService {

<span style="white-space:pre">	</span>@Override

<span style="white-space:pre">	</span>public String SayHello() {

<span style="white-space:pre">		</span>System.out.println("功能方法被调用!");

<span style="white-space:pre">		</span>return "Hello 这是一个简单的WebService实例";

<span style="white-space:pre">	</span>}

调用方法

import org.apache.cxf.frontend.ClientProxyFactoryBean;

import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;

import jp.co.service.TestService;

public class TestClient {

public static void main(String[] args) {

			ClientProxyFactoryBean clientProxy = new ClientProxyFactoryBean() ;

			clientProxy.setServiceClass(TestService.class);

			clientProxy.setAddress("http://localhost:8080/WcxF/services/test");

			TestService pic = (TestService)clientProxy.create();

			System.out.println(pic.SayHello());

img

bean.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: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/schemas/jaxws.xsd">

		<!-- 引入CXF的支持的文件,来源CXF的jar文件 -->

		<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="vo" implementor="com.iflyee.cxf.Vo" address="/vo">

            <bean class="org.apache.cxf.interceptor.LoggingInInterceptor"></bean>  

            <bean class="com.lzw.springcxf.auth.AuthInterceptor"></bean>  

            <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor"></bean>  

cxf-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"

	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

	xmlns:simple="http://cxf.apache.org/simple"

	xmlns:soap="http://cxf.apache.org/bindings/soap"

	xsi:schemaLocation="http://www.springframework.org/schema/beans 

									http://www.springframework.org/schema/beans/spring-beans-2.0.xsd

									http://cxf.apache.org/bindings/soap

									http://cxf.apache.org/schemas/configuration/soap.xsd

									http://cxf.apache.org/simple

									http://cxf.apache.org/schemas/simple.xsd">

	<simple:server id="testservice"

					serviceClass="jp.co.service.TestService" address="/test">

			<bean class="jp.co.service.impl.TestServiceImpl"></bean>

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">

		<param-name>contextConfigLocation</param-name>  		

		<param-value>WEB-INF/bean.xml</param-value>

  		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

		<servlet-name>cxf</servlet-name>	

		<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>

  		<load-on-startup>1</load-on-startup>

  	<servlet-name>cxf</servlet-name>

  	<url-pattern>/services/*</url-pattern>

  <display-name>WcxF</display-name>

    <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>

源码一:CXF+Spring + 自定义拦截器 WebService 实例源码下载:download.csdn.net/detail/qq_1…

源码二:根据实体类装换 xml 源码下载 : download.csdn.net/detail/qq_1…

全文完

本文由 简悦 SimpRead 优化,用以提升阅读体验

使用了 全新的简悦词法分析引擎 beta,点击查看详细说明

WSDL:web service definition languageSEI:WebServiceEndPoint Interface(终端)