cxf+webservice基本配置及java.lang.ClassCastException: 服务端实体类 cannot be cast to 客户端实体类错误解决

本文主要是介绍cxf+webservice基本配置及java.lang.ClassCastException: 服务端实体类 cannot be cast to 客户端实体类错误解决,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

**

cxf+webservice基本配置及java.lang.ClassCastException: 服务端实体类 cannot be cast to 客户端实体类错误解决**

例如:java.lang.ClassCastException: com.xima.webservice.service.User cannot be cast to com.xima.breast.vo.User

其中User为wenservice传输的bean,两端bean中的属性相同

此处使用springboot,所用pom如下

         <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- http --><dependency><groupId>org.apache.httpcomponents</groupId><artifactId>httpclient</artifactId></dependency><dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.1.41</version></dependency><!-- 热部署模块 --><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-devtools</artifactId><optional>true</optional>  <!--这个需要为 true 热部署才有效 --></dependency><!-- CXF webservice --><dependency><groupId>org.apache.cxf</groupId><artifactId>cxf-spring-boot-starter-jaxws</artifactId><version>3.1.11</version></dependency>
先将基本代码附上:

webservice接口:

@WebService(targetNamespace="http://service.webservice.modular.anyu.com")
public interface TestUserService {@WebMethod//标注该方法为webservice暴露的方法,用于向外公布,它修饰的方法是webservice方法,去掉也没影响的,类似一个注释信息。@WebMethodList<User> getUserByAll();
}

webservice接口实现类:

