• 9、Web Service-IDEA-jaxrs 服务端客户端的实现


     关于RestFul编程可以参考:https://www.cnblogs.com/wang-yaz/p/9237981.html

     关于jaxrs的实现需要有restful的理解。

     话不多说直接上代码!!

    1、服务端的开发

    1、新建web项目、工程目录如下图

    2、pom文件添加依赖

    <?xml version="1.0" encoding="UTF-8"?>
    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.cr</groupId>
      <artifactId>server</artifactId>
      <version>1.0-SNAPSHOT</version>
    
      <name>server</name>
      <!-- FIXME change it to the project's website -->
      <url>http://www.example.com</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>org.apache.cxf</groupId>
          <artifactId>cxf-rt-frontend-jaxrs</artifactId>
          <version>3.0.1</version>
        </dependency>
    <!-- 内置jetty服务器 --> <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> <scope>test</scope> </dependency> <!--restful风格客户端调用所需要的 --> <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> <dependency> <groupId>org.codehaus.jettison</groupId> <artifactId>jettison</artifactId> <version>1.3.7</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> <showWarnings>true</showWarnings> </configuration> </plugin> </plugins> </build> </project>

    3、类:

    User.java
    注意需要和client端在同一个包里
    package com.cr.entity;
    
    import javax.xml.bind.annotation.XmlRootElement;
    
    //基于restful风格的webservice
    //客户端与服务的之间通讯可以传到xml、json
    
    //该注解指定对象序列化为xml或者json数据时根节点的名称
    //xml:  <User><id></id></User>
    //json:效率更高   {"User":"",pwd:""}
    
    @XmlRootElement(name = "User")
    public class User {
        private  String name;
        private  String  pwd;
    
        //.....
    }
    接口
    UserService.java
    package com.cr.service;
    
    import com.cr.entity.User;
    
    import javax.ws.rs.*;
    import java.util.List;
    
    //访问当前服务接口对应的路径
    @Path("/userService")
    @Produces("*/*")//支持任意类型
    public interface UserService {
    
        @POST
        @Path("/user")//访问当前端方法对应的路径
        @Consumes({"application/xml","application/json"})//服务器支持的请求数据格式类型
        public void save(User user);
    
        @GET
        @Path("/user")
        @Consumes({"application/xml","application/json"})
        @Produces("application/xml")
        public List<User> findUser();
    }
    接口的实现
    UserServiceImpl.java
    package com.cr.service.impl;
    
    import com.cr.entity.User;
    import com.cr.service.UserService;
    
    import java.util.ArrayList;
    import java.util.List;
    
    public class UserServiceImpl implements UserService {
        public void save(User user){
            System.out.println("save:"+user);
        }
    public List<User> findUser(){ List<User> uList = new ArrayList<>(); User u1 = new User("aa","qwe"); User u2 = new User("bb","asd"); uList.add(u1); uList.add(u2); System.out.println(uList); return uList; } }

    发布服务 

    package com.cr;
    import com.cr.service.impl.UserServiceImpl;
    import org.apache.cxf.interceptor.LoggingInInterceptor;
    import org.apache.cxf.interceptor.LoggingOutInterceptor;
    import org.apache.cxf.jaxrs.JAXRSServerFactoryBean;
    
    public class server {
    
        public static void main(String[] args) {
    
            //发布服务的工程
            JAXRSServerFactoryBean factoryBean = new JAXRSServerFactoryBean();
    
            //设置服务的 地址
            factoryBean.setAddress("http://localhost:8001/cr/");
    
            //设置服务类
            factoryBean.setServiceBean(new UserServiceImpl());
    
            //添加日志输入
            factoryBean.getInInterceptors().add(new LoggingInInterceptor());
            factoryBean.getOutInterceptors().add(new LoggingOutInterceptor());
    
            //发布服务
            factoryBean.create();
    
            System.out.println("发布成功...");
        }
    }

    2、客户端的代码

    1、工程结构

    2、pom文件

    <?xml version="1.0" encoding="UTF-8"?>
    
    <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      xsi:schemaLocation="http://maven.apache.org/POM/4.0.0http://maven.apache.org/xsd/maven-4.0.0.xsd">
      <modelVersion>4.0.0</modelVersion>
    
      <groupId>com.cr</groupId>
      <artifactId>client</artifactId>
      <version>1.0-SNAPSHOT</version>
    
      <name>client</name>
      <!-- FIXME change it to the project's website -->
      <url>http://www.example.com</url>
    
      <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.7</maven.compiler.source>
        <maven.compiler.target>1.7</maven.compiler.target>
      </properties>
    
      <dependencies>
        <dependency>
          <groupId>org.apache.cxf</groupId>
          <artifactId>cxf-rt-frontend-jaxrs</artifactId>
          <version>3.0.1</version>
        </dependency>
    <!-- 内置jetty服务器 --> <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> <scope>test</scope> </dependency> <!--restful风格客户端调用所需要的 --> <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> <dependency> <groupId>org.codehaus.jettison</groupId> <artifactId>jettison</artifactId> <version>1.3.7</version> </dependency> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> <showWarnings>true</showWarnings> </configuration> </plugin> </plugins> </build> </project>

    3、类

    User.java

    package com.cr.entity;
    
    import javax.xml.bind.annotation.XmlRootElement;
    
    //基于restful风格的webservice
    //客户端与服务的之间通讯可以传到xml、json
    
    //该注解指定对象序列化为xml或者json数据时根节点的名称
    //xml:  <User><id></id></User>
    //json:效率更高   {"User":"",pwd:""}
    
    @XmlRootElement(name = "User")
    public class User {
        private  String name;
        private  String  pwd;
            //....
    }

    测试:

    @Test
    public void save(){
        //远程调用服务端
        WebClient.
                create("http://localhost:8001/cr/userService/user").
                type("application/json").
                post(new User("qq","22"));
    }
    

    server端的打印 

    ----------------------------
    ID: 4
    Address: http://localhost:8001/cr/userService/user
    Encoding: ISO-8859-1
    Http-Method: POST
    Content-Type: application/json
    Headers: {Accept=[*/*], Cache-Control=[no-cache], connection=[keep-alive], Content-Length=[31], content-type=[application/json], Host=[localhost:8001], Pragma=[no-cache], User-Agent=[Apache CXF 3.0.1]}
    Payload: {"User":{"name":"qq","pwd":22}}
    --------------------------------------
    save:com.cr.entity.User@4986f0c7
    INFO  - LoggingOutInterceptor      - Outbound Message
    ---------------------------
    ID: 4
    Response-Code: 204
    Content-Type:
    Headers: {Date=[Mon, 18 Mar 2019 11:56:29 GMT], Content-Length=[0]}
    --------------------------------------

    测试:

    //查询
    @Test
    public void find(){
       WebClient.create("http://localhost:8001/cr/userService/user").get();
    }
    ID: 5
    Address: http://localhost:8001/cr/userService/user
    Http-Method: GET
    Content-Type: */*
    Headers: {Accept=[*/*], Cache-Control=[no-cache], connection=[keep-alive], content-type=[*/*], Host=[localhost:8001], Pragma=[no-cache], User-Agent=[Apache CXF 3.0.1]}
    --------------------------------------
    [com.cr.entity.User@7f4f702, com.cr.entity.User@3cb7324]
    INFO  - LoggingOutInterceptor      - Outbound Message
    ---------------------------
    ID: 5
    Response-Code: 200
    Content-Type: application/xml
    Headers: {Content-Type=[application/xml], Date=[Mon, 18 Mar 2019 11:57:38 GMT]}
    Payload: <?xml version="1.0" encoding="UTF-8"?><Users><User><name>aa</name><pwd>qwe</pwd></User><User><name>bb</name><pwd>asd</pwd></User></Users>

    3、额外的补充

    额外的补充都可以尝试去实现!!!

  • 相关阅读:
    告别单身淘宝小店
    微信机器人 细腻化
    # 导入模块 from wxpy import * # 初始化机器人,扫码登陆 bot = Bot()
    减小文件大小 减少 帧
    无有效图视频
    生成一张白色图片的算法--逻辑
    加logo
    字幕 3系数
    音频分析 字幕同步
    尊重百度的api语音合成规则
  • 原文地址:https://www.cnblogs.com/Mrchengs/p/10578981.html
Copyright © 2020-2023  润新知