SpringBoot+Axis2搭建WebService服务端
之前用过Spring + Axis2搭建过WebService项目,网上也有很多资料教程,最近需要在一个SpringBoot项目中添加Axis2的服务端,在网上找了很久,没有找到相关教程,最终经过大神朋友的指点,终于添加成功了,在此记录一下,防止忘记。
参考资料:https://www.cnkirito.moe/servlet-explore/?utm_source=tuicool&utm_medium=referral
改变一:添加services.xml时
spring项目时,有WEB-INF目录,services.xml配置文件需要放在此目录下,但是springboot下没有了这个目录,需要在resources目录下新建WEB-INF目录,然后把services.xml的相关目录放到WEB-INF下:
改变二:添加servlet时
spring项目时,可以在web.xml中配置,但是springboot项目没有了这个文件,我们可以通过java代码来实现添加:
@Bean
public ServletRegistrationBean helloWorldServlet() {
ServletRegistrationBean helloWorldServlet = new ServletRegistrationBean();
helloWorldServlet.setServlet(new AxisServlet());//这里的AxisServlet就是web.xml中的org.apache.axis2.transport.http.AxisServlet
helloWorldServlet.addUrlMappings("/services/*");
//通过默认路径无法找到services.xml,这里需要指定一下路径,且必须是绝对路径
helloWorldServlet.addInitParameter("axis2.repository.path", this.getClass().getResource("/WEB-INF").getPath().toString());
helloWorldServlet.setLoadOnStartup(1);
return helloWorldServlet;
}
后续
在实际部署后发现获得的路径里带有“!”,
导致Axis2无法正常使用这个路径,经过各种查资料,最终没有找到比较好的解决办法,只能用最笨的办法拷贝到项目所在的目录下来用了,解决方案如下:
@Bean
public ServletRegistrationBean helloWorldServlet() {
ServletRegistrationBean helloWorldServlet = new ServletRegistrationBean();
helloWorldServlet.setServlet(new AxisServlet());//这里的AxisServlet就是web.xml中的org.apache.axis2.transport.http.AxisServlet
helloWorldServlet.addUrlMappings("/services/*");
//通过默认路径无法找到services.xml,这里需要指定一下路径,且必须是绝对路径
String path = this.getClass().getResource("/WEB-INF").getPath().toString();
LogUtil.info("The original path:" + path);
if(path.toLowerCase().startsWith("file:")){
LogUtil.info("去掉前面的“file:”!");
path = path.substring(5);
}
if(path.indexOf("!") != -1){
try {
LogUtil.info("将WEB-INF/services/MyWebService/META-INF/services.xml文件拷贝到jar包同级目录下!");
FileCopyUtils.copy("WEB-INF/services/MyWebService/META-INF/services.xml");
} catch (IOException e) {
LogUtil.error(e);
}
LogUtil.info("jar包运行!查找jar包同级目录下的“/WEB-INF”目录");
path = path.substring(0, path.lastIndexOf("/", path.indexOf("!"))) + "/WEB-INF";
}
LogUtil.info("The final path:" + path);
helloWorldServlet.addInitParameter("axis2.repository.path", path);
helloWorldServlet.setLoadOnStartup(1);
return helloWorldServlet;
}
其中FileCopyUtils类是在网上找到的一个前辈写的:https://blog.csdn.net/sz85850597/article/details/81116755
另外发现“/WEB-INF”目录名是可以改的,不是非要叫这个名字。
技术有限,暂时无法完美解决,如有好的解决方案,请多指点。
附:源码 链接: https://pan.baidu.com/s/1zEo9pIQlkkLpeIBVzQ1yZw 提取码: kp9j
再后续
services.xml文件存放的目录问题,必须包含的目录结构:“axis2.repository.path”参数目录/services/自定义目录/META-INF/services.xml
其中services、META-INF、services.xml三个名字应该是不能修改,改了找不到服务了