SPRINGBOOT整合CXF发布WEB SERVICE和客户端调用(用户和密码验证)

主要分为客户端和服务端

服务端

  1. pom配置
<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>webservice-service</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>webservice-service</name>
    <description>webservice-client</description>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <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>
            <version>4.5.4</version>
        </dependency>

        <!-- Fast Json -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.41</version>
        </dependency>
        <!-- CXF webservice -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
            <version>3.3.3</version>
            <exclusions>
                <exclusion>
                    <groupId>javax.validation</groupId>
                    <artifactId>validation-api</artifactId>
                </exclusion>
            </exclusions>
        </dependency>

    </dependencies>
    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>
  1. Config配置
@Configuration
public class CxfConfig {
    
    @Autowired
    private Bus bus;
    
    @Autowired
    private ServiceMaster serviceMaster;

    //------------------------------------------  默认是services ------------------------------------------
    @Bean
    public ServletRegistrationBean cxfServlet(){
        return new ServletRegistrationBean( new CXFServlet(), "/services/*");
    }
    @Bean
    public Endpoint endpoint(){
        EndpointImpl endpoint = new EndpointImpl(bus, serviceMaster);
        endpoint.publish("/ServiceMaster");
        endpoint.getInInterceptors().add(new ClientLoginInterceptor());
        endpoint.getInInterceptors().add(new AuthInterceptor());
        return endpoint;
    }

}

3.WebService拦截器验证

package com.example.webserviceclient.intercptor;

import org.apache.cxf.binding.soap.SoapMessage;
import org.apache.cxf.binding.soap.saaj.SAAJInInterceptor;
import org.apache.cxf.interceptor.Fault;
import org.apache.cxf.phase.AbstractPhaseInterceptor;
import org.apache.cxf.phase.Phase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.NodeList;

import javax.xml.soap.Name;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;

/**
 * 定义拦截器用户用户验证
 */
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 = "guanguan";
    private static final String USER_PASSWORD = "sailing2018!";
    public AuthInterceptor() {
        super(Phase.PRE_PROTOCOL);
        getAfter().add(SAAJInInterceptor.class.getName());
    }
    @Override
    public void handleMessage(SoapMessage message) throws Fault {
        System.out.println("来了哟!"+message);
        SOAPMessage mess = message.getContent(SOAPMessage.class);
        if(mess==null){
            saa.handleMessage(message);
            mess=message.getContent(SOAPMessage.class);
        }
        SOAPHeader header =null;
        try {
            header = mess.getSOAPHeader();
        } catch (SOAPException e) {
            logger.error("getSOAPheader error:{}",e.getMessage(),e);
            e.printStackTrace();
        }
        if(header==null){
            throw new Fault(new IllegalAccessException("找不到Header,无法验证用户信息"));
        }
        NodeList username = header.getElementsByTagName("username");
        NodeList password = header.getElementsByTagName("password");
        if(username.getLength()<1){
            throw new Fault(new IllegalAccessException("找不到Header,无法验证用户信息"));
        }
        if(password.getLength()<1){
            throw new Fault(new IllegalAccessException("找不到Header,无法验证用户信息"));
        }
        String userName = username.item(0).getTextContent().trim();
        String passWord = password.item(0).getTextContent().trim();
        if(USER_NAME.equals(userName)&&USER_PASSWORD.equals(passWord)){
            System.out.println("admin auth success");
            logger.info("admin auth success");
        }else {
            SOAPException soapException = new SOAPException("认证错误");
            logger.info("admin auth failed");
            throw new Fault(soapException);
        }
    }
}

4.客户端用户密码登录验证

package com.example.webserviceclient.intercptor;

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;

import javax.xml.namespace.QName;
import java.util.List;

public class ClientLoginInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
    private String username;
    private String password;
    public ClientLoginInterceptor() {
        super(Phase.PREPARE_SEND);
    }
    public ClientLoginInterceptor(String username, String password) {
        //super();
        super(Phase.PREPARE_SEND);
        this.username = username;
        this.password = password;
    }

    @Override
    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("timamaes"), auth));
    }
}

