webService的原理以及简单使用

webService是一种技术   实现多系统之间的通讯    

CXF框架是webService的具体实现

CXF分为  JAX-WS    JAX-RS
JAX-WS是基于xml格式传输数据  基于soap协议
JAX-RS是基于xml和json格式传输数据   基于HTTP协议

【JAX-WS独立使用】(了解)
    1 建立maven的java项目(jar包)
    2 导入cxfjar包的支持
            <!-- 要进行jaxws 服务开发 -->
            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-frontend-jaxws</artifactId>
                <version>3.0.1</version>
            </dependency>
            <!-- 内置jetty web服务器  -->
            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-transports-http-jetty</artifactId>
                <version>3.0.1</version>
            </dependency>
            <!-- 日志实现 -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>1.7.12</version>
            </dependency>
    3 实现domian和service层代码
        service层添加注解   在接口类上添加@WebService   
                            在接口类的方法上添加@WebMethod
                            在实现类上@WebService(endpointInterface = "cn.itcast.cxf.service.IUserService", serviceName = "userService")
    4 实现服务端的代码   将方法注册到网络
            // 1 、 服务实现对象
            IUserService userService = new UserServiceImpl();
            // 2、 发布服务地址
            String address = "http://localhost:9999/userService";
            // 3、 发布服务
            Endpoint.publish(address, userService);
    5 实现客户端的代码
            JaxWsProxyFactoryBean jaxWsProxyFactoryBean = new JaxWsProxyFactoryBean();
            jaxWsProxyFactoryBean.setServiceClass(IUserService.class);
            jaxWsProxyFactoryBean.setAddress("http://localhost:9999/userService");
            //设置监控 输入输出日志
            jaxWsProxyFactoryBean.getInInterceptors().add(new LoggingInInterceptor());
            jaxWsProxyFactoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
            // 创建调用远程服务代理对象
            IUserService proxy = (IUserService) jaxWsProxyFactoryBean.create();
            // 调用代理对象 任何一个方法,都将通过网络 调用web服务
            System.out.println(proxy.sayHello("传智播客"));
【JAX-WS和spring整合开发】
    1 建立maven工程(war包)
    2 导入坐标
            <!-- cxf ws 开发-->
            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-frontend-jaxws</artifactId>
                <version>3.0.1</version>
            </dependency>
            <!--spring开发 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>4.1.7.RELEASE</version>
            </dependency>
            <!-- spring开发-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>4.1.7.RELEASE</version>
            </dependency>
            <!-- spring整合测试-->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>4.1.7.RELEASE</version>
            </dependency>
            <!--测试 -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
    3 web.xml编写
            <!-- spring配置文件位置 -->
            <context-param>
                <param-name>contextConfigLocation</param-name>
                <param-value>classpath:applicationContext.xml</param-value>
            </context-param>
            <!-- spring核心监听器 -->
            <listener>
                <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
            </listener>
            <!-- CXF 基于 web 访问 -->
            <servlet>
                <servlet-name>CXFService</servlet-name>
                <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
                <load-on-startup>1</load-on-startup>
            </servlet>
            <servlet-mapping>
                <servlet-name>CXFService</servlet-name>
                <url-pattern>/services/*</url-pattern>
*/            </servlet-mapping>
    4 applicationContext.xml编写
            引入名称空间
            xmlns:jaxws="http://cxf.apache.org/jaxws"
            http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd
            <!--
                address 客户端访问服务路径   serviceClass 配置接口    serviceBean 配置实现类
             -->
            <jaxws:server id="userService" address="/userService"
                serviceClass="cn.itcast.cxf.service.IUserService">
                <jaxws:serviceBean>
                    <bean class="cn.itcast.cxf.service.UserServiceImpl" />
                </jaxws:serviceBean>
            </jaxws:server>
    5 访问路径
        基础路径+web中配置的路径+applicationContext中配置的路径
        http://localhost:9998/cxf_ws_spring/services/userService?wsdl
    6 客户端applicationContext配置(web.xml配置同上)
            <!--
                serviceClass 服务接口    address 服务访问地址
             -->
            <jaxws:client id="userServiceClient"
                serviceClass="cn.itcast.cxf.service.IUserService"
                address="http://localhost:9998/cxf_ws_spring/services/userService" >
                <!-- 来源消息拦截器 -->
                <jaxws:inInterceptors>
                    <bean class="org.apache.cxf.interceptor.LoggingInInterceptor"/>
                </jaxws:inInterceptors>
                <!-- 输出消息拦截器 -->
                <jaxws:outInterceptors>
                    <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
                </jaxws:outInterceptors>
            </jaxws:client>
