springboot整合cxf发布webservice以及调用的方法

webservice性能不高,但是现在好多公司还是在用,恰好今天在开发的时候对接项目组需要使用到webservice下面来说下简单的案例应用

首先老规矩:引入jar包

<dependency>
 <groupId>org.apache.cxf</groupId>
 <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
 <version>3.1.11</version>
</dependency>

新增一个公共的返回实体类

public class BaseResult {
 private String isSuccess;
 private String errCode;
 private String message;

 public String getIsSuccess() {
 return isSuccess;
 }

 public void setIsSuccess(String isSuccess) {
 this.isSuccess = isSuccess;
 }

 public String getErrCode() {
 return errCode;
 }

 public void setErrCode(String errCode) {
 this.errCode = errCode;
 }

 public String getMessage() {
 return message;
 }

 public void setMessage(String message) {
 this.message = message;
 }

}

其他类继承即可

@XmlRootElement(name = "testResult")
public class TestResult extends BaseResult implements Serializable {

 private static final long serialVersionUID = -7128575337024823798L;

 private List<User> data;

 public List<User> getData() {
 return data;
 }

 public void setData(List<User> data) {
 this.data = data;
 }
}

新增user类

public class User {
 private String name;
 private int age;

 public User(String name, int age) {
 super();
 this.name = name;
 this.age = age;
 }
 public User() {
 super();
 }
 public String getName() {
 return name;
 }
 public void setName(String name) {
 this.name = name;
 }
 public int getAge() {
 return age;
 }
 public void setAge(int age) {
 this.age = age;
 }
}

接下来新增服务接口

@WebService
public interface TestWService{
 @WebMethod
 @WebResult
 TestResult list3();
}

实现服务接口

@Service
@WebService(targetNamespace = "http://ws.**.com/",//命名空间,一般是接口的包名倒序)
endpointInterface = "com.**.ws.TestWSservice")//接口全路径
//**自己改自己的包路径
public class TestWSservice Impl implements TestWSservice {

 @Override
 public TestResult list3() {
 List<User> list = new ArrayList<User>();
 list.add(new User("张三",23));
 list.add(new User("李四",24));
 TestResult testResult = new TestResult();
 testResult.setIsSuccess("Y");
 testResult.setData(list);
 testResult.setMessage("操作成功");
 return testResult;
 }

}

新增配置类,发布服务

import javax.xml.ws.Endpoint;

import org.apache.cxf.Bus;
import org.apache.cxf.bus.spring.SpringBus;
import org.apache.cxf.jaxws.EndpointImpl;
import org.apache.cxf.transport.servlet.CXFServlet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import com.hikvision.hikserviceassign.ws.MonitorSurveyWS;
import com.hikvision.hikserviceassign.ws.SmartLockServiceOrderWS;
/**
 * webservice 发布服务类
 * @author Xupx
 * @Date 2018年8月14日 下午4:25:25
 *
 */
@Configuration
public class CxfConfig {
 @Autowired
 private TestWService testWService;
 @SuppressWarnings("all")
 @Bean
 public ServletRegistrationBean wsServlet() {
  ServletRegistrationBean bean = new ServletRegistrationBean(new CXFServlet(), "/soap/*"); 

  return bean;
 }

 @Bean(name = Bus.DEFAULT_BUS_ID)
 public SpringBus springBus() {
  return new SpringBus();
 }
 @Bean
 public Endpoint testWService() {
  //会找到O2oWebService的实现类,所以实现类只能有一个
  EndpointImpl endpoint = new EndpointImpl(springBus(), testWService);

  endpoint.publish("/testWService");

  return endpoint;
 }
}

启动项目,然后打开路径:localhost:8080/soap 可以查看多个自己发布的服务,如果要发布多个服务,使用多个Bean即可

测试调用1:

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringBootCxfApplicationTests {

 @Test
 public void contextLoads() throws Exception {
 JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
 Client client = dcf.createClient("http://127.0.0.1:8080/soap/testWservice?wsdl");
 Object[] objects = client.invoke("list3",param1,param2);//list3方法名 后面是可变参数
 //输出调用结果
 System.out.println(objects[0].getClass());
 System.out.println(objects[0].toString());
 }
}

客户端调用,用soapUI生成客户端(具体方法自己百度下,不介绍了)

TestWSImplService implService = new TestWSImplService ();
 TestServiceWS ws = implService.getTestServiceWSImplPort();
 TestResult result = ws.list3();
 System.err.println(result);

增加密码校验,以下基础内容引用https://www.jb51.net/article/145707.htm,我补充下包依赖

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 LoginInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
 private String username="root";
 private String password="admin";
 public LoginInterceptor(String username, String password) {
  //设置在发送请求前阶段进行拦截
  super(Phase.PREPARE_SEND);
  this.username=username;
  this.password=password;
 }

 @Override
 public void handleMessage(SoapMessage soapMessage) throws Fault {
  List<Header> headers = soapMessage.getHeaders();
  Document doc = DOMUtils.createDocument();
  Element auth = doc.createElementNS("http://cxf.wolfcode.cn/","SecurityHeader");
  Element UserName = doc.createElement("username");
  Element UserPass = doc.createElement("password");

  UserName.setTextContent(username);
  UserPass.setTextContent(password);

  auth.appendChild(UserName);
  auth.appendChild(UserPass);

  headers.add(0, new Header(new QName("SecurityHeader"),auth));
 }
}
import java.util.List;
import javax.xml.soap.SOAPException;
import org.apache.commons.lang3.StringUtils;
import org.apache.cxf.binding.soap.SoapHeader;
import org.apache.cxf.binding.soap.SoapMessage;
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;

