Labels

.NET Job Questions About Java Absract class Abstract class Abstract Class and Interface Aggregation ajax aop apache ofbiz Apache ofbiz tutrial Association authentication autocad basics batch Binary Tree bootstrap loader in java build Builder design pattern C++ Job Questions caching CallableStatement in java certifications Chain of responsibility Design pattern charts check parentheses in a string Classes classloader in java classloading concept code quality collage level java program Composition concurrency Concurrency Tutorial Converting InputStream to String Core Java core java concept core java interview questions Core Java Interview Questions Core Java Questions core java tutorial CyclicBarrier in Java data structures database Database Job Questions datetime in c# DB Db2 SQL Replication deserialization in java Design Patterns designpatterns Downloads dtd Eclipse ejb example/sample code exception handling in core java file handling injava File I/O vs Memory-Mapped Filter first program in spring flex Garbage Collection Generics concept in java grails groovy and grails Guice Heap hibernate Hibernate Interview Questions how-to IBM DB2 IBM DB2 Tutorial ide immutable Interceptor Interface interview Interview Questions for Advanced JAVA investment bank j2ee java JAVA Code Examples Java 7 java changes java class loading JAVA Classes and Objects Java Classloader concept Java classloading concept java cloning concept java collection Java collection interview questions Java Collections java concurrency Java CountDownLatch java definiton Java design pattern Java EE 5 Java EE 6 Java Exceptions Java file Java Garbage Collection Java generics Java Glossary java hot concept java immutable concept Java Interface Java interview Question java interview question 2012 java interview question answer Java Interview Questions Java Interview Questions and Answers java interview topic java investment bank Java Job Questions java multithreading java multithreading concept java new features Java Packages java proxy object java questions Java Serialization Java serialization concept java serialization interview question java session concept java string Java Swings Questions java synchronization java threading Java Threads Questions java tutorial java util; java collections; java questions java volatile java volatile interview question Java Wrapper Classes java.java1.5 java.lang.ClassCastException JavaNotes javascript JAX-WS jdbc JDBC JDBC Database connection jdk 1.5 features JDK 1.5 new features Concurrent HashMap JMS interview question JMS tutorial job JSESSIONID concept JSESSIONID interview Question JSF jsp JSP Interview Question JSP taglib JSTL with JSP Junit Junit Concept Junit interview question.Best Practices to write JUnit test cases in Java JVM Linux - Unix tutorial Marker Interfaces MD5 encryption and decryption messaging MNC software java interview question musix NCR java interview question Networking Job Questions news Object Serialization Objects ojdbc14.jar OOP Oracle Oracle SQL Query for two timestamp difference orm own JavaScript function call in Apache ofbiz Packages Palm Apps patterns pdf persistence Portal Portlet Spring Integration Prime number test in java programs Rails Reboot remote computers REST Ruby Sample application schema SCJP security Senior java developer interviews servlet3 servlets session tracking singleton design pattern Spring Spring 2.5 Framework spring ebook Spring framework concept spring MVC spring pdf Spring Security Spring Security interview questions SQL SQL performance SQL Query to create xml file Sql Query tuning ssis and ssrs StAX and XML string concept string immutable string in java strings struts Struts2 Struts2 integration synchronization works in java Technical Interview testing tips Tomcat top Tutorial Volatile in deep Volatile working concept web Web Developer Job Questions web services weblogic Weblogic Application Server websphere what is JSESSIONID xml XML parsing in java XML with Java xslt


Wednesday, 3 July 2013

Integrate Jersey and Spring

This post describes a way to integrate spring with Jersey resource classes. It expands on the earlier sample Restful Web Services With Jersey API. The code here has been implemented on following configuration
  • Tomcat 7
  • Java 7
  • Spring 3.1.1
  • Jersey 1.12
