欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springBoot整合CXF并實(shí)現(xiàn)用戶名密碼校驗(yàn)的方法

 更新時(shí)間:2018年08月15日 15:42:12   作者:__sky__  
這篇文章主要介紹了springBoot整合CXF并實(shí)現(xiàn)用戶名密碼校驗(yàn)的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

準(zhǔn)備工作:

創(chuàng)建springBoot項(xiàng)目webservice_server

創(chuàng)建springBoot項(xiàng)目webservice_client

分別添加CXF的依賴:

<!-- CXF webservice -->
<dependency>
  <groupId>org.apache.cxf</groupId>
  <artifactId>cxf-spring-boot-starter-jaxws</artifactId>
  <version>3.1.11</version>
</dependency>
<!-- CXF webservice -->

一.定義要發(fā)布的接口和實(shí)現(xiàn)類

接口:

@WebService
public interface AppService {


  @WebMethod
  String getUserName(@WebParam(name = "id") String id) throws UnsupportedEncodingException;
  @WebMethod
  public User getUser(String id) throws UnsupportedEncodingException;
}

實(shí)現(xiàn)類:

//name暴露的服務(wù)名稱, targetNamespace:命名空間,設(shè)置為接口的包名倒寫(默認(rèn)是本類包名倒寫). endpointInterface接口地址
@WebService(name = "test" ,targetNamespace ="http://cxf.wolfcode.cn/" ,endpointInterface = "cn.wolfcode.cxf.AppService")
public class AppServiceImpl implements AppService {
  JSONResult jsonResult = JSONResult.getJsonResult();
  @Override
  public String getUserName(String id) throws UnsupportedEncodingException {
    System.out.println("==========================="+id);
    JSONResult result= JSONResult.getJsonResult();
    result.setSuccess(true);
    result.setMessage("明哥");
    return result.toJsonObject();
  }
  @Override
  public User getUser(String id)throws UnsupportedEncodingException {
    System.out.println("==========================="+id);
    return new User(1L,"明哥");
  }
}

二.發(fā)布服務(wù)

1.定義配置類

@Configuration
public class CxfConfig {
  //默認(rèn)servlet路徑/*,如果覆寫則按照自己定義的來
  @Bean
  public ServletRegistrationBean dispatcherServlet() {
    return new ServletRegistrationBean(new CXFServlet(), "/services/*");
  }

  @Bean(name = Bus.DEFAULT_BUS_ID)
  public SpringBus springBus() {
    return new SpringBus();
  }

  //把實(shí)現(xiàn)類交給spring管理
  @Bean
  public AppService appService() {
    return new AppServiceImpl();
  }

  //終端路徑
  @Bean
  public Endpoint endpoint() {
    EndpointImpl endpoint = new EndpointImpl(springBus(), appService());
    endpoint.getInInterceptors().add(new AuthInterceptor());//添加校驗(yàn)攔截器
    endpoint.publish("/user");
    return endpoint;
  }
}

2.發(fā)布服務(wù)

@SpringBootApplication
public class WebserviceApplication {

  public static void main(String[] args) {
    SpringApplication.run(WebserviceApplication.class, args);
  }
}

因?yàn)槲姨砑恿擞脩裘兔艽a校驗(yàn)所以在發(fā)布之前還需要定義自己校驗(yàn)用戶名和密碼的Interceptor

public class AuthInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
  Logger logger = LoggerFactory.getLogger(this.getClass());
  private static final String USERNAME="root";
  private static final String PASSWORD="admin";

  public AuthInterceptor() {
    //定義在哪個(gè)階段進(jìn)行攔截
    super(Phase.PRE_PROTOCOL);
  }

  @Override
  public void handleMessage(SoapMessage soapMessage) throws Fault {
    List<Header> headers = null;
    String username=null;
    String password=null;
    try {
      headers = soapMessage.getHeaders();
    } catch (Exception e) {
      logger.error("getSOAPHeader error: {}",e.getMessage(),e);
    }

    if (headers == null) {
      throw new Fault(new IllegalArgumentException("找不到Header,無法驗(yàn)證用戶信息"));
    }
    //獲取用戶名,密碼
    for (Header header : headers) {
      SoapHeader soapHeader = (SoapHeader) header;
      Element e = (Element) soapHeader.getObject();
      NodeList usernameNode = e.getElementsByTagName("username");
      NodeList pwdNode = e.getElementsByTagName("password");
       username=usernameNode.item(0).getTextContent();
       password=pwdNode.item(0).getTextContent();
      if( StringUtils.isEmpty(username)||StringUtils.isEmpty(password)){
        throw new Fault(new IllegalArgumentException("用戶信息為空"));
      }
    }
    //校驗(yàn)用戶名密碼
    if(!(username.equals(USERNAME) && password.equals(PASSWORD))){
      SOAPException soapExc = new SOAPException("認(rèn)證失敗");
      logger.debug("用戶認(rèn)證信息錯(cuò)誤");
      throw new Fault(soapExc);
    }
  }
}

