Spring Boot项目WebService接口发布、调用、以及常见错误详解

一、Spring Boot项目发布WebService接口

  • 添加maven依赖:
         <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
            <version>3.2.5</version>
        </dependency>
  • 定义Webservice接口:
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebService;

@WebService
public interface JobListService {

	@WebMethod
    String getList(@WebParam(name = "userId") String userId, @WebParam(name = "agentNum") Integer agentNum);
}
  • 定义接口实现类:targetNamespace 的值最好是包名反写,不是也没关系。endpointInterface 是webservice接口的地址,注意给这个类添加@Component直接注入到spring中
import javax.jws.WebService;

import org.springframework.stereotype.Component;

@WebService(targetNamespace = "http://webservice.test.fc.com/",
endpointInterface = "com.fc.test.webservice.JobListService")
@Component
public class JobListServiceImpl implements JobListService{

	@Override
    public String getList(String userId, Integer agentNum) {
        return "请求成功";
       
    }

}
  • 定义webservice接口服务的配置类:该类的作用是将改webservice服务以jobListService的名称发布出去。此处一定要注意springboot整合了shiro,需要把webservice路径添加到过滤路径上去
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;

@Configuration
public class WebServiceConfig {
	@Autowired
    private JobListService jobListService;
 
	/**
     * 注入servlet  bean name不能dispatcherServlet 否则会覆盖dispatcherServlet
     * @return
     */
    @Bean(name = "cxfServlet")
    public ServletRegistrationBean cxfServlet() {
        return new ServletRegistrationBean(new CXFServlet(),"/services/*");
    }

    @Bean(name = Bus.DEFAULT_BUS_ID)
    public SpringBus springBus() {
        return new SpringBus();
    }
 
 
    @Bean
    public Endpoint endpoint() {
        EndpointImpl endpoint = new EndpointImpl(springBus(), jobListService);
        endpoint.publish("/jobListService");
        return endpoint;
    }
}

在ShiroFilterMapFactory中的shiroFilterMap()方法,加上filterChainDefinitionMap.put("/services/**", "anon");此时启动项目就发布成功了

  • 启动springboot项目:一定要注意使用jdk运行项目不可用jre,必须要有jdk中的tools.jar;此处注意localhost有时不行,可以用127.0.0.1

访问如下目录:ip+端口/services/服务名称?wsdl
例如:http://localhost:8081/services/jobListService?wsdl

二、SpringBoot项目调用WebService接口,测试了第二种动态调用方式可用,其他两种方式未测试

//import javax.xml.rpc.ParameterMode;
//
//import org.apache.axis.client.Call;
//import org.apache.axis.client.Service;
//import org.apache.axis.encoding.XMLType;
import javax.xml.namespace.QName;

import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;

public class TestWebSevice {
	public static void main(String[] args) {
//		TestWebSevice.main1();
		TestWebSevice.main2();
//		doSelectRiskReportForm();
    }

