• WebService之基于REST机制的实现实例(Java版)


    REST是REpresentational State Transfer的缩写(一般中文翻译为表述性状态转移)。2000年Roy Fielding博士在他的博士论文“Architectural Styles and the Design of Network-based Software Architectures”《体系结构与基于网络的软件架构设计》中提出了REST。

    REST是一种体系结构, 而HTTP是一种包含了REST架构属性的协议。

    REST基础概念

    • 在REST中所有东西都被看作资源。每一个资源都有一个URI和它对应。
    • 在REST中使用统一接口处理资源。与数据库CRUD操作(Create、Read、Update 和 Delete)一样,可以用POST、GET、PUT和DELETE处理REST资源。
    • 每个REST请求都是孤立的,请求中包含了所需的全部信息。REST服务端不存储状态。
    • REST支持不同的通信数据格式,比如XML、JSON。

    RESTful Web Services

    RESTful Web Services因其简单性被广泛使用,它比SOAP要更简单。本文将重点介绍如何使用Jersey框架创建RESTful Web Services。Jersey框架实现了JAX-RS接口。本文示例代码使用Eclipse和Java SE 8编写。

    一、新建项目:RESTfulWS ,然后创建RESTful Web Service服务端

    • 在Eclipse中创建一个“dynamic web project”(动态web工程) ,项目名设为 “RESTfulWS”。
    • 这里下载Jersey(https://jersey.github.io/)。示例代码使用的是Jersey 1.19.1。首先解压Jersey到“jersey-archive-1.19.1”文件夹。接着将里面lib文件夹下的jar文件拷贝到工程目录的WEB-INF -> lib。然后将它们添加到build path。
      1. asm-3.1.jar
      2. jersey-client-1.19.1.jar
      3. jersey-core-1.19.1.jar
      4. jersey-server-1.19.1.jar
      5. jersey-servlet-1.19.1.jar
      6. jsr311-api-1.1.1.jar
      7. jersey-bundle-1.19.1.jar(单独下载 http://mvnrepository.com/artifact/com.sun.jersey/jersey-bundle)

    在工程Java Resources -> src中创建“com.eviac.blog.restws”包,并在其中创建“UserInfo”类。

    UserInfo.java

    package com.eviac.blog.restws;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.PathParam;
    import javax.ws.rs.Produces;
    import javax.ws.rs.core.MediaType;
    /**
     * 
     * @author 
     * 
     */
    
    // 这里@Path定义了类的层次路径。
    // 指定了资源类提供服务的URI路径。
    @Path("UserInfoService")
    public class UserInfo {
        // @GET表示方法会处理HTTP GET请求
        @GET
        // 这里@Path定义了类的层次路径。指定了资源类提供服务的URI路径。
        @Path("/name/{i}")
        // @Produces定义了资源类方法会生成的媒体类型。
        @Produces(MediaType.TEXT_XML)
        // @PathParam向@Path定义的表达式注入URI参数值。
        public String userName(@PathParam("i")
        String i) {
            String name = i;
            return "<User>" + "<Name>" + name + "</Name>" + "</User>";
        }
    
        @GET
        @Path("/age/{j}")
        @Produces(MediaType.TEXT_XML)
        public String userAge(@PathParam("j")
        int j) {
            int age = j;
            return "<User>" + "<Age>" + age + "</Age>" + "</User>";
        }
    
        @GET
        @Path("/department/{k}")
        @Produces(MediaType.TEXT_XML)
        public String userDepartment(@PathParam("k")
        String k) {
            String userDepartment = k;
            return "<User>" + "<Department>" + userDepartment + "</Department>" + "</User>";
        }
    }

    最后把web.xml拷贝到WEB-INF目录下,web.xml内容为:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app id="WebApp_ID" version="2.5"
    	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    	xmlns="http://java.sun.com/xml/ns/javaee"
    	xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee">
    	<a href="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    		http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    	</a>
    
    	<display-name>RESTfulWS</display-name>
    	<servlet>
    		<servlet-name>Jersey REST Service</servlet-name>
    		<servlet-class>
    			com.sun.jersey.spi.container.servlet.ServletContainer
    		</servlet-class>
    		<init-param>
    			<param-name>
    				com.sun.jersey.config.property.packages
    			</param-name>
    			<param-value>com.eviac.blog.restws</param-value>
    		</init-param>
    		<load-on-startup>1</load-on-startup>
    	</servlet>
    	<servlet-mapping>
    		<servlet-name>Jersey REST Service</servlet-name>
    		<url-pattern>/rest/*</url-pattern>
    	</servlet-mapping>
    </web-app>
    
    • 将此webservice-URL拷贝到浏览器地址栏中运行:http://localhost:8080/RESTfulWS/rest/UserInfoService/name/lxj

    二、再新建一个项目:RestTest,来创建客户端,使用上一个项目发布的webservice服务接口

    • 首先创建一个独立新项目:RestTest (再次创建一个java project即可)。
    • 这里同样需要Jersey框架的lib目录下的jar包。解压Jersey到“jersey-archive-1.19.1”文件夹,接着将里面lib文件夹下的jar文件拷贝到工程目录的WEB-INF -> lib或者将它们添加到build path。

    asm-3.1.jar

    jersey-client-1.19.1.jar

    jersey-core-1.19.1.jar

    jersey-server-1.19.1.jar

    jersey-servlet-1.19.1.jar

    jsr311-api-1.1.1.jar

    jersey-bundle-1.19.1.jar(单独下载 http://mvnrepository.com/artifact/com.sun.jersey/jersey-bundle)

    • 创建一个“com.eviac.blog.restclient”包,然后新建“UserInfoClient”类。

    UserInfoClient.java

    package com.eviac.blog.restclient;
    
    import javax.ws.rs.core.MediaType;
    
    import com.sun.jersey.api.client.Client;
    import com.sun.jersey.api.client.ClientResponse;
    import com.sun.jersey.api.client.WebResource;
    import com.sun.jersey.api.client.config.ClientConfig;
    import com.sun.jersey.api.client.config.DefaultClientConfig;
    
    /**
     * 
     * @author pavithra
     * 
     */
    public class UserInfoClient {
    
        public static final String BASE_URI = "http://localhost:8080/RESTfulWS";
        public static final String PATH_NAME = "/UserInfoService/name/";
        public static final String PATH_AGE = "/UserInfoService/age/";
        public static final String PATH_DEP = "/UserInfoService/department/";
        /**
         * 返回客户端请求。 例如: GET
         * http://localhost:8080/RESTfulWS/rest/UserInfoService/name/Pavithra
         * 返回请求结果状态“200 OK”。
         * 
         * @param service
         * @return
         */
        private static String getClientResponse(WebResource resource) {
            return resource.accept(MediaType.TEXT_XML).get(ClientResponse.class)
                    .toString();
        }
    
        /**
         * 返回请求结果XML 例如:<User><Name>Pavithra</Name></User>
         * 
         * @param service
         * @return
         */
        private static String getResponse(WebResource resource) {
            return resource.accept(MediaType.TEXT_XML).get(String.class);
        }
        public static void main(String[] args) {
    
            String name = "雷小江";
            int age = 27;
            String department="中国***公司";
            ClientConfig config = new DefaultClientConfig();
            Client client = Client.create(config);
            WebResource resource = client.resource(BASE_URI);
    
            WebResource nameResource = resource.path("rest").path(PATH_NAME + name);
            System.out.println("Client Response 
    "
                    + getClientResponse(nameResource));
            System.out.println("Response 
    " + getResponse(nameResource) + "
    
    ");
    
            WebResource ageResource = resource.path("rest").path(PATH_AGE + age);
            System.out.println("Client Response 
    "
                    + getClientResponse(ageResource));
            System.out.println("Response 
    " + getResponse(ageResource));
            
            WebResource departmentResource = resource.path("rest").path(PATH_DEP + department);
            System.out.println("Client Response 
    "
                    + getClientResponse(departmentResource));
            System.out.println("Response 
    " + getResponse(departmentResource));
            
        }
    
    
    }
    • 运行客户端程序后,可以看到以下输出:
  • 相关阅读:
    HTML事件处理程序---内联onclick事件
    js的width函数
    了解跨站请求伪造CSRF
    离线百度地图
    GetOverlappedResult 函数
    OVERLAPPED 结构
    SetupDi系列函数
    Linux 各个命令的缩写原型
    Linux grep命令
    Linux if[......] then ......else...... fi
  • 原文地址:https://www.cnblogs.com/Lxiaojiang/p/8990456.html
Copyright © 2020-2023  润新知