5.service处理类

import com.example.webserviceclient.service.ServiceMaster;
import org.springframework.stereotype.Service;
import javax.jws.WebService;

@Service
@WebService(serviceName = "ServiceMaster", targetNamespace = "http://service.webserviceclient.example.com", endpointInterface = "com.example.webserviceclient.service.ServiceMaster")
public class ServiceMasterImpl implements ServiceMaster {

    @Override
    public String sendMessage(String username) {
        System.out.println("---------------------"+username);
        return "收到消息啦!" + username;
    }
}
import javax.jws.WebMethod;
import javax.jws.WebParam;
import javax.jws.WebResult;
import javax.jws.WebService;

@WebService(name = "ServiceMaster", targetNamespace = "http://service.webserviceclient.example.com")//采用的是包的反向地址
public interface ServiceMaster {

    @WebMethod
    @WebResult(name = "String", targetNamespace = "http://service.webserviceclient.example.com")//采用的是包的反向地址
    String sendMessage(@WebParam(name = "username") String username);

}

客户端

1.pom

 <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.4.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>webservice-client</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>webservice-client</name>
    <description>webservice-client</description>
    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <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>
            <version>4.5.4</version>
        </dependency>

        <!-- Fast Json -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.1.41</version>
        </dependency>

        <!-- Web Service - cxf -->
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http</artifactId>
            <version>3.3.3</version>
        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.3.3</version>
        </dependency>

        <!-- Junit -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>RELEASE</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

2.测试代码

import com.example.webserviceclient.interceptor.ClientLoginInterceptor;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
import org.junit.Test;

public class WebController {

     @Test
     public void TestClient(){
         //----------------------------------------  创建动态客户端  ----------------------------------------

         JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
         Client client = dcf.createClient("http://localhost:8080/services/ServiceMaster?wsdl");
//此地址为服务端请求地址,端口配置文件中没有指定,默认为8080
        //-------------------------------  需要密码的情况需要加上用户名和密码  -----------------------------

         client.getOutInterceptors().add(new ClientLoginInterceptor("guanguan", "sailing2018!"));
         Object[] objects = new Object[0];

         try {
             // invoke("方法名",参数一,参数二,参数三....);
             objects = client.invoke("sendMessage", "天黑请闭眼。。。");
             System.out.println("返回数据:" + objects[0]);
         } catch (java.lang.Exception e) {
             e.printStackTrace();
         }

     }

}

