zoukankan      html  css  js  c++  java
  • resteasy web Guice集成版本

     xxxx:8080/resteasy/messageservice/aaaa

    Hello : aaaa

    web.xml
      <context-param>
        <param-name>resteasy.guice.modules</param-name>
        <param-value>com.zlg.resteasy.MyGuiceModule</param-value>
      </context-param>
    
      <listener>
        <listener-class>org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener</listener-class>
      </listener>
      <servlet>
        <servlet-name>resteasy-servlet</servlet-name>
        <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>
      </servlet>
      <servlet-mapping>
        <servlet-name>resteasy-servlet</servlet-name>
        <url-pattern>/*</url-pattern>
      </servlet-mapping>  
    
    
    pom.xml
      <dependencies>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        
        <dependency>  
                <groupId>org.jboss.resteasy</groupId>  
                <artifactId>resteasy-guice</artifactId>  
                <version>3.0.16.Final</version> 
        </dependency>     
      </dependencies>
      <build>
        <finalName>resteasy</finalName>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                    <showDeprecation>true</showDeprecation>
                    <showWarnings>true</showWarnings>
                </configuration>
            </plugin>    
        </plugins>
      </build>
    
    
    public class MyGuiceModule implements Module{
    
        @Override
        public void configure(Binder binder) {
            // TODO Auto-generated method stub
            binder.bind(MessageService.class);
        }
    
    }
    
    @Path("/messageservice")  
    public class MessageService {  
       public MessageService(){} 
        @GET 
        @Path("/{param}")  
        public Response printMessage(@PathParam("param") String msg) {  
            String result = "Hello : " + msg;  
       
            return Response.status(200).entity(result).build();  
        }  
    } 

    RESTEasy:JAX-RS restful webservices 示例

    纯web版本

    pom添加依赖: 

     
    1. <dependencies>  
    2.         <dependency>  
    3.             <groupId>org.jboss.resteasy</groupId>  
    4.             <artifactId>resteasy-jaxrs</artifactId>  
    5.             <version>3.0.11.Final</version>  
    6.         </dependency>  
    7.     </dependencies>  

    web.xml添加servlet定义 

     
    1. <servlet>  
    2.     <servlet-name>resteasy-servlet</servlet-name>  
    3.     <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>  
    4.     <init-param>  
    5.       <param-name>javax.ws.rs.Application</param-name>  
    6.       <param-value>test.MyRESTEasyApplication</param-value>  
    7.     </init-param>  
    8.   </servlet>  
    9.   <servlet-mapping>  
    10.     <servlet-name>resteasy-servlet</servlet-name>  
    11.     <url-pattern>/*</url-pattern>  
    12.   </servlet-mapping>  


    JAX-RS定义 

     
    1. package test;  
    2.   
    3. import javax.ws.rs.core.Application;  
    4. import java.util.HashSet;  
    5. import java.util.Set;  
    6.   
    7. public class MyRESTEasyApplication extends Application {  
    8.     private Set<Object> singletons = new HashSet<Object>();  
    9.   
    10.     public MyRESTEasyApplication() { singletons.add(new HelloWorldRestService()); }  
    11.   
    12.     @Override  
    13.     public Set<Object> getSingletons() { return singletons; }  
    14. }  
    [java] view plain copy
     
    1. package test;  
    2.   
    3. import javax.ws.rs.GET;  
    4. import javax.ws.rs.Path;  
    5. import javax.ws.rs.PathParam;  
    6. import javax.ws.rs.core.Response;  
    7.   
    8. @Path("/hello")  
    9. public class HelloWorldRestService {  
    10.     @GET  
    11.     public Response defaultResponse() {  
    12.         return Response.status(404).entity("404: Default Response ....").build();  
    13.     }  
    14.   
    15.     @GET  
    16.     @Path("/{param}")  
    17.     public Response getName(@PathParam("param") String name) {  
    18.         String result = "RESTEasy Hello World : " + name;  
    19.         return Response.status(200).entity(result).build();  
    20.     }  
    21. }  

    web Guice集成版本

    pom添加依赖:
    [html] view plain copy
     
    1. <dependencies>  
    2.         <dependency>  
    3.             <groupId>org.jboss.resteasy</groupId>  
    4.             <artifactId>resteasy-guice</artifactId>  
    5.             <version>3.0.16.Final</version>  
    6.         </dependency>  
    7.     </dependencies>  
    web.xml添加内容:
    [html] view plain copy
     
    1. <context-param>  
    2.     <param-name>resteasy.guice.modules</param-name>  
    3.     <param-value>guice.hello.MyGuiceModule</param-value>  
    4. </context-param>  
    5.   
    6. <listener>  
    7.     <listener-class>  
    8.         org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener  
    9.     </listener-class>  
    10. </listener>  
    11.   
    12. <servlet>  
    13.     <servlet-name>Resteasy</servlet-name>  
    14.     <servlet-class>org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher</servlet-class>  
    15. </servlet>  
    16.   
    17. <servlet-mapping>  
    18.     <servlet-name>Resteasy</servlet-name>  
    19.     <url-pattern>/*</url-pattern>  
    20. </servlet-mapping>  

    java代码:
    [java] view plain copy
     
    1. package guice.hello;  
    2.   
    3. public interface Greeter {  
    4.     String greet(String name);  
    5. }  
    [java] view plain copy
     
    1. package guice.hello;  
    2.   
    3. import javax.inject.Singleton;  
    4.   
    5. @Singleton  
    6. public class DefaultGreeter implements Greeter {  
    7.     public String greet(String name) {  
    8.         System.out.println(this);  
    9.         return "Hello " + name;  
    10.     }  
    11. }  
    [java] view plain copy
     
    1. package guice.hello;  
    2.   
    3. import com.google.inject.Binder;  
    4. import com.google.inject.Module;  
    5.   
    6. // TODO: 可参考 core 模块中的例子:com.conquer.comutils.core.guice.MyGuiceModule  
    7. public class MyGuiceModule implements Module {  
    8.     public void configure(final Binder binder) {  
    9.         binder.bind(MyResource.class);  
    10.         binder.bind(Greeter.class).to(DefaultGreeter.class)  
    11.         //                使用 javax.inject.Singleton() 标注 实现类 实现单例  
    12. //                .in(com.google.inject.Scopes.SINGLETON)// 这里设置单例,默认不是单例的而是每次创建  
    13.         ;  
    14.     }  
    15. }  
    [java] view plain copy
     
    1. package guice.hello;  
    2.   
    3. import javax.inject.Inject;  
    4. import javax.ws.rs.GET;  
    5. import javax.ws.rs.Path;  
    6. import javax.ws.rs.PathParam;  
    7.   
    8. @Path("hello")  
    9. public class MyResource {  
    10.     private final Greeter greeter;  
    11.   
    12.     @Inject  
    13.     public MyResource(final Greeter greeter) {  
    14.         this.greeter = greeter;  
    15.     }  
    16.   
    17.     @GET  
    18.     @Path("{name}")  
    19.     public String hello(@PathParam("name") final String name) {  
    20.         return greeter.greet(name);  
    21.     }  
    22. }  

    @GET、@POST、@PUT、@DELETE 以及 @HEAD 均是 HTTP 请求方法指示符注释

    https://www.ibm.com/developerworks/cn/web/wa-jaxrs/

    @path:  顾名思义,就是请求的处理路径

    Java 资源

    JAX-RS 建立了一种特殊的语言来描述资源,正如由其编程模型所表示的。有五种主要条目:根资源、子资源、资源方法、子资源方法以及子资源定位器。

     @Path 的使用
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    package com.ibm.jaxrs.sample.organization;
     
    import java.util.List;
    import javax.ws.rs.GET;
    import javax.ws.rs.Path;
    import javax.ws.rs.PathParam;
     
    @Path(value="/contacts")
    public class ContactsResource {
     
             
        @GET
        @Path(value="/{emailAddress:.+@.+\.[a-z]+}")
        public ContactInfo getByEmailAddress(@PathParam(value="emailAddress")
            String emailAddress) {
            ...
        }
         
        @GET
        @Path(value="/{lastName}")
        public ContactInfo getByLastName(@PathParam(value="lastName") String lastName) {
            ...
        }
    }

    ContactsResource 类上的注释表明对 /contacts 路径的所有请求都将由 ContactsResource 根资源处理。

    getByEmailAddress 上的 @Path 注释则表明任何发送到 /contacts/{emailAddress} 的请求(其中 emailAddress 代表的是正则表达式 .+@.+\.[a-z]+)都将由 getByEmailAddress 处理。

    getByLastName 方法上的 @Path 注释指定了发送到 /contacts/{lastName} 路径的所有请求(其中 lastName 代表的是一个与getByEmailAddress 内的正则表达式不匹配的有效的 URL 部分)都将由 getByLastName 方法处理。

    https://www.cnblogs.com/jhcelue/p/7053959.html

    http://docs.jboss.org/resteasy/docs/3.0.9.Final/userguide/html_single/index.html#d4e2122

    Chapter 48. Guice 3.0 Integration

    RESTEasy has some simple integration with Guice 3.0.

    RESTEasy will scan the binding types for a Guice Module for @Path and @Provider annotations. It will register these bindings with RESTEasy. The guice-hello project that comes in the RESTEasy examples/ directory gives a nice example of this.

    @Path("hello")
    public class HelloResource
    {
       @GET
       @Path("{name}")
       public String hello(@PathParam("name") final String name) {
          return "Hello " + name;
       }
    }
    

    First you start off by specifying a JAX-RS resource class. The HelloResource is just that. Next you create a Guice Module class that defines all your bindings:

    import com.google.inject.Module;
    import com.google.inject.Binder;
    
    public class HelloModule implements Module
    {
        public void configure(final Binder binder)
        {
           binder.bind(HelloResource.class);
        }
    }
    

    You put all these classes somewhere within your WAR WEB-INF/classes or in a JAR within WEB-INF/lib. Then you need to create your web.xml file. You need to use the GuiceResteasyBootstrapServletContextListener as follows

    <web-app>
        <display-name>Guice Hello</display-name>
    
        <context-param>
            <param-name>resteasy.guice.modules</param-name>
            <param-value>org.jboss.resteasy.examples.guice.hello.HelloModule</param-value>
        </context-param>
    
        <listener>
            <listener-class>
                org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener
            </listener-class>
        </listener>
    
        <servlet>
            <servlet-name>Resteasy</servlet-name>
            <servlet-class>
                org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
            </servlet-class>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>Resteasy</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
    
    </web-app>
    
    

    GuiceResteasyBootstrapServletContextListener is a subclass of ResteasyBootstrap, so you can use any other RESTEasy configuration option within your web.xml file. Also notice that there is a resteasy.guice.modules context-param. This can take a comma delimited list of class names that are Guice Modules.

    48.1. Request Scope

    Add the RequestScopeModule to your modules to allow objects to be scoped to the HTTP request by adding the @RequestScoped annotation to your class. All the objects injectable via the @Context annotation are also injectable, except ServletConfig and ServletContext.

    import javax.inject.Inject;
    import javax.servlet.http.HttpServletRequest;
    import javax.ws.rs.core.Context;
    
    import org.jboss.resteasy.plugins.guice.RequestScoped;
    
    @RequestScoped
    public class MyClass
    {
        @Inject @Context
        private HttpRequest request;
    }
    
    

    48.2. Binding JAX-RS utilities

    Add the JaxrsModule to bind javax.ws.rs.ext.RuntimeDelegate, javax.ws.rs.core.Response.ResponseBuilder, javax.ws.rs.core.UriBuilder, javax.ws.rs.core.Variant.VariantListBuilder and org.jboss.resteasy.client.ClientExecutor.

    48.3. Configuring Stage

    You can configure the stage Guice uses to deploy your modules by specific a context param, resteasy.guice.stage. If this value is not specified, Resteasy uses whatever Guice's default is.

    <web-app>
        <display-name>Guice Hello</display-name>
    
        <context-param>
            <param-name>resteasy.guice.modules</param-name>
            <param-value>org.jboss.resteasy.examples.guice.hello.HelloModule</param-value>
        </context-param>
    
        <context-param>
            <param-name>resteasy.guice.stage</param-name>
            <param-value>PRODUCTION</param-value>
        </context-param>
    
        <listener>
            <listener-class>
                org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener
            </listener-class>
        </listener>
    
        <servlet>
            <servlet-name>Resteasy</servlet-name>
            <servlet-class>
                org.jboss.resteasy.plugins.server.servlet.HttpServletDispatcher
            </servlet-class>
        </servlet>
    
        <servlet-mapping>
            <servlet-name>Resteasy</servlet-name>
            <url-pattern>/*</url-pattern>
        </servlet-mapping>
    
    </web-app>
    
    

    48.4. Custom Injector creation

    GuiceResteasyBootstrapServletContextListener can be extended to allow more flexibility in the way the Injector and Modules are created. Three methods can be overridden: getModules(), withInjector() and getStage(). Register your subclass as the listener in the web.xml.

    Override getModules() when you need to pass arguments to your modules' constructor or perform more complex operations.

    Override withInjector(Injector) when you need to interact with the Injector after it has been created.

    Override getStage(ServletContext) to set the Stage yourself.

    <web-app>
        <!-- other tags omitted -->
        <listener>
          <listener-class>
             org.jboss.resteasy.plugins.guice.GuiceResteasyBootstrapServletContextListener
          </listener-class>
        </listener>
    </web-app>
    
    public class MyServletContextListener extends GuiceResteasyBootstrapServletContextListener
    {
    
        @Override
        protected List<? extends Module> getModules(ServletContext context)
        {
            return Arrays.asList(new JpaPersistModule("consulting_hours"), new MyModule());
        }
        
        @Override
        public void withInjector(Injector injector)
        {
            injector.getInstance(PersistService.class).start();
        }
    }
    
    
  • 相关阅读:
    判断输入的是否是汉字(中文,不包括中文符号)
    第XX行将截断字符串或二进制数据。语句已终止
    Joomla学习之旅开始啦
    bean加载与注入之重新理解 L
    Excelsior JET 7.6 MP5 发布
    Squid Analyzer 5.1 发布,Squid日志统计
    flashrd 1.3 发布,OpenBSD 安装器
    Oracle 宣布 MySQL 5.6 正式版发布
    Spring Hateoas 0.4 发布
    MacPorts 2.1.3 发布,Mac 软件包管理
  • 原文地址:https://www.cnblogs.com/ydxblog/p/7891224.html
Copyright © 2011-2022 走看看