Springboot整合CXF发布Web service和客户端调用(用户和密码验证)

Springboot整合CXF发布Web service和客户端调用(用户和密码验证)

  • 服务端:
    • pom.xml
    • CXF 配置
    • ServiceMaster
    • ServiceMasterImpl
    • ClientLoginInterceptor
    • 服务端,定义拦截器用户用户验证
  • 客户端
    • pom.xml
    • WebController
    • 下载地址:https://download.csdn.net/download/qq_42459147/11870064

效果图:
Springboot整合CXF发布Web service和客户端调用(用户和密码验证)_第1张图片

服务端:

pom.xml

		<!-- 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>
        </dependency>

CXF 配置

@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.getInInterceptors().add(new AuthInterceptor());
         endpoint.publish("/ServiceMaster");
        return endpoint;
    }

}

ServiceMaster

@WebService(name = "ServiceMaster", targetNamespace = "http://serve.my.com")
public interface ServiceMaster {
     

    @WebMethod
    @WebResult(name = "String", targetNamespace = "")
    String sendMessage(@WebParam(name = "username") String username);

}

ServiceMasterImpl

@Component
@WebService(serviceName = "ServiceMaster", targetNamespace = "http://serve.my.com", endpointInterface = "com.my.serve.service.ServiceMaster")
public class ServiceMasterImpl implements ServiceMaster {
     

    @Override
    public String sendMessage(String username) {
     
        return "sendMessage:" + username;
    }
}

ClientLoginInterceptor

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.createElementNS("http://serve.my.com","ServiceMaster"); // ServiceMaster:命名空间
        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("identification"), auth));
    }
}

服务端,定义拦截器用户用户验证

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 = "123456";
    public AuthInterceptor() {
     
        super(Phase.PRE_PROTOCOL);
        getAfter().add(SAAJInInterceptor.class.getName());
    }
    @Override
    public void handleMessage(SoapMessage message) throws Fault {
     
        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)){
     
            logger.debug("admin auth success");
        }else {
     
            SOAPException soapException = new SOAPException("认证错误");
            logger.debug("admin auth failed");
            throw new Fault(soapException);
        }
    }
}

客户端

pom.xml

     <!-- 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>

WebController

public class WebController {
     

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

         JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
         Client client = dcf.createClient("http://localhost:8080/services/ServiceMaster?wsdl");

        //-------------------------------  需要密码的情况需要加上用户名和密码  -----------------------------

         client.getOutInterceptors().add(new ClientLoginInterceptor("admin", "123456"));

         Object[] objects = new Object[0];

         try {
     

             // invoke("方法名",参数一,参数二,参数三....);
             objects = client.invoke("sendMessage", "Mo-yec");
             System.out.println("返回数据:" + objects[0]);
         } catch (java.lang.Exception e) {
     
             e.printStackTrace();
         }

     }

}

下载地址:https://download.csdn.net/download/qq_42459147/11870064

你可能感兴趣的:(Java,CXF,Web,Service)