To show the use of Spring, I added MyService class which will be injected into RestWS class. For this example, we start out with the sample code in Restful Web Services With Jersey API and make the following changes...
  1. Web.xml: In the Web Deployment Descriptor, the Jersey Servlet has to be modified to use com.sun.jersey.spi.spring.container.servlet.SpringServlet instead of com.sun.jersey.spi.container.servlet.ServletContainer
    <?xml version="1.0" encoding="UTF-8"?>
    <web-app 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 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
        id="WebApp_ID" version="3.0">
        <display-name>JerseyRest</display-name>
        <welcome-file-list>
            <welcome-file>index.html</welcome-file>
        </welcome-file-list>
        <context-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext.xml</param-value>
        </context-param>
        <listener>
            <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
        </listener>

        <servlet>
            <servlet-name>Jersey Web Application</servlet-name>
            <servlet-class>com.sun.jersey.spi.spring.container.servlet.SpringServlet</servlet-class>
            <init-param>
                <param-name>com.sun.jersey.config.property.packages</param-name>
                <param-value>com.blogspot.aoj.restws</param-value>
            </init-param>

            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>Jersey Web Application</servlet-name>
            <url-pattern>/rest/*</url-pattern>
        </servlet-mapping>
    </web-app>
  2. RestWS: There is not much change in the RestWS.java file, other than adding the field MyService which will be injected by spring. The following sample code shows @Autowire, which works with @Component annotation for spring to inject dependencies. However, you can implement the same example without Autowiring by simply creating a bean in spring context file.
    /**
     * @author Abhi Vuyyuru
     */

    package com.blogspot.aoj.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;

    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;

    import com.blogspot.aoj.service.MyService;

    @Path("/restws")
    @Component
    public class RestWS {
       
        @Autowired
        private MyService myService;

        @GET
        @Path("concat/i/{i}/j/{j}")
        @Produces(MediaType.TEXT_HTML)
        public String concat(@PathParam("i") String i, @PathParam("j") String j) {
            return myService.concat(i, j);
        }

        public MyService getMyService() {
            return myService;
        }

        public void setMyService(MyService myService) {
            this.myService = myService;
        }

    }
  3. /WEB-INF/applicationContext.xml: The following code shows code for Autowire and otherwise. Simply comment the unused version

    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
        xmlns:context="http://www.springframework.org/schema/context"
        xsi:schemaLocation="
                http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd
                http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
       
        <bean id="myService" class="com.blogspot.aoj.service.MyService" />
        <bean id="restWS" class="com.blogspot.aoj.restws.RestWS">
            <property name="myService" ref="myService"></property>
        </bean>
        <!-- <context:component-scan base-package="com.blogspot.aoj.restws" /> -->
    </beans>

  4. Client will be the same as used in the previous code sample Restful Web Services With Jersey API
  5. The Jersey Spring Servlet is part of the jersey-spring.jar file which can be downloaded from the Jersey download site
  6. Finally, the following is the ant build file that I used.
    <project name="jerseyRest" default="compile" basedir=".">
        <property file="build.properties" />
        <property file="${user.home}/build.properties" />
        <property name="app.name" value="jerseyRest" />
        <property name="app.path" value="/${app.name}" />
        <property name="app.version" value="0.1-dev" />
        <property name="build.home" value="${basedir}/build" />
        <property name="catalina.home" value="c:/tomcat7" />
        <property name="dist.home" value="${basedir}/dist" />
        <property name="docs.home" value="${basedir}/docs" />
        <property name="manager.url" value="http://localhost:8080/manager/text" />
        <property name="manager.username" value="tomcat" />
        <property name="manager.password" value="tomcat" />
        <property name="src.home" value="${basedir}/src" />
        <property name="web.home" value="${basedir}/WebContent" />
        <path id="compile.classpath">
            <fileset dir="${catalina.home}/bin">
                <include name="*.jar" />
            </fileset>
            <pathelement location="${catalina.home}/lib" />
            <fileset dir="${catalina.home}/lib">
                <include name="*.jar" />
            </fileset>
            <fileset dir="${web.home}/WEB-INF/lib">
                <include name="*.jar" />
            </fileset>

        </path>
        <taskdef resource="org/apache/catalina/ant/catalina.tasks" classpathref="compile.classpath" />
        <taskdef name="deploy" classname="org.apache.catalina.ant.DeployTask" classpathref="compile.classpath" />
        <taskdef name="list" classname="org.apache.catalina.ant.ListTask" classpathref="compile.classpath" />
        <taskdef name="reload" classname="org.apache.catalina.ant.ReloadTask" classpathref="compile.classpath" />
        <taskdef name="findleaks" classname="org.apache.catalina.ant.FindLeaksTask" classpathref="compile.classpath" />
        <taskdef name="resources" classname="org.apache.catalina.ant.ResourcesTask" classpathref="compile.classpath" />
        <taskdef name="start" classname="org.apache.catalina.ant.StartTask" classpathref="compile.classpath" />
        <taskdef name="stop" classname="org.apache.catalina.ant.StopTask" classpathref="compile.classpath" />
        <taskdef name="undeploy" classname="org.apache.catalina.ant.UndeployTask" classpathref="compile.classpath" />

        <property name="compile.debug" value="true" />
        <property name="compile.deprecation" value="false" />
        <property name="compile.optimize" value="true" />


        <target name="all" depends="clean,compile" description="Clean build and dist directories, then compile" />

        <target name="clean" description="Delete old build and dist directories">
            <delete dir="${build.home}" />
            <delete dir="${dist.home}" />
        </target>


        <target name="compile" depends="prepare" description="Compile Java sources">
            <mkdir dir="${build.home}/WEB-INF/classes" />
            <javac srcdir="${src.home}" destdir="${build.home}/WEB-INF/classes" debug="${compile.debug}" deprecation="${compile.deprecation}" optimize="${compile.optimize}">
                <classpath refid="compile.classpath" />
            </javac>
            <copy todir="${build.home}/WEB-INF/classes">
                <fileset dir="${src.home}" excludes="**/*.java" />
            </copy>
        </target>

        <target name="dist" depends="compile,javadoc" description="Create binary distribution">
            <mkdir dir="${dist.home}/docs" />
            <copy todir="${dist.home}/docs">
                <fileset dir="${docs.home}" />
            </copy>
            <jar jarfile="${dist.home}/${app.name}-${app.version}.war" basedir="${build.home}" />
        </target>


        <target name="install" depends="compile" description="Install application to servlet container">
            <deploy url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}" localWar="file://${build.home}" />
        </target>


        <target name="javadoc" depends="compile" description="Create Javadoc API documentation">
            <mkdir dir="${dist.home}/docs/api" />
            <javadoc sourcepath="${src.home}" destdir="${dist.home}/docs/api" packagenames="*">
                <classpath refid="compile.classpath" />
            </javadoc>
        </target>



        <target name="list" description="List installed applications on servlet container">
            <list url="${manager.url}" username="${manager.username}" password="${manager.password}" />
        </target>


        <target name="prepare">
            <mkdir dir="${build.home}" />
            <mkdir dir="${build.home}/WEB-INF" />
            <mkdir dir="${build.home}/WEB-INF/classes" />
            <copy todir="${build.home}">
                <fileset dir="${web.home}" />
            </copy>
            <mkdir dir="${build.home}/WEB-INF/lib" />
        </target>

        <target name="reload" depends="compile" description="Reload application on servlet container">
            <reload url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}" />
        </target>
        <target name="remove" description="Remove application on servlet container">
            <undeploy url="${manager.url}" username="${manager.username}" password="${manager.password}" path="${app.path}" />
        </target>
    </project>

No comments:

Post a Comment

LinkWithin

Related Posts Plugin for WordPress, Blogger...