import org.apache.cxf.headers.Header;

public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
 private static final String USERNAME="root";
 private static final String PASSWORD="admin";

 public AuthInterceptor() {
  //定义在哪个阶段进行拦截
  super(Phase.PRE_PROTOCOL);
 }

 @Override
 public void handleMessage(SoapMessage soapMessage) throws Fault {
  List<Header> headers = null;
  String username=null;
  String password=null;
  try {
   headers = soapMessage.getHeaders();
  } catch (Exception e) {
   e.printStackTrace();
  }

  if (headers == null) {
   throw new Fault(new IllegalArgumentException("找不到Header,无法验证用户信息"));
  }
  //获取用户名,密码
  for (Header header : headers) {
   SoapHeader soapHeader = (SoapHeader) header;
   Element e = (Element) soapHeader.getObject();
   NodeList usernameNode = e.getElementsByTagName("username");
   NodeList pwdNode = e.getElementsByTagName("password");
    username=usernameNode.item(0).getTextContent();
    password=pwdNode.item(0).getTextContent();
   if( StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
    throw new Fault(new IllegalArgumentException("用户信息为空"));
   }
  }
  //校验用户名密码
  if(!(username.equals(USERNAME) && password.equals(PASSWORD))){
   SOAPException soapExc = new SOAPException("认证失败");
   throw new Fault(soapExc);
  }
 }
}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持我们。

(0)