【restful风格】*****
    Restful就是一个资源定位及资源操作的风格。不是标准也不是协议,只是一种风格,是对http协议的诠释。
    restful好处
        基于这种风格架构,软件编写可以更简洁
        基于 HTTP 协议, 支持多种消息格式,比如 XML 、JSON
        更易于实现缓存机制 (第一次访问资源 缓存,第二次访问资源,返回 304 客户端调用本地)
        POST 请求方式访问 保存操作    
        PUT  请求方式访问 修改操作    
        GET  请求方式访问 查询操作
        DELETE 请求方式访问 删除操作
【JAX-rs独立使用】(了解)         
    1 建立maven的java项目(jar包)
    2 导入坐标
            <!-- 使用CXF RS开发 -->
            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-frontend-jaxrs</artifactId>
                <version>3.0.1</version>
            </dependency>
            <!-- 内置jetty web服务器 -->
            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-transports-http-jetty</artifactId>
                <version>3.0.1</version>
            </dependency>
            <!-- 使用log4j日志实现  -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>1.7.12</version>
            </dependency>
    3 实体类和service创建
        实体类类名上写注解 @XmlRootElement(name="user") 指定序列化 转换成xml或json时使用的名字
         如果 WebService CXF 返回带有泛型的集合 ,解决需要在使用带有泛型的集合类型上面@XmlSeeAlso(类名.class) 注解
        service层
            @Path("/userService")
            public interface IUserService {
                @POST
                @Path("/user")
                @Consumes({ "application/xml", "application/json" })
                public void saveUser(User user);
                @PUT
                @Path("/user")
                @Consumes({ "application/xml", "application/json" })
                public void updateUser(User user);
                @GET
                @Path("/user")
                @Produces({ "application/xml", "application/json" })
                public List<User> findAllUsers();
                @GET
                @Path("/user/{id}")
                @Consumes("application/xml")
                @Produces({ "application/xml", "application/json" })
                public User finUserById(@PathParam("id") Integer id);
                @DELETE
                @Path("/user/{id}")
                @Consumes("application/xml")
                public void deleteUser(@PathParam("id") Integer id);
            }
        @path 服务访问资源路径
        @producers  传送给客户端的数据格式
        @consumers  处理客户端传递过来的数据格式
    4 服务器端实现
            // 创建业务接口 实现类对象
            IUserService userService = new UserServiceImpl();
            // 服务器FactoryBean 创建服务
            JAXRSServerFactoryBean jaxrsServerFactoryBean = new JAXRSServerFactoryBean();
            jaxrsServerFactoryBean.setResourceClasses(User.class, Car.class); // 将哪些实体数据转换xml、json发送
            jaxrsServerFactoryBean.setServiceBean(userService);
            jaxrsServerFactoryBean.setAddress("http://localhost:9997");
            // 发布服务
            jaxrsServerFactoryBean.create();
    5 访问路径  
        基础路径+类名上的@path+方法上的@path  http://localhost:9997/userService/user
    6 客户端实现    
            基于服务端的基础上再倒入一些jar包
            <!-- 使用rs客户端  -->
            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-rs-client</artifactId>
                <version>3.0.1</version>
            </dependency>
        // create 建立与调用 服务资源路径 连接
        // type 发送给服务器数据格式 --- @Consumes
        // accept 接收服务器传输数据格式 ---- @Produces
        // 采用HTTP协议哪种方式访问服务器
        Collection<? extends User> collection = WebClient
                .create("http://localhost:9997/userService/user")
                .accept(MediaType.APPLICATION_XML).getCollection(User.class);
        WebClient.create("http://localhost:9997/userService/user")
                .type(MediaType.APPLICATION_JSON).post(user);
        User resultUser = WebClient
                .create("http://localhost:9997/userService/user/1")
                .accept(MediaType.APPLICATION_JSON).get(User.class);
    7 如果指定转换json格式的数据需要另外导入jar包
            <!-- 在CXF扩展提供者,提供转换json接口  -->
            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-rs-extension-providers</artifactId>
                <version>3.0.1</version>
            </dependency>
            <!-- cxf 扩展提供者 转换json 默认需求一个工具包  -->
            <dependency>
                <groupId>org.codehaus.jettison</groupId>
                <artifactId>jettison</artifactId>
                <version>1.3.7</version>
            </dependency>
