`
zhang_ly520
  • 浏览: 162523 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

Jersey and Spring

    博客分类:
  • java
阅读更多

Jersey and Spring

by Paul Sandoz

http://blogs.sun.com/enterprisetechtips/entry/jersey_and_spring

Jersey is an open-source, production-ready reference implementation of JAX-RS, the Java API for RESTful Web Services (JSR-311). JAX-RS is an annotation-driven API that makes it easy to build Java-based RESTful web services that adhere to the REST architectural style. The JAX-RS API is standardized by the Java Community Process. The JAX-RS API is currently at version 1.0 and Jersey is at version 1.0.2.

Jersey provides additional value beyond the JAX-RS API. It provides its own APIs that support Atom's XML format, MIME MultiPart message format , JavaScript Object Notation (JSON), Web Application Description Language (WADL), as well as Spring framework integration. Jersey is shipped with GlassFish and is available from the GlassFish version 2 and version 3 update centers.

An earlier Tech Tip, Implementing RESTful Web Services in Java, introduced RESTful Web Services, JAX-RS, and Jersey. It also showed how you can write RESTful web services that conform to the JAX-RS specification. Other tips on Jersey-related topics described how to configure JSON for RESTful web services in Jersey 1.0 and how to consume RESTful web services with the Jersey client API.

In this tip, you will learn how to use Jersey's integrated support for Spring, a framework for building and running enterprise Java applications. You'll learn how to configure Spring with Jersey and use Jersey's Spring-related features. The tip assumes that you are familiar with Spring concepts. If not, refer to the Spring Tutorial.

Creating a Basic Web Application

To demonstrate Jersey's Spring-related features, you'll first create a simple web application, one that does not use Spring and then change it to use Spring. Let's use the Maven 2 software project management tool to build the simple web application. If you're not familiar with Maven, see Welcome to Maven and Building Web Applications with Maven 2.

First, create a Maven 2 project by running the following Maven 2 archetype plugin in a command line:

   mvn archetype:generate -DarchetypeCatalog=http://download.java.net/maven/2

In response, Maven 2 will prompt you to choose an archetype, that is, a Maven 2 project template, from the archetypes listed in the archetype catalog, archetype-catalog.xml, at URL http://download.java.net/maven/2:

   Choose archetype:

   1: http://download.java.net/maven/2 -> jersey-quickstart-grizzly (Archetype for creating a RESTful web application with Jersey and Grizzly)

   2: http://download.java.net/maven/2 -> jersey-quickstart-webapp (Archetype for creating a Jersey based RESTful web application WAR packaging)

   Choose a number:  (1/2):

Choose 2, jersey-quickstart-webapp. You will then be prompted for a group ID and an artifact ID. Enter example.jersey.spring for the group ID and example-spring-jersey for the artifact ID. Accept the default values for the other prompts.

After you confirm the inputs, Maven 2 creates a new subdirectory called example-spring-jersey, which contains a template for the new Jersey-based web application. Figure 1 shows the expanded structure of the example-spring-jersey directory.

Figure 1. Expanded Structure of the example-spring-jersey directory

Maven 2 also creates a Project Object Model (POM) file, pom.xml, which contains an XML representation of the Maven project. You can find the pom.xml file in the example-spring-jersey directory. If you navigate below the example-spring-jersey directory to src/main/java/example/jersey/spring, you'll see a Java class named MyResource that represents a resource used in the application. You'll also find a web.xml file for the web application in the src/main/webapp/WEB-INF directory.

Let's build, deploy, and test the web application to see if it works. To build the application, go to the example-spring-jersey directory and enter the following command:

   mvn clean install

In response, Maven 2 compiles the source code and creates an example-spring-jersey.war file for the application.

To deploy the application, GlassFish V3 Prelude must be running. Start GlassFish V3 Prelude if it isn't already running. To start GlassFish V3 Prelude, enter the following command:

   <GF_install_dir/bin>asadmin start-domain domain1

where <GF_install_dir/bin> is the directory where you installed GlassFish v3 Prelude.

Deploy the application to GlassFish v3 Prelude using the following command:

   asadmin deploy --force=true target/example-spring-jersey.war

Finally, you can verify that the deployed application runs by using the command line tool, curl, as follows:

   curl -v http://localhost:8080/example-spring-jersey/webresources/myresource

In response, you should see the following output in the command window:

   * About to connect() to localhost port 8080 (#0)

   *   Trying 127.0.0.1... connected

   * Connected to localhost (127.0.0.1) port 8080 (#0)

   > GET /example-spring-jersey/webresources/myresource HTTP/1.1

   > User-Agent: curl/7.17.1 (i586-pc-mingw32msvc) libcurl/7.17.1 OpenSSL/0.9.7c zib/1.2.3

   > Host: localhost:8080

   > Accept: */*

   >

   < HTTP/1.1 200 OK

   < X-Powered-By: Servlet/2.5

   < Server: Sun Java System Application Server 9.1_02

   < Content-Type: text/plain

   < Transfer-Encoding: chunked

   < Date: Thu, 02 Apr 2009 22:18:29 GMT

   <

   Hi there!* Connection #0 to host localhost left intact

   * Closing connection #0

You can also verify the application by pointing your browser to the URL http://localhost:8080/example-spring-jersey/webresources/myresource. You should see the following text displayed on the page: Hi there!

Transforming the Web Application to Use Spring

Now let's change the web application to use Spring. To do that, you need to take the following actions:

·    Modify the pom.xml file to include Spring dependencies.

·    Create a Spring application context configuration file.

·    Modify the web.xml file to declare the Spring configuration.

·    Modify the root resource class to be a Spring component.

Modify the pom.xml File: Recall that one of the files generated when you created the Maven 2 project for the web application is a pom.xml file that represents the Maven project. Replace the contents of the pom.xml file with the content shown here.

The replacing code simplifies the Maven configuration to only use the required dependencies for this example. Note especially the following code, which adds the Jersey Spring dependency, using the jersey-spring module:

   <dependency>

       <groupId>com.sun.jersey.contribs</groupId>

       <artifactId>jersey-spring</artifactId>

       <version>${jersey-version}</version>

   </dependency>

Create a Spring Application Context Configuration: The Spring application context configuration file specifies an application's configuration for initialization by Spring. You need to create a Spring application context configuration file for the web application. Create a file applicationContext.xml and put it in the src/main/resources directory. The file should have the following content:

   <beans xmlns="http://www.springframework.org/schema/beans"

          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

          xmlns:context="http://www.springframework.org/schema/context"

          xsi:schemaLocation="

   http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd

   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

       <context:component-scan base-package="example.jersey.spring"/>

   </beans>

This configuration directs Spring to use autowiring with Spring-based annotations and to scan for Spring-based resources in the Java package example.spring.jersey. Autowiring is a feature in Spring that allows it to introspect bean classes for dependencies so that you do not have to explicitly specify bean properties or constructor arguments.

Modify the web.xml File: Replace the contents of the web.xml file with the content shown here.

The following code in the updated web.xml file declares the Spring application context configuration, created earlier as a servlet context parameter:

   <context-param>

       <param-name>contextConfigLocation</param-name>

       <param-value>classpath:applicationContext.xml</param-value>

   </context-param>

The updated content also declares two listeners. The first configures Spring and the second configures Spring for use with the request scope for Spring beans.

   <listener>

          <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>

   </listener>

   <listener>

          <listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>

   </listener>

Then, the file declares the Jersey Spring servlet, which supports the Jersey integration with Spring.

   <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>

   </servlet>

Modify the Root Resource Class: Modify the MyResource.java file in the src/main/java/example/jersey/spring directory with the following content:

   package example.jersey.spring;

 

   import javax.ws.rs.GET;

   import javax.ws.rs.Path;

   import javax.ws.rs.Produces;

   import org.springframework.context.annotation.Scope;

   import org.springframework.stereotype.Component;

 

   // The Java class will be hosted at the URI path "/myresource"

   @Path("/myresource")

   @Component

   @Scope("request")

 

   public class MyResource {

 

       // The Java method will process HTTP GET requests

       @GET

       // The Java method will produce content identified by the MIME Media

       // type "text/plain"

       @Produces("text/plain")

       public String getIt() {

           return "Hi there!";

       }

   }

The @Component annotation declares that the class is a Spring bean class. The @Scope("request") annotation declares that instances of this class will be instantiated within the scope of the HTTP request. This highlights a difference between the default scopes for JAX-RS or Jersey and Spring. The default scope for JAX-RS is per request. By comparison, the default scope for Spring is a singleton, that is, one instance per web application. See Supported Scopes for more information about the scopes that Jersey supports.

The MyResource root resource class is functionally equivalent to the root resource class that you originally created, but it's now Spring-enabled.

Verify that the Spring-enabled web application deploys and executes by entering the following commands in a command line:

   mvn clean install

   asadmin deploy --force=true target/example-spring-jersey.war

   curl -v http://localhost:8080/example-spring-jersey/webresources/myresource

After the Spring-enabled web application is successfully deployed, you should see output similar to the following in the server.log (<GF_install_dir>/glassfish/domains/domain1/logs/server.txt):

   [PWC1412: WebModule[/example-spring-jersey] ServletContext.log():Initializing Spring root WebApplicationContext|#]

   [INFO| Root WebApplicationContext: initialization started|]

   [INFO| Refreshing org.springframework.web.context.support.XmlWebApplicationContext@53ecec: display name [Root WebApplicationContext]; startup date [Mon Apr 06 14:37:02 PDT 2009]; root of context hierarchy|#]

   [INFO| Loading XML bean definitions from class path resource [applicationContext.xml]|#]

   [INFO| Bean factory for application context [org.springframework.web.context.support.XmlWebApplicationContext@53ecec]: org.springframework.beans.factory.support.DefaultListableBeanFactory@c0267a|#]

   [INFO| Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@c0267a: defining beans [myResource,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor]; root of factory hierarchy|#]

   [INFO| Root WebApplicationContext: initialization completed in 891 ms|#]

   [INFO| Loading application example-spring-jersey at /example-spring-jersey|#]

   [INFO| Deployment of example-spring-jersey done is 4500 ms|#]

   [INFO| Registering Spring bean, myResource, of type example.jersey.spring.MyResource as a root resource class|#]

Notice the final line that begins "Registering Spring bean". This is output from Jersey. Jersey knows that the class MyResource is a root resource class and also a Spring bean class. No Jersey-specific configuration was required to register root resource classes, as was the case in the web.xml for the original version of the web application.

Because Spring is used to register Spring beans, in this case using autowiring, Jersey leverages Spring to perform registration rather that requiring duplicate registration. It is possible to intermix Spring-managed and Jersey-managed root resource classes by using Jersey's registration mechanism. It does not matter if both Spring and Jersey find the same class -- only one reference to the class will be managed appropriately.

Supported Scopes

Jersey supports the following Spring scopes:

·    Request. Scopes a single Spring bean definition to the lifecycle of a single HTTP request, that is, each HTTP request has its own instance of a Spring bean created from a single Spring bean definition. This scope requires that you declare the Spring RequestContextListener servlet context in the web.xml file for the web application.

·    Singleton. Scopes a single Spring bean definition to a single object instance per web application.

·    Prototype. Scopes a single Spring bean definition to multiple object instances. A new Spring bean instance is created for each request for that specific bean.

You can inject Jersey artifacts into fields of Spring bean instances according to the scoping rules. If the scope is prototype, then the scoping rules for request apply. If Jersey does not recognize the scope, then it assumes a scope of singleton for the purpose of injection.

For example, you can modify the MyResource class in the Spring-enabled Web application to include an @QueryParam for injection. Here is what the modified class looks like:

   package example.jersey.spring;

 

   import javax.ws.rs.GET;

   import javax.ws.rs.Path;

   import javax.ws.rs.Produces;

   import javax.ws.rs.QueryParam;

   import org.springframework.context.annotation.Scope;

   import org.springframework.stereotype.Component;

 

   // The Java class will be hosted at the URI path "/myresource"

   @Path("/myresource")

   @Component

   @Scope("request")

   public class MyResource {

       @QueryParam("x") String x;

 

       // The Java method will process HTTP GET requests

       @GET

       // The Java method will produce content identified by the MIME Media

       // type "text/plain"

       @Produces("text/plain")

       public String getIt() {

           return "Hi there! " + x;

       }

   }

In response, Jersey should inject the information into the Spring bean in request scope, that is, per request. To test that, you can redeploy and execute the updated application by entering the following commands in a command line window:

   mvn clean install

   asadmin deploy --force=true target/example-spring-jersey.war

   curl -v http://localhost:8080/example-spring-jersey/webresources/myresource?x=curl

The application should return "Hi there! curl" in the output. If it does, this verifies that Jersey can correctly inject information into the Spring bean per request.

Summary

This tip showed you how to use some of Jersey's Spring-related features. But there are other useful elements to Jersey's support for Spring. Some of the these are:

·    You can take advantage of the JAX-RS support for hierarchical URI path matching to further match a URI path that was not already matched by a root resource. This means that you can include a subresource locator method in a resource to return an instance of a newly created Spring bean class. You use the Jersey ResourceContext class to obtain the instance.

·    You can inject Spring beans into JAX-RS-based methods. You do this with the Jersey @Inject annotation.

·    You can use Jersey Spring-based Aspect-Oriented Programming (AOP).

·    You can have Spring instantiate a resource class, but have Jersey manage the resource class's lifecycle.

Further Reading

For more information on Jersey and Spring, see the following resources:

·    Jersey Project

·    Getting Started With Jersey

·    Jersey-Spring 1.0.2 API Overview

·    Jersey-Spring Container Servlet Package

·    ResourceContext Interface

·    @Inject Annotation

About the Author

Paul Sandoz is the co-spec lead and implementation lead for JSR 311: Java API for RESTful Web Services. He has participated in the W3C, ISO, and ITU-T standards organizations and contributed various performance-related technologies and improvements to the GlassFish web services stack, particularly in standardization, implementation, integration, and interoperability of Fast Infoset.


2009 JavaOne Conference, June 2-5, San Francisco ** Register Now**

Stay on top of everything new and different, both inside and around Java technology. Register by April 22, 2009, and save

 

分享到:
评论

相关推荐

    jersey-spring-hk2:泽西岛SpringHK2示例

    泽西岛SpringHK2集成示例 基于Stackoverflow问题, ###跑步 (这些步骤需要Maven。如果没有Maven,则可以将其部署到任何Servlet容器... 无论如何,您决定运行它,输出应该是“ HK2 Message and Spring Message”。

    jersey 1.9 框架源码

    4. **依赖注入**:Jersey 1.9支持CDI(Contexts and Dependency Injection)进行依赖注入,这使得服务类可以方便地获得所需的服务实例,简化了代码。 5. **MVC模型**:虽然RESTful服务不强求MVC模式,但Jersey可以...

    Jersey2的例子

    5. **Filters and Interceptors**: 过滤器和拦截器可以全局或局部地处理请求和响应,例如日志记录、认证、权限控制等。 **三、实例化 Jersey2 应用** 在 `JerseyDemo` 示例中,首先会有一个启动类,通过 `javax.ws...

    spring-boot-reference.pdf

    27.3. JAX-RS and Jersey 27.4. Embedded Servlet Container Support 27.4.1. Servlets, Filters, and listeners Registering Servlets, Filters, and Listeners as Spring Beans 27.4.2. Servlet Context ...

    完整jersey包和jackson-all-1.9.2.jar

    4. **依赖注入**:Jersey支持CDI(Contexts and Dependency Injection),允许开发者通过依赖注入管理服务的生命周期和依赖关系。 5. **扩展性**:Jersey的模块化设计使得它可以与其他框架(如Spring)集成,提供更...

    springBootPrimefaces:演示使用 spring-boot 和 spring security primefaces with push notification and jersey

    在本文中,我们将深入探讨如何将Spring Boot、Spring Security、PrimeFaces以及Push Notification和Jersey集成,以构建一个高效、安全且功能丰富的Web应用程序。Spring Boot简化了Spring框架的配置和初始化过程,而...

    Jersey简明手册

    - **配置Jersey**:在`web.xml`中添加Spring的初始化参数,使Jersey能够找到Spring上下文。 例如,`ApplicationContext.xml`: ```xml &lt;beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi=...

    jersey

    2. **依赖注入**:Jersey 支持 CDI(Contexts and Dependency Injection),允许开发者通过注解来注入依赖,简化组件管理。 3. **过滤器和拦截器**:Jersey 允许使用 `ContainerRequestFilter` 和 `...

    Spring boot 中文.pdf

    - **Application events and listeners**:Spring Boot 支持事件监听器机制,可以监听应用程序启动、停止等事件。 - **Web 环境**:如何配置 Web 环境下的特定选项。 - **访问应用程序参数**:如何从命令行传递...

    jersey-example

    - **依赖注入**:如果项目使用了 CDI(Contexts and Dependency Injection),那么会有相应的配置文件和类来管理对象实例。 - **测试类**:使用 `JerseyTest` 或其他测试框架,编写单元测试或集成测试,验证 REST ...

    Spring mvc 接收json对象

    与Jersey等其他RESTful框架相比,Spring MVC在处理JSON时可能显得较为繁琐,需要更多的注解和配置。不过,Spring生态系统强大,能提供更全面的解决方案,比如支持多种视图技术、AOP、事务管理等。 总的来说,...

    Java在Web开发中的应用.zip

    9. **RESTful API设计**: REST(Representational State Transfer)是一种网络应用设计风格,Java的Jersey和Spring MVC都支持创建RESTful服务,便于构建可扩展、松耦合的Web应用。 10. **Web安全**: 在Java Web开发...

    SpringBoot简单搭建教程

    - **spring-boot-starter-jersey**:提供了Apache Jersey的支持,用于构建RESTful Web服务。 - **spring-boot-starter-jdbc**:用于数据库连接池的配置,基于Tomcat JDBC实现。 2. **自动配置**:SpringBoot通过`...

    企业内部通讯软件

    Java的Jersey、Spring MVC等库可以帮助开发者构建RESTful服务。 8. **测试与监控**:JUnit和Mockito等工具用于单元测试,而像JMX(Java Management Extensions)和Spring Actuator则可实现应用的监控和管理。 9. *...

    对WebService的系统研究, 七种方式实现!

    7. **Jersey**:Jersey是Sun Microsystems发起的开源项目,也是JAX-RS的参考实现。它可以轻松地在任何Servlet容器中部署REST服务,并提供了丰富的客户端API,方便服务调用。 在实现WebService的过程中,开发者需要...

    用Java写的银行系统

    Java的Jersey或Spring Boot可以方便地实现RESTful服务。 7. **异常处理**:在银行系统中,良好的异常处理机制是必不可少的。Java的异常处理机制(try-catch-finally、throw和throws关键字)有助于捕获和处理程序...

    79套JAVA项目毕业设计

    4. **RESTful API**:利用Java的Jersey或Spring Boot的@RestController注解构建REST服务,提供JSON格式的数据交换,用于前后端分离的系统。 5. **移动应用**:部分项目可能涉及Android开发,使用Java语言和Android ...

    10_java网站_java开发_Java使用_java_web_

    Java的Jersey和Spring Boot框架都提供了实现RESTful服务的支持。 9. **前端技术**:虽然Java主要处理后端逻辑,但与前端交互必不可少。常见的前端技术有HTML、CSS、JavaScript,以及现代化的库和框架如Bootstrap、...

    深入分析Java Web技术内幕

    Java Web中的Jersey和Spring Boot等框架支持创建RESTful API,使得服务更加简洁、可扩展。 最后,安全是任何Web应用都必须考虑的问题。Java Web提供了多种安全机制,如SSL/TLS加密、Spring Security框架等,用于...

    JavaWeb

    JavaWeb应用可以使用Jersey、Spring Boot等框架实现RESTful API。 10. **Web安全**: 包括认证(Authentication)、授权(Authorization)、加密(Cryptography)等,如HTTPS、Spring Security、CSRF防护、XSS防护...

Global site tag (gtag.js) - Google Analytics