@WebService(serviceName="TestUserService",//对外发布的服务名targetNamespace="http://service.webservice.modular.anyu.com",//指定你想要的名称空间,通常使用使用包名反转endpointInterface="com.anyu.modular.webservice.service.TestUserService")//服务接口全路径, 指定做SEI(Service EndPoint Interface)服务端点接口
@Component
public class TestUserServiceImpl implements TestUserService{@AutowiredBreastCureNodeDao breastCureNodeDao;//dao层,数据库查询public List<User> getUserByAll(){return breastCureNodeDao.selectUserByAll();}}

BreastCureNode 类 (bean):

@XmlRootElement(name="User")
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(propOrder= {""})
public class User implements Serializable {private static final long serialVersionUID = 1L;private Integer id;private String userName;private Integer age;private String six;private String school;private Date brithday;//.......get   ....set  ....toString省略}

webservice配置config

@Configuration
public class CxfConfig {@Autowiredprivate Bus bus;@AutowiredTestUserService testUserService;/*** 此方法作用是改变项目中服务名的前缀名,此处127.0.0.1或者localhost不能访问时,请使用ipconfig查看本机ip来访问* wsdl访问地址为:http://127.0.0.1:8080/soap/user?wsdl* 不用此方法,则访问 : http://127.0.0.1:8080/services/user?wsdl*/
//	@SuppressWarnings("all")
//	@Bean
//	public ServletRegistrationBean dispatcherServlet() {
//		return new ServletRegistrationBean(new CXFServlet(), "/soap/*");
//	}/*** 方法一*/// @Bean(name = Bus.DEFAULT_BUS_ID)// public SpringBus springBus() {// return new SpringBus();// }//// @Bean// public TestUserService testUserService() {// return new TestUserServiceImpl();// }//// @Bean// public Endpoint endpoint() {// EndpointImpl endpoint = new EndpointImpl(springBus(), testUserService());// endpoint.publish("/user");// return endpoint;// }/** * 方法二* 若有多个webservice,将下面方法复制,修改service和publish即可 **/@Beanpublic Endpoint endpoint() {EndpointImpl endpoint = new EndpointImpl(bus, testUserService);endpoint.publish("/user/breast");endpoint.getInInterceptors().add(new AuthInterceptor());//添加用户密码验证,去掉则客户端不需要用户密码验证return endpoint;}}

AuthInterceptor 用户名密码验证:

public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage>{private static final Logger logger = LoggerFactory.getLogger(AuthInterceptor.class);private SAAJInInterceptor saa = new SAAJInInterceptor();private static final String USER_NAME = "admin";private static final String USER_PASSWORD = "admin";public AuthInterceptor() {super(Phase.PRE_PROTOCOL);getAfter().add(SAAJInInterceptor.class.getName());}@Overridepublic void handleMessage(SoapMessage message) throws Fault {SOAPMessage mess = message.getContent(SOAPMessage.class);if (mess == null) {saa.handleMessage(message);mess = message.getContent(SOAPMessage.class);}SOAPHeader head = null;try {head = mess.getSOAPHeader();} catch (Exception e) {logger.error("getSOAPHeader error: {}",e.getMessage(),e);}if (head == null) {throw new Fault(new IllegalArgumentException("找不到Header,无法验证用户信息"));}NodeList users = head.getElementsByTagName("username");NodeList passwords = head.getElementsByTagName("password");if (users.getLength() < 1) {throw new Fault(new IllegalArgumentException("找不到用户信息"));}if (passwords.getLength() < 1) {throw new Fault(new IllegalArgumentException("找不到密码信息"));}String userName = users.item(0).getTextContent().trim();String password = passwords.item(0).getTextContent().trim();//可以从数据库获取用户名密码验证,也可以使用固定的用户名,密码//根据项目需要选择//固定的用户名和密码   此处为admin adminif(USER_NAME.equals(userName) && USER_PASSWORD.equals(password)){logger.debug("admin auth success");} else {SOAPException soapExc = new SOAPException("认证错误");logger.debug("admin auth failed");throw new Fault(soapExc);}}
}

客户端代码:

public class CxfClient {public static void main(String[] args) {CxfClient.main1();CxfClient.main2();}/*** 1.代理类工厂的方式,需要拿到对方的接口地址*/public static void main1() {try {// 接口地址String address = "http://192.168.0.100:8081/services/user/breast?wsdl";// 代理工厂JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();// 设置代理地址jaxWsProxyFactoryBean.setAddress(address);// 设置接口类型jaxWsProxyFactoryBean.setServiceClass(TestUserService.class);// 创建一个代理接口实现TestUserService us = (TestUserService) jaxWsProxyFactoryBean.create();// 数据准备// 调用代理接口的方法调用并返回结果String result = us.getUserByAll();System.err.println("返回结果:" + result);} catch (Exception e) {e.printStackTrace();}}/*** 2:动态调用*/public static void main2() {// 创建动态客户端JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();Client client = dcf.createClient("http://192.168.0.100:8081/services/user/breast?wsdl");// 需要密码的情况需要加上用户名和密码client.getOutInterceptors().add(new ClientLoginInterceptor("admin", "admin"));Object[] objects = new Object[0];try {// invoke("方法名",参数1,参数2,参数3....);objects = client.invoke("getUserByAll");List<User> users = (List<User>)objects[0];for (User user : users) {System.out.println(user.toString());}System.err.println("main2 : 动态调用  : 返回数据:" + objects[0]);} catch (java.lang.Exception e) {e.printStackTrace();}}
}

客户端User类:

public class User implements Serializable {private static final long serialVersionUID = 1L;private Integer id;private String userName;private Integer age;private String six;private String school;private Date brithday;//.......get   ....set  ....toString省略}

ClientLoginInterceptor 验证用户名,密码的类:

public class ClientLoginInterceptor extends AbstractPhaseInterceptor<SoapMessage>
{public ClientLoginInterceptor(String username, String password) {super(Phase.PREPARE_SEND);  this.username = username;this.password = password;}private String username;  private String password;public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}public void handleMessage(SoapMessage soap) throws Fault {List<Header> headers = soap.getHeaders();Document doc = DOMUtils.createDocument();Element auth = doc.createElement("authrity");Element username = doc.createElement("username");Element password = doc.createElement("password");username.setTextContent(this.username);password.setTextContent(this.password);auth.appendChild(username);auth.appendChild(password);headers.add(0, new Header(new QName("tiamaes"),auth));}}

此时基本代码书写完成,启动服务端,输入:http://localhost:8081/services/user/breast?wsdl则可以出现如下页面:

在这里插入图片描述

启动客户端: 则会报以下错误:

java.lang.ClassCastException: com.xima.webservice.service.User cannot be cast to com.xima.breast.vo.Userat com.example.demo.CxfClient.main2(CxfClient.java:79)at com.example.demo.CxfClient.main(CxfClient.java:26)
错误原因:

两个bean类的路径不同,导致映射失败;

将客户端User的路径改为com.xima.webservice.service.User即成功在客户端输出User数据

重点说明:bean类所在路径必须是wenservice的路径

这篇关于cxf+webservice基本配置及java.lang.ClassCastException: 服务端实体类 cannot be cast to 客户端实体类错误解决的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/410800

相关文章

Spring Boot中WebSocket常用使用方法详解

《SpringBoot中WebSocket常用使用方法详解》本文从WebSocket的基础概念出发,详细介绍了SpringBoot集成WebSocket的步骤,并重点讲解了常用的使用方法,包括简单消... 目录一、WebSocket基础概念1.1 什么是WebSocket1.2 WebSocket与HTTP

SpringBoot+Docker+Graylog 如何让错误自动报警

《SpringBoot+Docker+Graylog如何让错误自动报警》SpringBoot默认使用SLF4J与Logback,支持多日志级别和配置方式,可输出到控制台、文件及远程服务器,集成ELK... 目录01 Spring Boot 默认日志框架解析02 Spring Boot 日志级别详解03 Sp

java中反射Reflection的4个作用详解

《java中反射Reflection的4个作用详解》反射Reflection是Java等编程语言中的一个重要特性,它允许程序在运行时进行自我检查和对内部成员(如字段、方法、类等)的操作,本文将详细介绍... 目录作用1、在运行时判断任意一个对象所属的类作用2、在运行时构造任意一个类的对象作用3、在运行时判断

java如何解压zip压缩包

《java如何解压zip压缩包》:本文主要介绍java如何解压zip压缩包问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录Java解压zip压缩包实例代码结果如下总结java解压zip压缩包坐在旁边的小伙伴问我怎么用 java 将服务器上的压缩文件解压出来,

MySQL 中的 CAST 函数详解及常见用法

《MySQL中的CAST函数详解及常见用法》CAST函数是MySQL中用于数据类型转换的重要函数,它允许你将一个值从一种数据类型转换为另一种数据类型,本文给大家介绍MySQL中的CAST... 目录mysql 中的 CAST 函数详解一、基本语法二、支持的数据类型三、常见用法示例1. 字符串转数字2. 数字

SpringBoot中SM2公钥加密、私钥解密的实现示例详解

《SpringBoot中SM2公钥加密、私钥解密的实现示例详解》本文介绍了如何在SpringBoot项目中实现SM2公钥加密和私钥解密的功能,通过使用Hutool库和BouncyCastle依赖,简化... 目录一、前言1、加密信息(示例)2、加密结果(示例)二、实现代码1、yml文件配置2、创建SM2工具

Spring WebFlux 与 WebClient 使用指南及最佳实践

《SpringWebFlux与WebClient使用指南及最佳实践》WebClient是SpringWebFlux模块提供的非阻塞、响应式HTTP客户端,基于ProjectReactor实现,... 目录Spring WebFlux 与 WebClient 使用指南1. WebClient 概述2. 核心依

SQL Server配置管理器无法打开的四种解决方法

《SQLServer配置管理器无法打开的四种解决方法》本文总结了SQLServer配置管理器无法打开的四种解决方法,文中通过图文示例介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的... 目录方法一:桌面图标进入方法二:运行窗口进入检查版本号对照表php方法三:查找文件路径方法四:检查 S

Spring Boot @RestControllerAdvice全局异常处理最佳实践

《SpringBoot@RestControllerAdvice全局异常处理最佳实践》本文详解SpringBoot中通过@RestControllerAdvice实现全局异常处理,强调代码复用、统... 目录前言一、为什么要使用全局异常处理?二、核心注解解析1. @RestControllerAdvice2

Spring IoC 容器的使用详解(最新整理)

《SpringIoC容器的使用详解(最新整理)》文章介绍了Spring框架中的应用分层思想与IoC容器原理,通过分层解耦业务逻辑、数据访问等模块,IoC容器利用@Component注解管理Bean... 目录1. 应用分层2. IoC 的介绍3. IoC 容器的使用3.1. bean 的存储3.2. 方法注