【JAX-RS和Spring整合开发】******
    1 建立maven web项目(war包)
    2 导入坐标
            <!-- cxf 进行rs开发 必须导入  -->
            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-frontend-jaxrs</artifactId>
                <version>3.0.1</version>
            </dependency>
            <!-- 日志引入  -->
            <dependency>
                <groupId>org.slf4j</groupId>
                <artifactId>slf4j-log4j12</artifactId>
                <version>1.7.12</version>
            </dependency>
            <!-- 客户端 -->
            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-rs-client</artifactId>
                <version>3.0.1</version>
            </dependency>
            <!-- 扩展json提供者 -->
            <dependency>
                <groupId>org.apache.cxf</groupId>
                <artifactId>cxf-rt-rs-extension-providers</artifactId>
                <version>3.0.1</version>
            </dependency>
            <!-- 转换json工具包,被extension providers 依赖 -->
            <dependency>
                <groupId>org.codehaus.jettison</groupId>
                <artifactId>jettison</artifactId>
                <version>1.3.7</version>
            </dependency>
            <!-- spring 核心 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-context</artifactId>
                <version>4.1.7.RELEASE</version>
            </dependency>
            <!-- spring web集成 -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-web</artifactId>
                <version>4.1.7.RELEASE</version>
            </dependency>        
            <!-- spring 整合junit  -->
            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>4.1.7.RELEASE</version>
            </dependency>
            <!-- junit 开发包 -->
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
            </dependency>
    3 web.xml配置
            <!-- spring配置文件位置 -->   <!-- spring核心监听器 --> ..........
            <servlet>
                <servlet-name>CXFService</servlet-name>
                <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
                <load-on-startup>1</load-on-startup>
            </servlet>
            <servlet-mapping>
                <servlet-name>CXFService</servlet-name>
                <url-pattern>/services/*</url-pattern>
*/            </servlet-mapping>
    4 applicationContext配置
        引入名称空间 xmlns:jaxrs="http://cxf.apache.org/jaxrs"
        http://cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd
        
        <jaxrs:server id="userService" address="/userService" >
            <jaxrs:serviceBeans>
                <bean class="cn.itcast.cxf.service.UserServiceImpl" />
            </jaxrs:serviceBeans>
            <jaxrs:inInterceptors>
                <bean class="org.apache.cxf.interceptor.LoggingInInterceptor" />
            </jaxrs:inInterceptors>
            <jaxrs:outInterceptors>
                <bean class="org.apache.cxf.interceptor.LoggingOutInterceptor" />
            </jaxrs:outInterceptors>
        </jaxrs:server>
    5 最终访问资源服务路径
        服务器根目录地址 + web.xml 配置 + applicationContext.xml address 配置 + 类 @Path +方法 @Path
    6 客户端代码
            Collection<? extends User> collection = WebClient
                    .create("http://localhost:9997/services/userService/user")
                    .accept(MediaType.APPLICATION_XML).getCollection(User.class);//查询所有数据
            WebClient.create("http://localhost:9997/services/userService/user")
                    .type(MediaType.APPLICATION_JSON).post(user);//保存user
            User resultUser = WebClient
                    .create("http://localhost:9997/services/userService/user/1")
                    .accept(MediaType.APPLICATION_JSON).get(User.class);//查询id是1的user
        
