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

相关文章

Windows环境下解决Matplotlib中文字体显示问题的详细教程

《Windows环境下解决Matplotlib中文字体显示问题的详细教程》本文详细介绍了在Windows下解决Matplotlib中文显示问题的方法,包括安装字体、更新缓存、配置文件设置及编码調整,并... 目录引言问题分析解决方案详解1. 检查系统已安装字体2. 手动添加中文字体(以SimHei为例)步骤

Spring Boot中的路径变量示例详解

《SpringBoot中的路径变量示例详解》SpringBoot中PathVariable通过@PathVariable注解实现URL参数与方法参数绑定,支持多参数接收、类型转换、可选参数、默认值及... 目录一. 基本用法与参数映射1.路径定义2.参数绑定&nhttp://www.chinasem.cnbs

MySql基本查询之表的增删查改+聚合函数案例详解

《MySql基本查询之表的增删查改+聚合函数案例详解》本文详解SQL的CURD操作INSERT用于数据插入(单行/多行及冲突处理),SELECT实现数据检索(列选择、条件过滤、排序分页),UPDATE... 目录一、Create1.1 单行数据 + 全列插入1.2 多行数据 + 指定列插入1.3 插入否则更

JAVA中安装多个JDK的方法

《JAVA中安装多个JDK的方法》文章介绍了在Windows系统上安装多个JDK版本的方法,包括下载、安装路径修改、环境变量配置(JAVA_HOME和Path),并说明如何通过调整JAVA_HOME在... 首先去oracle官网下载好两个版本不同的jdk(需要登录Oracle账号,没有可以免费注册)下载完

Spring StateMachine实现状态机使用示例详解

《SpringStateMachine实现状态机使用示例详解》本文介绍SpringStateMachine实现状态机的步骤,包括依赖导入、枚举定义、状态转移规则配置、上下文管理及服务调用示例,重点解... 目录什么是状态机使用示例什么是状态机状态机是计算机科学中的​​核心建模工具​​,用于描述对象在其生命

Spring Boot 结合 WxJava 实现文章上传微信公众号草稿箱与群发

《SpringBoot结合WxJava实现文章上传微信公众号草稿箱与群发》本文将详细介绍如何使用SpringBoot框架结合WxJava开发工具包,实现文章上传到微信公众号草稿箱以及群发功能,... 目录一、项目环境准备1.1 开发环境1.2 微信公众号准备二、Spring Boot 项目搭建2.1 创建

Java中Integer128陷阱

《Java中Integer128陷阱》本文主要介绍了Java中Integer与int的区别及装箱拆箱机制,重点指出-128至127范围内的Integer值会复用缓存对象,导致==比较结果为true,下... 目录一、Integer和int的联系1.1 Integer和int的区别1.2 Integer和in

SpringSecurity整合redission序列化问题小结(最新整理)

《SpringSecurity整合redission序列化问题小结(最新整理)》文章详解SpringSecurity整合Redisson时的序列化问题,指出需排除官方Jackson依赖,通过自定义反序... 目录1. 前言2. Redission配置2.1 RedissonProperties2.2 Red

IntelliJ IDEA2025创建SpringBoot项目的实现步骤

《IntelliJIDEA2025创建SpringBoot项目的实现步骤》本文主要介绍了IntelliJIDEA2025创建SpringBoot项目的实现步骤,文中通过示例代码介绍的非常详细,对大家... 目录一、创建 Spring Boot 项目1. 新建项目2. 基础配置3. 选择依赖4. 生成项目5.

nginx 负载均衡配置及如何解决重复登录问题

《nginx负载均衡配置及如何解决重复登录问题》文章详解Nginx源码安装与Docker部署,介绍四层/七层代理区别及负载均衡策略,通过ip_hash解决重复登录问题,对nginx负载均衡配置及如何... 目录一:源码安装:1.配置编译参数2.编译3.编译安装 二,四层代理和七层代理区别1.二者混合使用举例