认证通过时服务端后台打印
在这里插入图片描述
客服端打印
在这里插入图片描述
当认证不通过时
服务端
在这里插入图片描述
客户端
在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
### 回答1: Spring Boot是一个开发框架,它提供了很多便利的功能来简化Spring应用程序的开发。CXF是一个用于构建和部署Web服务的开源框架。整合Spring BootCXF可以让我们更容易地开发和部署Web服务。 要在Spring Boot整合CXF,我们需要首先添加CXF的依赖。可以在pom.xml文件中添加以下代码来引入CXF的依赖: ```xml <dependency> <groupId>org.apache.cxf</groupId> <artifactId>cxf-spring-boot-starter-jaxws</artifactId> <version>3.3.1</version> </dependency> ``` 接下来,我们需要创建一个配置类来配置CXF。可以创建一个名为CxfConfig的类,并使用@Configuration注解进行标注。在该类中,我们可以配置CXF的一些属性,例如请求路径和服务实现类等。 ```java @Configuration public class CxfConfig { @Autowired private Bus bus; @Bean public Endpoint endpoint() { EndpointImpl endpoint = new EndpointImpl(bus, new YourServiceImpl()); endpoint.publish("/your-service"); return endpoint; } } ``` 在上面的配置类中,我们使用@Autowired注解将Spring Boot的默认总线注入进来,并且创建了一个名为endpoint的bean。通过EndpointImpl类,我们可以将我们的服务实现类(YourServiceImpl)和请求路径(/your-service)与CXF进行绑定。 最后,我们需要在主应用类上添加@EnableWebServices注解,使得Spring Boot能够自动注册和部署我们的Web服务。 ```java @SpringBootApplication @EnableWebServices public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } ``` 通过以上步骤,我们就完成了Spring BootCXF整合。现在我们可以启动应用程序,并通过访问相应的路径来调用我们的Web服务了。 总结起来,Spring Boot整合CXF可以让我们更方便地开发和部署Web服务。我们只需要添加相关的依赖和配置类,并使用@EnableWebServices注解来注册和部署服务即可。整合CXF后,我们可以更加高效地构建和处理Web服务。 ### 回答2: Spring Boot是一个开源的Java开发框架,可以快速构建独立的、可运行的、生产级别的基于Spring框架的应用程序。而Apache CXF是一个Web服务框架,可以用于构建和开发SOAP和RESTful风格的Web服务。 在Spring Boot整合CXF可以实现基于JavaWeb服务的开发和部署。首先,我们需要引入CXF的依赖项,可以在pom.xml文件中添加相关的依赖。然后,我们可以创建一个配置类,使用CXF提供的注解配置Web服务的相关信息,例如服务地址、端口等。在配置类中,可以使用@Endpoint注解来标注Web服务的具体实现类。接下来,我们可以创建一个Spring Boot启动类,使用@EnableAutoConfiguration注解启用Spring Boot的自动配置功能,并使用@ImportResource注解导入CXF的配置文件。 通过以上步骤,我们就可以在Spring Boot应用中集成CXF。当应用启动时,CXF将根据配置类和注解,自动发布Web服务,并根据接口和实现类自动生成相关的WSDL文件和SOAP消息。此时,我们可以使用SOAPUI等工具来测试和调用这些Web服务。另外,CXF还提供了一些扩展点和配置选项,可以用于定制和优化Web服务的性能和安全性。 总的来说,Spring Boot整合CXF可以帮助我们快速、高效地开发和部署基于JavaWeb服务。通过使用Spring Boot的自动配置功能和CXF的注解配置,我们可以简化Web服务的开发过程,并提供可靠和高性能的Web服务。同时,Spring Boot还支持其他的Web服务框架,例如Jersey、Axis等,可以根据实际需求选择合适的框架。 ### 回答3: Spring Boot是一个开发框架,可以帮助开发者快速搭建基于SpringJava应用程序。而Apache CXF是一个开源的Web服务框架,可以用来构建和部署SOAP和RESTful服务。 在Spring Boot整合CXF可以使用以下步骤: 1.添加依赖:首先,在项目的pom.xml文件中添加CXF的依赖,以便能够使用CXF的相关功能。 2.配置CXFWeb服务:在Spring Boot的配置文件中,添加CXF的相关配置,包括服务地址、请求拦截器等。 3.创建Web服务接口:在项目中创建Web服务接口,定义服务的方法、参数和返回值。 4.实现Web服务接口:实现接口,并在实现类中编写具体的业务逻辑。 5.发布Web服务:使用CXF的相关注解,将实现类发布Web服务,使其能够被外部访问。 6.启动应用程序:启动Spring Boot应用程序,让CXFWeb服务开始监听请求。 通过以上步骤,我们就可以使用Spring Boot整合CXF,从而搭建一个可以提供SOAP或RESTful服务的应用程序。在这个应用程序中,我们可以使用CXF的一些特性,如拦截器和异常处理等,来增加应用程序的功能和稳定性。 总而言之,Spring Boot整合CXF能够大大简化CXF的配置过程,并使开发者能够更快地构建和部署Web服务。通过这种方式,我们可以更加高效地开发和管理我们的应用程序,提供更好的用户体验。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值