    /**
     * 1.代理类工厂的方式,需要拿到对方的接口地址
     */
    public static void main1() {
        try {
            // 接口地址
            String address = "http://127.0.0.1:8080/services/jobListService?wsdl";
            // 代理工厂
            JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
            // 设置代理地址
            jaxWsProxyFactoryBean.setAddress(address);
            // 设置接口类型
            jaxWsProxyFactoryBean.setServiceClass(JobListService.class);
            // 创建一个代理接口实现
            JobListService us = (JobListService) jaxWsProxyFactoryBean.create();
            // 数据准备
            String userId = "zz";
            // 调用代理接口的方法调用并返回结果
            String result = us.getList("", 1);
            System.out.println("返回结果:" + result);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    /**
     * 2:动态调用
     */
    public static void main2() {
        // 创建动态客户端
        JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
        Client client = dcf.createClient("http://127.0.0.1:8080/services/jobListService?wsdl");
        // 需要密码的情况需要加上用户名和密码
        // client.getOutInterceptors().add(new ClientLoginInterceptor(USER_NAME, PASS_WORD));
        Object[] objects = new Object[0];
        try {
        	//如果有命名空间需要加上这个,第一个参数为命名空间名称,第二个参数为WebService方法名称
        	QName operationName = new QName("http://webservice.test.fc.com/","getList");
            // invoke("方法名",参数1,参数2,参数3....);
            objects = client.invoke(operationName, "maple",2);
            System.out.println("返回数据:" + objects[0]);
        } catch (java.lang.Exception e) {
            e.printStackTrace();
        }
    }
    
//    public static void doSelectRiskReportForm(){
//		//调用接口		
//		//方法一:直接AXIS调用远程的web service
//		try {  				
//            String endpoint = "http://localhost:8080/services/jobListService?wsdl";  	            
//            Service service = new Service();  
//            Call call = (Call) service.createCall();
//            call.setTargetEndpointAddress(endpoint);
//            String parametersName = "settle_num"; 		// 参数名//对应的是 public String printWord(@WebParam(name = "settle_num") String settle_num); 
//            call.setOperationName("getList");  		// 调用的方法名//当这种调用不到的时候,可以使用下面的,加入命名空间名
            call.setOperationName(new QName("http://jjxg_settlement.platform.bocins.com/", "printWord"));// 调用的方法名
//            call.addParameter(parametersName, XMLType.XSD_STRING, ParameterMode.IN);//参数名//XSD_STRING:String类型//.IN入参
//            call.setReturnType(XMLType.XSD_STRING); 	// 返回值类型:String
//            String message = "123456789";  
//            String result = (String) call.invoke(new Object[] { message });// 远程调用
//            System.out.println("result is " + result);  
//        } catch (Exception e) {  
//            System.err.println(e.toString());  
//        }  
//	}
    
    
}

三、接口调试工具SoapUI

免安装版下载链接:https://download.csdn.net/download/wgd930701/12701666

  • 1
    点赞
  • 18
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Spring Boot可以使用JAX-WS或者Spring Web Services(Spring-WS)来调用SOAP Web Service接口,也可以使用RestTemplate来调用RESTful Web Service接口。 以下是使用Spring-WS调用SOAP Web Service接口的步骤: 1. 引入Spring-WS和JAXB相关依赖 ```xml <dependency> <groupId>org.springframework.ws</groupId> <artifactId>spring-ws-core</artifactId> <version>3.0.7.RELEASE</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-core</artifactId> <version>3.0.0</version> </dependency> <dependency> <groupId>com.sun.xml.bind</groupId> <artifactId>jaxb-impl</artifactId> <version>3.0.0</version> </dependency> ``` 2. 配置WebServiceTemplate 在配置类中添加WebServiceTemplate的Bean,并设置WebServiceTemplate的Marshaller和Unmarshaller,这里使用Jaxb2Marshaller ```java @Configuration public class WebServiceConfig { @Bean public Jaxb2Marshaller marshaller() { Jaxb2Marshaller marshaller = new Jaxb2Marshaller(); marshaller.setContextPath("com.example.webservice.demo.wsdl"); return marshaller; } @Bean public WebServiceTemplate webServiceTemplate() { WebServiceTemplate template = new WebServiceTemplate(); template.setMarshaller(marshaller()); template.setUnmarshaller(marshaller()); template.setDefaultUri("http://localhost:8080/ws"); return template; } } ``` 3. 调用WebService 使用WebServiceTemplate的marshalSendAndReceive方法来发送SOAP请求并接收响应,示例代码如下: ```java @Autowired private WebServiceTemplate webServiceTemplate; public void callWebService() { GetCountryRequest request = new GetCountryRequest(); request.setName("Spain"); GetCountryResponse response = (GetCountryResponse) webServiceTemplate.marshalSendAndReceive(request); System.out.println(response.getCountry().getCapital()); } ``` 以上就是使用Spring-WS调用SOAP Web Service接口的步骤。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值