現(xiàn)在可以發(fā)布服務(wù)了.....

發(fā)布完成后訪問http://localhost:8888/services/user?wsdl

能夠出現(xiàn)以下界面就是發(fā)布OK

三.調(diào)用服務(wù)

1.新建調(diào)用端項(xiàng)目,添加依賴

2.因?yàn)槭纠菔玖藘煞N調(diào)用方式,其中一種需要用到接口,所以先把服務(wù)接口拷貝一份到調(diào)用端項(xiàng)目中(代碼就是上面接口的代碼)

3.因?yàn)榉?wù)端添加了用戶名密碼校驗(yàn),所以調(diào)用的時(shí)候需要添加用戶名密碼信息, 所以需要使用下面的Interceptor完成添加用戶名密碼信息

/**
 * Created by sky on 2018/2/27.
 */
public class LoginInterceptor extends AbstractPhaseInterceptor<SoapMessage> {
  private String username="root";
  private String password="admin";
  public LoginInterceptor(String username, String password) {
    //設(shè)置在發(fā)送請求前階段進(jìn)行攔截
    super(Phase.PREPARE_SEND);
    this.username=username;
    this.password=password;
  }

  @Override
  public void handleMessage(SoapMessage soapMessage) throws Fault {
    List<Header> headers = soapMessage.getHeaders();
    Document doc = DOMUtils.createDocument();
    Element auth = doc.createElementNS("http://cxf.wolfcode.cn/","SecurityHeader");
    Element UserName = doc.createElement("username");
    Element UserPass = doc.createElement("password");

    UserName.setTextContent(username);
    UserPass.setTextContent(password);

    auth.appendChild(UserName);
    auth.appendChild(UserPass);

    headers.add(0, new Header(new QName("SecurityHeader"),auth));
  }
}

4.調(diào)用接口

/**
 * Created by sky on 2018/2/27.
 */
public class Cxfclient {
  //webservice接口地址
  private static String address = "http://localhost:8888/services/user?wsdl";

  //測試
  public static void main(String[] args) {
    test1();
    test2();
  }

  /**
   * 方式1:使用代理類工廠,需要拿到對(duì)方的接口
   */
  public static void test1() {
    try {
      // 代理工廠
      JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
      // 設(shè)置代理地址
      jaxWsProxyFactoryBean.setAddress(address);
      //添加用戶名密碼攔截器
      jaxWsProxyFactoryBean.getOutInterceptors().add(new LoginInterceptor("root","admin"));;
      // 設(shè)置接口類型
      jaxWsProxyFactoryBean.setServiceClass(AppService.class);
      // 創(chuàng)建一個(gè)代理接口實(shí)現(xiàn)
      AppService cs = (AppService) jaxWsProxyFactoryBean.create();
      // 數(shù)據(jù)準(zhǔn)備
      String LineId = "1";
      // 調(diào)用代理接口的方法調(diào)用并返回結(jié)果
      User result = (User)cs.getUser(LineId);
      System.out.println("==============返回結(jié)果:" + result);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  /**
   * 動(dòng)態(tài)調(diào)用方式
   */
  public static void test2() {
    // 創(chuàng)建動(dòng)態(tài)客戶端
    JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
    Client client = dcf.createClient(address);
    // 需要密碼的情況需要加上用戶名和密碼
     client.getOutInterceptors().add(new LoginInterceptor("root","admin"));
    Object[] objects = new Object[0];
    try {
      // invoke("方法名",參數(shù)1,參數(shù)2,參數(shù)3....);
      System.out.println("======client"+client);
      objects = client.invoke("getUserName", "1");
      System.out.println("返回?cái)?shù)據(jù):" + objects[0]);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

嗯...總體上就是這么簡單, 演示代碼可以去這里下載:http://xz.jb51.net:81/201808/yuanma/springBoot_WebService_jb51.rar

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論