【客户与定区关联案例】
        1 引入jar包   bos系统中引入对crm_domain的依赖
          crm系统中配置web.xml 配置applicationContext.xml   实体类加@XmlRootElement注解
        2 crm的service层接口实现
                //查询未关联的客户信息
                @Path("/noassociationcustomers")
                @GET
                @Produces({"application/xml","application/json"})
                public List<Customer> findNoAssociationCustomers();                
                //已经关联的客户信息
                @Path("/associationfixedareacustomers/{fixedareaid}")
                @GET
                @Produces({"application/xml","application/json"})
                public List<Customer> findHasAssociationFixedAreaCustomers(
                        @PathParam("fixedareaid") String FixedAreaId);                
                //将客户关联到定区,将所有的客户id连接成字符串 1,2,3
                @PUT
                @Path("/associationcustomerstofixedarea")
                public void associationCustomersToFixedArea(
                        @QueryParam("customerIdStr") String customerIdStr,
                        @QueryParam("fixedAreaId") String fixedAreaId);
        3 crm的service层实现类
                    public List<Customer> findNoAssociationCustomers() {
                        return customerRepository.findByFixedAreaIdIsNull();
                    }
                    public List<Customer> findHasAssociationFixedAreaCustomers(String FixedAreaId) {
                        return customerRepository.findByFixedAreaId(FixedAreaId);
                    }
                    public void associationCustomersToFixedArea(String customerIdStr, String fixedAreaId) {
                        //解除关联
                        customerRepository.clearFixedAreaId(fixedAreaId);
                        //避免空指针异常
                        if(StringUtils.isBlank(customerIdStr) || "null".equals(customerIdStr)){
                            return;
                        }
                        //切割字符串
                        String[] split = customerIdStr.split(",");
                        for (String idstr : split) {
                            Integer id=Integer.parseInt(idstr);
                            customerRepository.updateFixedArea(fixedAreaId,id);
                        }
                    }
        3 crm的dao层实现
                public List<Customer> findByFixedAreaIdIsNull();
    
                public List<Customer> findByFixedAreaId(String fixedAreaId);
                
                @Query("update Customer set fixedAreaId=? where id=?")
                @Modifying
                public void updateFixedArea(String fixedAreaId,Integer id);
                
                @Query("update Customer set fixedAreaId=null where fixedAreaId=?")
                @Modifying
                public void clearFixedAreaId(String fixedAreaId);
        4 页面实现
            点击关联客户
            function doAssociations(){
                var rows=$("#grid").datagrid('getSelections');
                if(rows.length==1){
                    //将选中的定区id 设置到隐藏域中
                    $("#customerFixedAreaId").val(rows[0].id);
                    //显示进度条
                    $.messager.progress({
                        interval :500
                    });
                    //清空列表
                        $("#noassociationSelect").empty();
                        $("#associationSelect").empty();
                    //发起ajax请求
                    $.post("../../fixedArea_findNoAssociationCustomers.action",function(data){
                        $(data).each(function(){
                            var option="<option value='"+this.id+"'>"+this.username+"("+this.address+")</option>";
                            $("#noassociationSelect").append(option);
                        });
                        //请求结束后关闭进度条
                        $.messager.progress('close');
                        //弹出关联窗口
                        $('#customerWindow').window('open');
                    });
                    $.post("../../fixedArea_findHasAssociationFixedAreaCustomers.action",{"id":rows[0].id},function(data){
                        $(data).each(function(){
                            var option="<option value='"+this.id+"'>"+this.username+"("+this.address+")</option>";
                            $("#associationSelect").append(option);
                        });
                        //弹出关联窗口
                        $('#customerWindow').window('open');
                        })
                }else{
                    $.messager.alert("警告","只能选择一条数据","warning");
                }
            }
            关联客户实现
                //向右移动按钮
                $("#toRight").click(function(){
                    $("#associationSelect").append($("#noassociationSelect option:selected"));
                })
                //向左移动按钮
                $("#toLeft").click(function(){
                    $("#noassociationSelect").append($("#associationSelect option:selected"));
                });
                //关联客户按钮添加事件
                $("#associationBtn").click(function(){
                    //右侧列表 设置全选
                    $("#associationSelect option").attr("selected","selected");
                    //提交
                    $("#customerForm").submit();
                });
        5 bos系统的action层
                @Action(value="fixedArea_findNoAssociationCustomers",results={
                    @Result(name="success",type="json")
            })
            public String findNoAssociationCustomers(){
                Collection<? extends Customer> collection=WebClient.create
                ("http://localhost:9002/crm_management/services/customerService/noassociationcustomers")
                .accept(MediaType.APPLICATION_JSON).getCollection(Customer.class);
                
                ActionContext.getContext().getValueStack().push(collection);
                return SUCCESS;
            }
            
            @Action(value="fixedArea_findHasAssociationFixedAreaCustomers",results={
                    @Result(name="success",type="json")
            })
            public String findHasAssociationFixedAreaCustomers(){
                
                Collection<? extends Customer> collection=WebClient.create
                        ("http://localhost:9002/crm_management/services/customerService/associationfixedareacustomers/"+model.getId())
                        .accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON)
                        .getCollection(Customer.class);
                        
                        ActionContext.getContext().getValueStack().push(collection);
                return SUCCESS;
            }
            
            @Action(value="fixedArea_associationCustomerToFixedArea",results=
                {@Result(name="success",type="redirect",location="./pages/base/fixed_area.html")})
            public String associationCustomerToFixedArea(){
                String customerIdStr = StringUtils.join(customerIds, ",");
                WebClient.create("http://localhost:9002/crm_management/"
                        + "services/customerService/associationcustomerstofixedarea"
                        + "?customerIdStr="+customerIdStr+"&fixedAreaId="+model.getId()).put(null);
                return SUCCESS;
            }
        
       
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Web服务接口(Web Service Interface)是一种用于不同应用程序之间进行通信的技术。它使用标准的互联网协议来传输和交换数据,使得不同平台、不同语言编写的应用程序可以进行互操作。 Web服务接口的原理基于以下几个关键概念: 1. 通信协议:Web服务通常使用基于HTTP(超文本传输协议)的协议来进行通信。HTTP提供了一种简单、可靠的方式来在客户端和服务器之间传输数据。 2. 数据格式:Web服务使用基于XML(可扩展标记语言)的格式来描述数据,如SOAP(简单对象访问协议)和RESTful(表述性状态转移)风格。这些数据格式可以在不同的系统之间进行解析和传输,并保证数据的一致性和可靠性。 3. 服务描述语言:Web服务使用服务描述语言(Service Description Language,SDL)来描述服务的接口、方法和参数等信息。常用的SDL包括WSDL(Web Services Description Language)和Swagger。 4. 服务注册与发现:为了使客户端能够找到和使用特定的Web服务,需要使用服务注册与发现机制。这些机制可以通过注册表或目录服务来管理已发布的Web服务,并提供查询功能以获取有关服务的详细信息。 5. 安全机制:考虑到数据的安全性,Web服务还可以使用各种安全机制来保护通信和数据传输。例如,使用加密技术对数据进行加密和解密,使用身份验证和授权机制来确保只有授权用户才能访问服务等。 总结起来,Web服务接口的原理是基于标准的互联网协议和数据格式,在服务描述语言的规范下进行通信和数据交换,并通过注册与发现机制实现服务的可用性和可访问性。同时,还可以使用安全机制来保护通信和数据的安全性。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值