• Restful 和 Jersey介绍(Web Service )


    一:REST简单介绍

    REST 2000 年由 Roy Fielding 在博士论文中提出,他是 HTTP 规范 1.0 和 1.1 版的首席作者之中的一个。

    REST 中最重要的概念是资源(resources) ,使用全球 ID(通常使用 URI)标识。client应用程序使用 HTTP 方法(GET/ POST/ PUT/ DELETE )操作资源或资源集。

    RESTful Web 服务是使用 HTTP 和 REST 原理实现的 Web 服务。通常。RESTful Web 服务应该定义下面方面:

    Web 服务的基/根 URI。比方 http://host/<appcontext>/resources。

    支持 MIME 类型的响应数据,包含 JSON/XML/ATOM 等等。

    服务支持的操作集合(比如 POST、GET、PUT 或  DELETE)
    例如以下表所看到的:
    方法/资源 资源集合。 URI 如:
    http://host/<appctx>/resources   成员资源,URI 如:
    http://host/<appctx>/resources/1234 
    GET 列出资源集合的全部成员检索标识为 1234 的资源的表示形式。
    PUT 使用一个集合更新(替换)还有一个集合。

    更新标记为 1234 的数字资源。
    POST 在集合中创建数字资源在以下创建一个子资源。


    DELETE 删除整个资源集合。删除标记为 1234 的数字资源。


    二:REST 与 JSR(jersey)

    JSR-311  Java API for RESTful Web Services (JAX-RS) 1.0 and 1.1

          JAX-RS是将在JavaEE 6引起的一种新技术。 JAX-RS即Java API for RESTful Web Services。是一个Java 编程语言的应用程序接口 ,支持依照表述性状态转移(REST)架构风格创建Web服务。

    JAX-RS使用了Java SE5引入的Java标注来简化Web服务的client和服务端 的开发和部署。包含:
     
    @Path。标注资源类或者方法的相对路径   
    @GET。@PUT。@POST。@DELETE,标注方法是HTTP请求的类型。

      
    @Produces,标注返回的MIME媒体类型   
    @Consumes。标注可接受请求的MIME媒体类型
    @PathParam。@QueryParam。@HeaderParam。@CookieParam,@MatrixParam。@FormParam,分别标注方法的參数来自于HTTP请求的不同位置。比如@PathParam来自于URL的路径,@QueryParam来自于URL的查询參数,@HeaderParam来自于HTTP请求的头信息,@CookieParam来自于HTTP请求的Cookie,@FormParam来自于HTTP请求的post的form格式。


     
    三:Jersey jar包简单介绍
     
    Jersey 是 JAX-RS 的參考实现,它包括三个主要部分。


    核心server(Core Server):通过提供 JSR 311 中标准化的凝视和 API 标准化,您能够用直观的方式开发 RESTful Web 服务。

    核心client(Core Client):Jersey client API 帮助您与 REST 服务轻松通信。

    集成(Integration):Jersey 还提供能够轻松集成 Spring、Guice、Apache Abdera 的库。

     注意:jar包下载 jersey jar包下载(须要积分的哦,辛苦整理的)

    四:自己创建一个rest资源

    用微账户的查询接口作一个样例
     
    Java代码  
    @Path("/accinfo")// prgramname/rest/下的路径 
    public class AccountInfoResource {  
        @Context  
        UriInfo uriInfo;  
        @Context  
        Request request;  
          
        /* 
         * Get all accounts info 
         */  
        @GET  
        @Path("all")// accinfo的子路径,也是外界调用的路径  
        @Produces(MediaType.APPLICATION_XML)  
        public List<AccountInfo> getAllaccounts() throws UnsupportedEncodingException{  
            List<AccountInfo> retList = new ArrayList<AccountInfo>();  
            EntityManager em = EntityManagerHelper.getEntityManager();  
            MaaccdtapManager mm = new MaaccdtapManager(em);  
            List<Maaccdtap> mList = mm.getAllAccounts();  
            AccountInfo ai = null;  
            AccountAdapter ad = new AccountAdapter();  
              
            for(Maaccdtap m : mList){             
                ai = ad.getAccountInfo(m);  
                retList.add(ai);  
            }  
              
            EntityManagerHelper.closeEntityManager();  
              
            return retList;  
        }     
          
        /* 
         * Get account info by mbrseq id   @GET方式
         */  
        @GET  
        @Path("{accountid}")// accinfo的子路径,也是外界调用的路径,既作为accountid又作为參数
        @Produces(MediaType.APPLICATION_JSON)  
        public AccountInfo getAccountBySid(@PathParam("accountid") String accountid)   
                throws UnsupportedEncodingException{  
              
            EntityManager em = EntityManagerHelper.getEntityManager();  
            MaaccdtapManager mm = new MaaccdtapManager(em);  
            Maaccdtap mp = mm.getAccountBySid(accountid);  
            AccountInfo ai = null;  
              
            if(null != mp){  
                AccountAdapter ad = new AccountAdapter();  
                ai = ad.getAccountInfo(mp);  
            }  
              
            EntityManagerHelper.closeEntityManager();  
              
            return ai;  
        }  
    /* 
         * Get account info by mbrseq id and name   @POST方式
         */
        @POST  
        @Path("change")  
        @Consumes(MediaType.APPLICATION_FORM_URLENCODED)  
        public void responseAccountChange(  
                @FormParam(value = "id") String id,  
                @FormParam(value = "name") String name,  
                @Context HttpServletResponse servletResponse) throws IOException{  
              
          
        System.out.println("Reveiced change parameters from UI:");  
        System.out.println("ID is " + id);  
        System.out.println("Name is " + name);  
          
        URI newUrl = uriInfo.getAbsolutePathBuilder().path(id).build();  
        System.out.println(newUrl.toString());  
          
        Response.created(newUrl).build();  
        //ServletOutputStream os = servletResponse.getOutputStream();  
        PrintWriter pw = servletResponse.getWriter();  
        pw.write("The change request has been sent to backend and id is " + id);  
        pw.flush();  
        }  

     }  

    測试:

    用以下的URL就可以訪问对应的账户信息(即Resource)

       http://ip:port/MicroAcc/rest/accinfo/{mbrseq}      

       http://ip:port/MicroAcc/rest/accinfo/al l

    @Produces(MediaType.APPLICATION_JSON)则能够产生Json的输出。

    @POST凝视会接收http post request, 将Web表单里的action指向POST的地址。比如:

       http://ip:port/MicroAcc/rest/accinfo/change 被凝视的方法就可以收到表单的内容。

    五:配置信息 Jersey配置:

    Jersey 1.2 以后的版本号和一些Update的维护版本号仅仅支持Java SE 6, 在选择版本号和对应server时须要注意。、

    从 Jersey 开发包中下面的库为必须:
    核心服务器:jersey-core.jar。jersey-server.jar。jsr311-api.jar。asm.jar
    核心客户端:(用于測试)jersey-client.jar
    JAXB 支持:(在高级例子中使用)jaxb-impl.jar,jaxb-api.jar。activation.jar,stax-api.jar,wstx-asl.jar
    JSON 支持:(在高级例子中使用)jersey-json.jar
    (JSON是类似于xml的一种通用。在不同project/语言/平台间传递数据的格式,其比xml更精炼更优良,差点儿全部的语言和框架已经支持了,传递过来的数据再用JSON解码就可以,就像c++struct结构体一样,直接json.xxx就可以訪问。多层的话就json.xxx.xxx)

    您须要将全部的 REST 请求发送到 Jersey 容器 —— 在应用程序的 web.xml 文件里定义 servlet 调度程序(參见清单 1)。

    除了声明 Jersey servlet 外,它还定义一个初始化參数,指示包括资源的 Java 包。

    Web.xml: Xml代码  

    <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>sh.cmbchina.pension.resources</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>  

     这样,全部在包sh.cmbchina.pension.resources以下的resource类都会被注冊为Restful url的响应处理类。


  • 相关阅读:
    DNS bind9安装
    DHCP服务器
    RAID
    LVM
    box-pack
    display:flex和display:box布局浏览器兼容性分析
    Flex布局
    几种常见的浏览器以及内核
    display 垂直居中
    font-family 定义的最后为什么要加一句sans-serif
  • 原文地址:https://www.cnblogs.com/lcchuguo/p/5153975.html
Copyright © 2020-2023  润新知