Conclusions on the framework of CXF webservice

  First, let's talk about the webservice advantage of it, the biggest advantage websevice is cross-platform cross-language remote call, is that you write a api released with java on webservice platform, others like using C ++, paython wrote platform also through webservice call you write api, likewise in turn do the same. Now the mainstream webservice framework Axis1 the Apache, the Apache Axis2, Codehaus XFire, the Apache CXF, Sun  JAX-WS (the most simple, convenient), and so, I have come to is that Axis2 and CXF, CXF feel than Axis2 simple and easy to use point , https: //www.cnblogs.com/ruiati/p/6640287.html the brother of the now more popular webservice framework are compared, are interested can look at. Well, the next start summarized webservice knowledge and CXF framework. (Because there is no contact with the landlord before webservice, it will start from the most basic).

1.webservice composition

  webservice by the XML + XSD, SOAP and WSDL components.

  1.1 xml+xsd

  webservice to send data via xml, but since xml data format and can not be clearly defined, and the type of data between different platforms may be inconsistent, it may lead to data errors accepted, so, when transferring data between different platforms need to harmonize data specifications, in order to unified specification to transmit data, accept data according to the specification, this would resolve the problem of transferring data type.

  1.2 soap

  SOAP (simple object access protocal) using XML-based data structure and hypertext transfer protocol to transfer (HTTP) data. = HTTP protocol SOAP protocol + XML data format.

  1.3 wsdl

  wsdl: Web Service Description Language, Web Services Description Language that is used to inform the population use or plan to use the webservice address of the interface, what needs to be transmitted, will return to what the details of that method calls. Before a client to call a WebService service, the WSDL file to know the address of the service. WebService service providers can be exposed in two ways its WSDL file address: 1 registered to UDDI server to be searched person; 2 directly to the client to tell the caller...

  1.4  SEI(WebService EndPoint Interface)

  SEI is a web service terminal interface is WebService interface to the server for processing the request.

2.CXF framework

  Here we just write about CXF distribution services and create a client about the process, do not integrate other frameworks, only use CXF.

  2.1 Creating server

  First, create a maven project (package manually guide the province), jdk is best to use 1.7, and then create an interface and its implementation class, add a method, with a focus on adding annotations @webservice preparing to release an interface and its implementation class , which is marked to be published interface.

 

 

 

 

 

   For example, I added in the interface of the two methods, a direct return information, to make a judgment after a return.

  Then, we need to release already written interfaces, we need to create a new class, to facilitate understanding of the name server. Publishing interface There are two ways, one for the Endpoint at Javax.xml.ws package, is released comes webservice java classes, interfaces directly with the release publish methods of the class, define their own specific address release; other is JaxWsServerFactoryBean under org.apache.cxf.jaxws package is cxf, the address can be set to be published, interface class, the implementation class, may be added to the input and output interceptor, interceptors can be implemented with secure authentication interface, adding white list of other operations.

 

 

  Thus the basic configuration server over, on, and also added in the maven dependency, the following specific dependency.

       <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-core</artifactId>
            <version>3.1.5</version>
        </dependency>

        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-frontend-jaxws</artifactId>
            <version>3.1.5</version>
        </dependency>
        <dependency>
            <groupId>org.apache.cxf</groupId>
            <artifactId>cxf-rt-transports-http-jetty</artifactId>
            <version>3.1.5</version>
        </dependency>

  

  Then we start tomcat, paste the address we define in the browser, and add in the back? wsdl suffix, if able to open normally, see the service name address, etc., that we successfully posted.

 

 

  

  2.2 Creating Client

  Before we create a client, you need to download the CXF framework, we need to use them wsdl2java tool, go to the official website CXF can download specific download process will not go, you should note that downloading need to configure the environment variables, add it to the path.

  Now we create a maven project for a client, we create a client needs to be generated from wsdl server released, so the first thing we need to start the server end before, then find where you want to generate a file in the client project in open the command line where you want to generate a file, with the wsdl tool to generate the desired file.

 

 

 

  

   If after running, as shown above, it represents a client code successfully generated, as shown makefile.

 

 

  Next, create a new class called client, in which a new webservice client class, interface class generated according to client class, we need to call the method according to the interface class.

 