相关推荐

  • 详解springboot-修改内置tomcat版本

    详解springboot-修改内置tomcat版本 1.解析Spring Boot父级依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.6.RELEASE</version> </parent> 这块配置就是Spring

  • SpringBoot 注解事务声明式事务的方式

    springboot 对新人来说可能上手比springmvc要快,但是对于各位从springmvc转战到springboot的话,有些地方还需要适应下,尤其是xml配置.我个人是比较喜欢注解➕xml是因为看着方便,查找方便,清晰明了.但是xml完全可以使用注解代替,今天就扒一扒springboot中事务使用注解的玩法. springboot的事务也主要分为两大类,一是xml声明式事务,二是注解事务,注解事务也可以实现类似声明式事务的方法,关于注解声明式事务,目前网上搜索不到合适的资料,所以在这里

  • SpringBoot2.0 整合 Dubbo框架实现RPC服务远程调用方法

    一.Dubbo框架简介 1.框架依赖 图例说明: 1)图中小方块 Protocol, Cluster, Proxy, Service, Container, Registry, Monitor 代表层或模块,蓝色的表示与业务有交互,绿色的表示只对 Dubbo 内部交互. 2)图中背景方块 Consumer, Provider, Registry, Monitor 代表部署逻辑拓扑节点. 3)图中蓝色虚线为初始化时调用,红色虚线为运行时异步调用,红色实线为运行时同步调用. 4)图中只包含 RPC

  • SpringBoot内部调用事务不起作用问题的解决方案

    在做业务开发时,遇到了一个事务不起作用的问题.大概流程是这样的,方法内部的定时任务调用了一个带事务的方法,失败后事务没有回滚.查阅资料后,问题得到解决,记录下来分享给大家. 场景 我在这里模拟一个场景,大概的调用方式就如下面的代码这样. @Override @Transactional(rollbackFor = RuntimeException.class) public void insertUser(User user) { userMapper.insertUser(user); thr

  • 详解SpringBoot中异步请求和异步调用(看完这一篇就够了)

    一.SpringBoot中异步请求的使用 1.异步请求与同步请求 特点: 可以先释放容器分配给请求的线程与相关资源,减轻系统负担,释放了容器所分配线程的请求,其响应将被延后,可以在耗时处理完成(例如长时间的运算)时再对客户端进行响应.一句话:增加了服务器对客户端请求的吞吐量(实际生产上我们用的比较少,如果并发请求量很大的情况下,我们会通过nginx把请求负载到集群服务的各个节点上来分摊请求压力,当然还可以通过消息队列来做请求的缓冲). 2.异步请求的实现 方式一:Servlet方式实现异步请求

  • SpringBoot获取yml和properties配置文件的内容

    (一)yml配置文件: pom.xml加入依赖: <!-- 支持 @ConfigurationProperties 注解 --> <!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-configuration-processor --> <dependency> <groupId>org.springframework.boot</groupId>

  • 详解SpringBoot的事务管理

    Springboot内部提供的事务管理器是根据autoconfigure来进行决定的. 比如当使用jpa的时候,也就是pom中加入了spring-boot-starter-data-jpa这个starter之后. Springboot会构造一个JpaTransactionManager这个事务管理器. 而当我们使用spring-boot-starter-jdbc的时候,构造的事务管理器则是DataSourceTransactionManager. 这2个事务管理器都实现了spring中提供的Pl

  • springboot配置内存数据库H2教程详解

    业务背景:因soa系统要供外网访问,处于安全考虑用springboot做了个前置模块,用来转发外网调用的请求和soa返回的应答.其中外网的请求接口地址在DB2数据库中对应专门的一张表来维护,要是springboot直接访问数据库,还要专门申请权限等,比较麻烦,而一张表用内置的H2数据库维护也比较简单,就可以作为替代的办法. 环境:springboot+maven3.3+jdk1.7 1.springboot的Maven工程结构 说明一下,resource下的templates文件夹没啥用.我忘记

  • springboot整合cxf发布webservice以及调用的方法

    webservice性能不高,但是现在好多公司还是在用,恰好今天在开发的时候对接项目组需要使用到webservice下面来说下简单的案例应用 首先老规矩:引入jar包 <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-spring-boot-starter-jaxws</artifactId> <version>3.1.11</version> &

  • SpringBoot使用CXF集成WebService的方法

    1.写在前面 WebService 对我来说既熟悉又陌生,已经将近六七年没有看到过他了, 具体的介绍我就不多少了, 想了解的百度百科下说的很详细. 之所以突然研究WebService是接到一个需求要去给 XX 项目做一个适配层,他们原有系统是使用webservice做的,所以-- 那我们就来看看,这一个古老的技术如何和如今最流行的框架SpringBoot进行结合. 2.SpringBoot 集成WebService 2.1 导入依赖 compile('org.springframework.bo

  • 解决springboot整合cxf启动报错,原因是版本问题

    springboot整合cxf启动报错 错误信息如下 [DEBUG] 2021-01-26 11:28:47,848 [main] org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter - Application failed to start due to an exception org.springframework.beans.factory.NoSuchBeanDefinitionException: N

  • springboot整合ehcache 实现支付超时限制的方法

    下面给大家介绍springboot整合ehcache 实现支付超时限制的方法,具体内容如下所示: <dependency> <groupId>net.sf.ehcache</groupId> <artifactId>ehcache-core</artifactId> <version>2.6.11</version> </dependency> pom文件中引入ehcache依赖 在类路径下存放ehcache.

  • springboot整合阿里云oss上传的方法示例

    OSS申请和配置 1. 注册登录 输入网址:https://www.aliyun.com/product/oss 如果没有账号点击免费注册,然后登录. 2.开通以及配置 点击立即开通 进入管理控制台 第一次使用会出现引导,按引导点击"我知道了",然后点击创建Bucket. 如果没有存储包或流量包点击购买. 点击确定,返回主页面,出现该页面,点击我知道了 将EndPoint记录下来,方便后期添加到我们项目的配置文件中 创建 AccessKeyID 和 AccessKeySecret 点击

  • SpringBoot整合MinIO实现文件上传的方法详解

    目录 前言 1. MinIO 简介 2. MinIO 安装 3. 整合 Spring Boot 4. 配置nginx 5. 小结 前言 现在 OSS 服务算是一个基础服务了,很多云服务厂商都有提供这样的服务,价格也不贵,松哥自己的网站用的就是类似的服务. 不过对于中小公司来说,除了购买 OSS 服务之外,也可以自己搭建专业的文件服务器,自己搭建专门的文件服务器的话,曾经比较专业的做法是 FastDFS,松哥之前也专门为之录过视频发在 B 站上,感兴趣的小伙伴可以自行查看.不过 FastDFS 搭

  • springboot整合使用云服务器上的Redis方法

    目录 一.前提条件 二.整合步骤 三.可能遇到的坑 一.前提条件 修改redis.conf配置文件 1.protected-mode yes(默认的) 修改成 protected-mode no,解除保护模式 2.注释掉绑定ip ,绑定ip的话,使得除了本机(服务器)以外的主机无法访问redis数据库 3.将守护进程模式关闭 daemonize yes 改成 daemonize no 4.最后,一定记住要redis-server redis.conf重启redis的配置文件,否则修改不生效!!!

  • springBoot整合CXF并实现用户名密码校验的方法

    准备工作: 创建springBoot项目webservice_server 创建springBoot项目webservice_client 分别添加CXF的依赖: <!-- CXF webservice --> <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-spring-boot-starter-jaxws</artifactId> <version

  • SpringBoot整合flyway实现自动创建表的方法

    spring boot - v: 2.1.3.RELEASE MySQL - v:5.7 JDK -v : 11 项目结构: pom.xml <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instan

  • 在webservice里调用耗时方法出错的解决方案

    webservice调用耗时方法出错 在webservice里调用多个耗时的方法时,如果按顺序执行,下面的方法要等上面的方法执行完毕才能执行,如果这些方法比较耗时,并且包括回调等异步调用,就回出现下面的方法不能正确执行, 实例代码如下: public String runMethod(String syncId) { try { //处理Datapull dataPullService.setSyncId(syncId); //设置数据库参数 dataPullService.setJdbcUrl

随机推荐