java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > springboot整合cxf发布webservice

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

作者:落叶清风

这篇文章主要介绍了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);
  }
 }
}

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

您可能感兴趣的文章:
阅读全文