public class Client {
    public static void main(String[] args) {
        HelloWorldServiceService helloworldServiceService =new HelloWorldServiceService();

        HelloWorldService helloworldService = helloworldServiceService.getHelloWorldServicePort();

        org.apache.cxf.endpoint.Client client = ClientProxy.getClient(helloworldService);
        client.getOutInterceptors().add(new AddHeaderInterceptor("lili","123"));//自定义输出拦截器
        client.getInInterceptors () the Add (. new new LoggingInInterceptor ()); // receiving data log interceptor 
        client.getOutInterceptors () the Add (. new new LoggingOutInterceptor ()); // send data log interceptor 

//         List <String> = the nums ArrayList new new <String> ();
 //         nums.add ( "One");
 //         nums.add ( "II");
 //         nums.add ( "III");
 //         nums.add ( "VI");
 //         for (String NUM: the nums
 //              ) {
 //             System.out.println (helloworldService.hi (NUM));
 //         } 

        List <User> users = new ArrayList<User>();
        users.add(new User("丽丽","123"));
        users.add(new User("花花","123"));
        users.add(new User("菲菲","123"));
        for (User user:users
             ) {
            Authority au = helloworldService.judgAuthority(user);
            System.out.println (I); 
        } 
    } 
}

 

  Then run the client main method to see the results.

  This is a client-side output, because we this is a simple test, it is written in the realization of server-side method of directly died authentication, the user name must be "Lily" or "Fifi" password must be 123, and in the client end we a first and a third test example of the right, the second is not correct, the client returns below.

 

   This is a server-side output, server-side output we let him what he received. As shown below.

 

 

   2.3 Creating interceptor

  Interceptor is a webservice be an important way to verify or filtration, can be a user name and password validated by the interceptor (Of course, you can also implement user name and password to verify the internal interface, but the interceptor verified was intercepted verified before it receives the data, and more for a number of strict security), ip authentication, etc., it is also an important way to ensure the security of the interface webservice.

  CXF interceptors there are four, the client's input interceptor, the output of the interceptor, the server-side input interceptor, the output of interceptors, their overall process is like this, the client output interceptor -> server input interceptor -> server output interceptor -> client input interceptors.

  First, we can add to the log interceptor, to the client service side are coupled with the input and output intercept. The main method is:.. GetInInterceptor () add (to add interceptors), getOutInterceptor () add (to add interceptors).

 

 

 

   

  Then start the server, run the client, there will be the following:

 

 

 

   The figure is a client logging, the details can be seen in detail receive data sent by the client, the server the same token, not posted.

  Now we define a user name and password validation interceptor, interceptors were added output and input interceptor in the client and server.

  First, a client of heaven output interceptor, AddHeaderInterceptor, adding interceptors header information for data sent to the head, add a user name and password, convenient service side validation. Note that the actual operation, how to verify, to the service and client communication between both sides, negotiated verify the contents of the communication mode.

 

 

public class AddHeaderInterceptor extends AbstractPhaseInterceptor<SoapMessage> {

    private String userName;
    private String password;

    public AddHeaderInterceptor(String userName, String password) {
        super(Phase.PREPARE_SEND);//这里的PREPARE_SEND表示在准备发送之前进行拦截
        this.userName=userName;
        this.password=password;
    }

    public void handleMessage(SoapMessage soapMessage) throws Fault {
        List<Header> headers = soapMessage.getHeaders();
        //因为发送的数据是xml格式的,所以此处是通过添加节点的方式添加用户名密码
        Document document = DOMUtils.createDocument();
        Element element = document.createElement("Auth");
        Element uElement = document.createElement("userName");//添加一个userName节点
        Element pElement = document.createElement("password");//添加一个password节点
        uElement.setTextContent(userName);//将用户名填写在节点中
        pElement.setTextContent(password);//将密码填写在节点中
        element.appendChild(uElement);
        element.appendChild(pElement);
        headers.add(new Header(new QName("auth"),element));
    }
}

  

  客户端添加完成之后,同理,我们在服务端添加进行验证的拦截器。

 

public class MyInterceptor extends AbstractPhaseInterceptor<SoapMessage> {


    public MyInterceptor() {
        super(Phase.PRE_INVOKE);//调用方法前调用自定义拦截器
    }

    public void handleMessage(SoapMessage soapMessage) throws Fault {
        List<Header> headers = soapMessage.getHeaders();
        if (headers==null||headers.size()==0){
            throw new Fault(new IllegalArgumentException("头部为空,请填写完整"));
        }
        
        //根据节点来读取数据
        Header header = headers.get(0);
        Element element = (Element) header.getObject();
        NodeList uList = element.getElementsByTagName("userName");
        NodeList pList = element.getElementsByTagName("password");

        if (uList.getLength()!=1){
            throw new Fault(new IllegalArgumentException("用户名格式不正确"));
        }
        if (pList.getLength()!=1){
            throw new Fault(new IllegalArgumentException("密码格式不正确"));
        }
        String userName = uList.item(0).getTextContent();
        String password = pList.item(0).getTextContent();

            if (!"lili".equals(userName)||!"123".equals(password)){
                throw new Fault(new IllegalArgumentException("用户名密码不正确"));
            }
    }
}

  

  为了方便,我们直接写死用户名密码,接下来我们测试一下。

  首先,测试一个错误的用户名密码,即用户名不为“lili”或者密码不为“123”,比如“feifei”,“123”

 

 

 

 

   

  从以上两图可以看到,客户端在接受完第一条返回值后就报了用户名密码错误的异常,服务端也是在接受完第一条数据后就报了异常,说明拦截器成功了。

  将客户端用户名密码改为正确的用户名密码后再次进行测试,结果正常。

 

 

 

 

Guess you like

Origin www.cnblogs.com/thePeaceOftheLord/p/11436556.html