SlideShare uma empresa Scribd logo
1 de 35
Baixar para ler offline
Building RESTful
applications with
   Spring MVC

     Craig Walls
Who Am I?
                       Java, Spring, and OSGi fanatic
              Principal Consultant with Improving
                                                       Author
                                             XDoclet in Action (Manning)

                                              Spring in Action (Manning)

                                       Modular Java (Pragmatic Bookshelf)




 E-mail: craig@habuma.com Blog: http://www.springinaction.com   Twitter: @habuma Slides: http://www.slideshare.net/habuma
What REST is NOT!!!



                 Web Services
                  with URLs




      E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
It’s about Resources

                                        Things, not actions


                                  Requests, not demands


                                  Resources, not services


                                 Transfer of state, not RPC

      E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
The Pillars of REST

        Resources

       URIs/URLs

     HTTP Methods

     Representations




       E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
The Pillars of REST

                   Resources
    Produced as model data in Spring MVC Controllers


                  URIs/URLs
      Supported in handler methods by @PathParam


               HTTP Methods
 @RequestMapping, HiddenHttpMethodFilter, <form:form>


              Representations
              Rendered by view resolvers
      HTML, XML, JSON, RSS, Atom, PDF, Excel, etc.
     Negotiated by ContentNegotiatingViewResolver




                  E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Identifying Resources




      E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Demanding URLs

                       Direct Imperative                                    Resource identifier
                          Command                                             is pushed into
                                                                            a query parameter



http://www.somestore.com/displayProduct?sku=1234


                       Very service-y
                                                                     Not very cacheable or
                                                                     search engine friendly




           E-mail: craig@habuma.com   Blog: http://www.springinaction.com    Twitter: habuma
Resourceful URLs

                              The focus is
                            on the product,                       We’re requesting
                             not the action                       a product’s info



   http://www.somestore.com/product/1234


                   Cacheable                                                This URL also
                                                                         identifies a product
                                                                          (within a context)




        E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Spring MVC overview




     E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
DispatcherServlet

In /WEB-INF/web.xml
<servlet>
 <servlet-name>spitter</servlet-name>
  <servlet-class>
   org.springframework.web.servlet.DispatcherServlet
  </servlet-class>
 <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
  <servlet-name>spitter</servlet-name>
  <url-pattern>/app/*</url-pattern>
</servlet-mapping>




                 E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
ContextLoaderListener
In /WEB-INF/web.xml
<context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>
  /WEB-INF/spitter-security.xml
  classpath:service-context.xml
  classpath:persistence-context.xml
  classpath:dataSource-context.xml
  classpath:setup-context.xml
 </param-value>
</context-param>

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




                   E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
UrlRewriteFilter
In /WEB-INF/web.xml
<filter>
    <filter-name>UrlRewriteFilter</filter-name>
    <filter-class>
        org.tuckey.web.filters.urlrewrite.UrlRewriteFilter
    </filter-class>
</filter>
<filter-mapping>
    <filter-name>UrlRewriteFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

                                                     In /WEB-INF/urlrewrite.xml
                                                     <urlrewrite default-match-type="wildcard">
                                                       <rule>
                      1234
           /pr oduct/                                    <from>/resources/**</from>
                                                         <to>/resources/$1</to>
                         /1234
                                                       </rule>
                     uct
          /ap p/prod                                   <rule>
                                                         <from>/**</from>
                                                         <to>/app/$1</to>
                                                       </rule>
                                                       <outbound-rule>
                                                         <from>/app/**</from>
                                                         <to>/$1</to>
                                                       </outbound-rule>
                                                     </urlrewrite>
                     E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Essential Configuration
Scan for controller (and other) components
     <context:component-scan
              base-package="com.habuma.sample.mvc" />



                             Resolve JSP views
<bean id="viewResolver"
    class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  <property name="prefix" value="/WEB-INF/jsp/"/>
  <property name="suffix" value=".jsp"/>
</bean>




                 Handle annotation-driven request mappings
                                             <mvc:annotation-driven/>



                  E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Use-case-based controllers
                                                                                      VERB!!!
@Controller
public class DisplayProductController {
  @RequestMapping(value="/displayProduct.htm")
  public String showProductBySku(String sku,
      Map<String,Object> model) {
    Product product = // ... lookup product ...
    model.put("product", product);
    return "product";
  }
  // ...
}


        http://host/myApp/displayProduct.htm?sku=1234

            E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Resource-oriented controller
                                                                           Noun
@Controller                                Verb
@RequestMapping("/product")
public class ProductController {
  @RequestMapping(value="/{sku}", method=GET)
  public String showProductBySku(
        @PathVariable String sku,
        Map<String,Object> model) {
    Product product = // ... lookup product ...
    model.put("product", product);
    return "product";
  }
}
              http://host/myApp/product/1234

          E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
HTTP Methods

              GET, DELETE, PUT
                      Idempotent
    Transfers state of resource
                                POST
                Not Idempotent
    Sends data (not nec. state)


     E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
PUT vs. POST

                                      PUT
      Used to transfer state to server
  Useful when the resource’s URL is known
                                     POST
        Used to send data to server
 Useful when the resource’s URL is unknown
     or when transferring partial state

          E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Handling DELETE

@Controller
@RequestMapping("/product")
public class ProductController {

    ...

    @RequestMapping(value="/{sku}", method=DELETE)
    public String deleteProduct(
          @PathVariable String sku) {
      // ... delete product ...
      return "redirect:home";
    }
}

                 http://host/myApp/product/1234
             E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Handling PUT
@Controller
@RequestMapping("/product")
public class ProductController {

    ...

    @RequestMapping(value="/{sku}", method=PUT)
    public String saveProduct(
          @PathVariable String sku,
          Product product) {
      // ... save product ...
      return "redirect:/product/" + sku;
    }
}
                 http://host/myApp/product/1234
             E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Handling POST
@Controller
@RequestMapping("/product")
public class ProductController {

    ...

    @RequestMapping(method=POST)
    public String setPrice(String sku,
                           double price) {
      // ... update price ...
      return "redirect:/product/" + sku;
    }
}
                      http://host/myApp/product
                         FORM DATA: sku=1234
                                    price=5.99
             E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Using PUT/DELETE in forms
 Most browsers only support GET and POST
    Spring’s <form:form> supports all
   <form:form method="DELETE"
       action="http://host/myApp/product/1234">
   ...
   </form:form>


                                                             Hidden method field
   <form method="POST"
       action="http://host/myApp/product/1234">
     <input type="hidden" name="_method"
             value="DELETE">
   ...
   </form>
           E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
HiddenHttpMethodFilter
 <filter>
   <filter-name>httpMethodFilter</filter-name>
   <filter-class>
     org.springframework.web.filter.HiddenHttpMethodFilter
   </filter-class>
 </filter>

 <filter-mapping>
   <filter-name>httpMethodFilter</filter-name>
   <url-pattern>/*</url-pattern>
 </filter-mapping>



                                               HiddenHttpMethodFilter
      POST
                                                                                      DELETE
 _method=DELETE




              E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Data representation


                                      PDF                                     RSS/Atom

                         Spring MVC
                            Views
 JSON



                                                                   Excel

        E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Negotiating Content

          Request



        Content
       Negotiating
         View
        Resolver




      E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Choosing a view

                                 1. Determine the media type
                                     URL path extension/mediaTypes
                                            format parameter
                                              URL path extension/JAF
                                                   HTTP Accept header


                                  2. Find a view resolver that
                                     serves that media type



      E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
ContentNegotiatingViewResolver

 <bean class="org.springframework.web.servlet.view.
                              ContentNegotiatingViewResolver">
   <property name="mediaTypes">
     <map>
       <entry key="htm" value="text/html"/>
       <entry key="json" value="application/json"/>
     </map>
   </property>
   <property name="defaultViews">
     <list>
       <bean class="org.springframework.web.servlet.view.json.
                                    MappingJacksonJsonView" />
     </list>
   </property>
 </bean>

 <bean id="spittles"
       class="com.habuma.spitter.mvc.view.SpittlesAtomView"/>



              E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Spring’s new views
        MappingJacksonJsonView
                  MarshallingView
         AbstractAtomFeedView
            AbstractRssFeedView




      E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
XML Marshalling View


<bean id="oxmMarshaller"
      class="org.springframework.oxm.xstream.XStreamMarshaller" />

<bean id="marshallingHttpMessageConverter"
      class="org.springframework.http.converter.xml.
                                 MarshallingHttpMessageConverter">
  <property name="marshaller" ref="oxmMarshaller" />
  <property name="unmarshaller" ref="oxmMarshaller" />
</bean>




                E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Sample RSS View
 public class SpittlesRssView extends AbstractRssFeedView {

     @Override
     protected List<Item> buildFeedItems(
             Map<String, Object> model,
             HttpServletRequest request,
             HttpServletResponse response) throws Exception {

         @SuppressWarnings("unchecked")
         List<Spittle> spittles = (List<Spittle>) model.get("spittles");
         List<Item> items = new ArrayList<Item>();
         for (Spittle spittle : spittles) {
           Item item = new Item();
           item.setTitle(spittle.getText());
           item.setPubDate(spittle.getWhen());
           item.setAuthor(spittle.getSpitter().getFullName());
           items.add(item);
         }

         return items;
     }
 }


                  E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Sample Atom View
  public class SpittlesAtomView extends AbstractAtomFeedView {

      @Override
      protected List<Entry> buildFeedEntries(
              Map<String, Object> model,
              HttpServletRequest request,
              HttpServletResponse response) throws Exception {

          @SuppressWarnings("unchecked")
          List<Spittle> spittles = (List<Spittle>) model.get("spittles");
          List<Entry> entries = new ArrayList<Entry>();
          for (Spittle spittle : spittles) {
            Entry entry = new Entry();
            entry.setTitle(spittle.getText());
            entry.setCreated(spittle.getWhen());
            entry.setAuthors(asList(spittle.getSpitter().getFullName()));
            entries.add(entry);
          }

          return entries;
      }
  }


                   E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
ETags
   Returns HTTP 304 if content is unmodified
                               if-none-match
                            (MD5 Hash comparison)
                                    Saves bandwidth

<filter>
  <filter-name>etagFilter</filter-name>
  <filter-class>org.springframework.web.filter.ShallowEtagHeaderFilter</filter-class>
</filter>

<filter-mapping>
  <filter-name>etagFilter</filter-name>
  <servlet-name>spitter</servlet-name>
</filter-mapping>




                   E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
RestTemplate
    In Spring context: (or yes, it could just be new’d up in Java)
    <bean id="restTemplate"
          class="org.springframework.web.client.RestTemplate">




In Java:
RestTemplate rest = (RestTemplate) context.getBean("restTemplate");
Map result = rest.getForObject(
        "http://localhost:8080/mugbooks/book/1.json", Map.class);




                    E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Summary



• Spring provides a flexible web MVC
  framework

• Full support for REST as of Spring 3.0
• Can consume REST services via a template


         E-mail: craig@habuma.com   Blog: http://www.springinaction.com   Twitter: habuma
Thank You

Don’t forget the evals!

Mais conteúdo relacionado

Mais procurados

Implicit objects advance Java
Implicit objects advance JavaImplicit objects advance Java
Implicit objects advance JavaDarshit Metaliya
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Michał Orman
 
Jsp & Ajax
Jsp & AjaxJsp & Ajax
Jsp & AjaxAng Chen
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoasZeid Hassan
 
Spring Web Flow. A little flow of happiness.
Spring Web Flow. A little flow of happiness.Spring Web Flow. A little flow of happiness.
Spring Web Flow. A little flow of happiness.Alex Tumanoff
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsCarol McDonald
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 updateJoshua Long
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Foreverstephskardal
 
Spray - Build RESTfull services in scala
Spray - Build RESTfull services in scalaSpray - Build RESTfull services in scala
Spray - Build RESTfull services in scalaSandeep Purohit
 
jQuery and AJAX with Rails
jQuery and AJAX with RailsjQuery and AJAX with Rails
jQuery and AJAX with RailsAlan Hecht
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJoshua Long
 
Spring Web Webflow
Spring Web WebflowSpring Web Webflow
Spring Web WebflowEmprovise
 
JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011Arun Gupta
 
An Introduction to Ruby on Rails
An Introduction to Ruby on RailsAn Introduction to Ruby on Rails
An Introduction to Ruby on RailsJoe Fiorini
 
Jsp (java server page)
Jsp (java server page)Jsp (java server page)
Jsp (java server page)Chitrank Dixit
 
MVC on the server and on the client
MVC on the server and on the clientMVC on the server and on the client
MVC on the server and on the clientSebastiano Armeli
 

Mais procurados (19)

Implicit objects advance Java
Implicit objects advance JavaImplicit objects advance Java
Implicit objects advance Java
 
Java Server Pages
Java Server PagesJava Server Pages
Java Server Pages
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Jsp & Ajax
Jsp & AjaxJsp & Ajax
Jsp & Ajax
 
Rest web service_with_spring_hateoas
Rest web service_with_spring_hateoasRest web service_with_spring_hateoas
Rest web service_with_spring_hateoas
 
Spring Web Flow. A little flow of happiness.
Spring Web Flow. A little flow of happiness.Spring Web Flow. A little flow of happiness.
Spring Web Flow. A little flow of happiness.
 
Rest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.jsRest with Java EE 6 , Security , Backbone.js
Rest with Java EE 6 , Security , Backbone.js
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
the Spring 4 update
the Spring 4 updatethe Spring 4 update
the Spring 4 update
 
jQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends ForeverjQuery and Rails: Best Friends Forever
jQuery and Rails: Best Friends Forever
 
Spray - Build RESTfull services in scala
Spray - Build RESTfull services in scalaSpray - Build RESTfull services in scala
Spray - Build RESTfull services in scala
 
jQuery and AJAX with Rails
jQuery and AJAX with RailsjQuery and AJAX with Rails
jQuery and AJAX with Rails
 
Java Configuration Deep Dive with Spring
Java Configuration Deep Dive with SpringJava Configuration Deep Dive with Spring
Java Configuration Deep Dive with Spring
 
Spring Web Webflow
Spring Web WebflowSpring Web Webflow
Spring Web Webflow
 
JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011JavaServer Faces 2.0 - JavaOne India 2011
JavaServer Faces 2.0 - JavaOne India 2011
 
An Introduction to Ruby on Rails
An Introduction to Ruby on RailsAn Introduction to Ruby on Rails
An Introduction to Ruby on Rails
 
Jsp (java server page)
Jsp (java server page)Jsp (java server page)
Jsp (java server page)
 
MVC on the server and on the client
MVC on the server and on the clientMVC on the server and on the client
MVC on the server and on the client
 

Destaque

What's new in Spring 3?
What's new in Spring 3?What's new in Spring 3?
What's new in Spring 3?Craig Walls
 
Design REST-ful Web Service
Design REST-ful Web ServiceDesign REST-ful Web Service
Design REST-ful Web ServiceKevingo Tsai
 
Designing REST services with Spring MVC
Designing REST services with Spring MVCDesigning REST services with Spring MVC
Designing REST services with Spring MVCSerhii Kartashov
 
k-means Clustering and Custergram with R
k-means Clustering and Custergram with Rk-means Clustering and Custergram with R
k-means Clustering and Custergram with RDr. Volkan OBAN
 
Program_Cluster_Analysis
Program_Cluster_AnalysisProgram_Cluster_Analysis
Program_Cluster_AnalysisSammya Sengupta
 
Modular Java - OSGi
Modular Java - OSGiModular Java - OSGi
Modular Java - OSGiCraig Walls
 
That old Spring magic has me in its SpEL
That old Spring magic has me in its SpELThat old Spring magic has me in its SpEL
That old Spring magic has me in its SpELCraig Walls
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action Alex Movila
 
Spring Framework 4.0 to 4.1
Spring Framework 4.0 to 4.1Spring Framework 4.0 to 4.1
Spring Framework 4.0 to 4.1Sam Brannen
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!Jakub Kubrynski
 
Implantación de Geoportales con soporte técnico profesionalizado en softwar...
Implantación de Geoportales con soporte técnico profesionalizado en softwar...Implantación de Geoportales con soporte técnico profesionalizado en softwar...
Implantación de Geoportales con soporte técnico profesionalizado en softwar...Alberto Apellidos
 
WP-Polls en castellano
WP-Polls en castellanoWP-Polls en castellano
WP-Polls en castellanocarmepla
 

Destaque (20)

What's new in Spring 3?
What's new in Spring 3?What's new in Spring 3?
What's new in Spring 3?
 
SpringMVC
SpringMVCSpringMVC
SpringMVC
 
Design REST-ful Web Service
Design REST-ful Web ServiceDesign REST-ful Web Service
Design REST-ful Web Service
 
Rest with Spring
Rest with SpringRest with Spring
Rest with Spring
 
Designing REST services with Spring MVC
Designing REST services with Spring MVCDesigning REST services with Spring MVC
Designing REST services with Spring MVC
 
k-means Clustering and Custergram with R
k-means Clustering and Custergram with Rk-means Clustering and Custergram with R
k-means Clustering and Custergram with R
 
Program_Cluster_Analysis
Program_Cluster_AnalysisProgram_Cluster_Analysis
Program_Cluster_Analysis
 
Modular Java - OSGi
Modular Java - OSGiModular Java - OSGi
Modular Java - OSGi
 
That old Spring magic has me in its SpEL
That old Spring magic has me in its SpELThat old Spring magic has me in its SpEL
That old Spring magic has me in its SpEL
 
Spring boot
Spring bootSpring boot
Spring boot
 
Boot It Up
Boot It UpBoot It Up
Boot It Up
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring Framework 4.0 to 4.1
Spring Framework 4.0 to 4.1Spring Framework 4.0 to 4.1
Spring Framework 4.0 to 4.1
 
slides Céline Beji
slides Céline Bejislides Céline Beji
slides Céline Beji
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Implantación de Geoportales con soporte técnico profesionalizado en softwar...
Implantación de Geoportales con soporte técnico profesionalizado en softwar...Implantación de Geoportales con soporte técnico profesionalizado en softwar...
Implantación de Geoportales con soporte técnico profesionalizado en softwar...
 
WP-Polls en castellano
WP-Polls en castellanoWP-Polls en castellano
WP-Polls en castellano
 

Semelhante a Spring Mvc Rest

Codeigniter : Custom Routing - Manipulate Uri
Codeigniter : Custom Routing - Manipulate UriCodeigniter : Custom Routing - Manipulate Uri
Codeigniter : Custom Routing - Manipulate UriAbdul Malik Ikhsan
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript FrameworkAll Things Open
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalystsvilen.ivanov
 
Jlook web ui framework
Jlook web ui frameworkJlook web ui framework
Jlook web ui frameworkHongSeong Jeon
 
Angular data binding by Soft Solutions4U
Angular data binding by Soft Solutions4UAngular data binding by Soft Solutions4U
Angular data binding by Soft Solutions4Usharsen
 
Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2A.K.M. Ahsrafuzzaman
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web servicesnbuddharaju
 
XamarinとAWSをつないでみた話
XamarinとAWSをつないでみた話XamarinとAWSをつないでみた話
XamarinとAWSをつないでみた話Takehito Tanabe
 
Make your App Frontend Compatible
Make your App Frontend CompatibleMake your App Frontend Compatible
Make your App Frontend CompatibleOdoo
 
Spca2014 hillier 3rd party_javascript_libraries
Spca2014 hillier 3rd party_javascript_librariesSpca2014 hillier 3rd party_javascript_libraries
Spca2014 hillier 3rd party_javascript_librariesNCCOMMS
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortalJennifer Bourey
 
Sharing Data between controllers in different ways.
Sharing Data between controllers in different ways.Sharing Data between controllers in different ways.
Sharing Data between controllers in different ways.Amar Shukla
 
Different way to share data between controllers in angular js
Different way to share data between controllers in angular jsDifferent way to share data between controllers in angular js
Different way to share data between controllers in angular jscodeandyou forums
 
Rest experience-report
Rest experience-reportRest experience-report
Rest experience-reportJim Barritt
 

Semelhante a Spring Mvc Rest (20)

Codeigniter : Custom Routing - Manipulate Uri
Codeigniter : Custom Routing - Manipulate UriCodeigniter : Custom Routing - Manipulate Uri
Codeigniter : Custom Routing - Manipulate Uri
 
Choosing a Javascript Framework
Choosing a Javascript FrameworkChoosing a Javascript Framework
Choosing a Javascript Framework
 
Doing REST Right
Doing REST RightDoing REST Right
Doing REST Right
 
Web applications with Catalyst
Web applications with CatalystWeb applications with Catalyst
Web applications with Catalyst
 
Basics of AngularJS
Basics of AngularJSBasics of AngularJS
Basics of AngularJS
 
Jlook web ui framework
Jlook web ui frameworkJlook web ui framework
Jlook web ui framework
 
The Rails Way
The Rails WayThe Rails Way
The Rails Way
 
Angular data binding by Soft Solutions4U
Angular data binding by Soft Solutions4UAngular data binding by Soft Solutions4U
Angular data binding by Soft Solutions4U
 
Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2Ride on the Fast Track of Web with Ruby on Rails- Part 2
Ride on the Fast Track of Web with Ruby on Rails- Part 2
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
Rest
RestRest
Rest
 
XamarinとAWSをつないでみた話
XamarinとAWSをつないでみた話XamarinとAWSをつないでみた話
XamarinとAWSをつないでみた話
 
Make your App Frontend Compatible
Make your App Frontend CompatibleMake your App Frontend Compatible
Make your App Frontend Compatible
 
Spca2014 hillier 3rd party_javascript_libraries
Spca2014 hillier 3rd party_javascript_librariesSpca2014 hillier 3rd party_javascript_libraries
Spca2014 hillier 3rd party_javascript_libraries
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortal
 
Camel as a_glue
Camel as a_glueCamel as a_glue
Camel as a_glue
 
AngularJS Basic Training
AngularJS Basic TrainingAngularJS Basic Training
AngularJS Basic Training
 
Sharing Data between controllers in different ways.
Sharing Data between controllers in different ways.Sharing Data between controllers in different ways.
Sharing Data between controllers in different ways.
 
Different way to share data between controllers in angular js
Different way to share data between controllers in angular jsDifferent way to share data between controllers in angular js
Different way to share data between controllers in angular js
 
Rest experience-report
Rest experience-reportRest experience-report
Rest experience-report
 

Spring Mvc Rest

  • 1. Building RESTful applications with Spring MVC Craig Walls
  • 2. Who Am I? Java, Spring, and OSGi fanatic Principal Consultant with Improving Author XDoclet in Action (Manning) Spring in Action (Manning) Modular Java (Pragmatic Bookshelf) E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: @habuma Slides: http://www.slideshare.net/habuma
  • 3. What REST is NOT!!! Web Services with URLs E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 4. It’s about Resources Things, not actions Requests, not demands Resources, not services Transfer of state, not RPC E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 5. The Pillars of REST Resources URIs/URLs HTTP Methods Representations E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 6. The Pillars of REST Resources Produced as model data in Spring MVC Controllers URIs/URLs Supported in handler methods by @PathParam HTTP Methods @RequestMapping, HiddenHttpMethodFilter, <form:form> Representations Rendered by view resolvers HTML, XML, JSON, RSS, Atom, PDF, Excel, etc. Negotiated by ContentNegotiatingViewResolver E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 7. Identifying Resources E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 8. Demanding URLs Direct Imperative Resource identifier Command is pushed into a query parameter http://www.somestore.com/displayProduct?sku=1234 Very service-y Not very cacheable or search engine friendly E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 9. Resourceful URLs The focus is on the product, We’re requesting not the action a product’s info http://www.somestore.com/product/1234 Cacheable This URL also identifies a product (within a context) E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 10. Spring MVC overview E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 11. DispatcherServlet In /WEB-INF/web.xml <servlet> <servlet-name>spitter</servlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>spitter</servlet-name> <url-pattern>/app/*</url-pattern> </servlet-mapping> E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 12. ContextLoaderListener In /WEB-INF/web.xml <context-param> <param-name>contextConfigLocation</param-name> <param-value> /WEB-INF/spitter-security.xml classpath:service-context.xml classpath:persistence-context.xml classpath:dataSource-context.xml classpath:setup-context.xml </param-value> </context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener </listener-class> </listener> E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 13. UrlRewriteFilter In /WEB-INF/web.xml <filter> <filter-name>UrlRewriteFilter</filter-name> <filter-class> org.tuckey.web.filters.urlrewrite.UrlRewriteFilter </filter-class> </filter> <filter-mapping> <filter-name>UrlRewriteFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> In /WEB-INF/urlrewrite.xml <urlrewrite default-match-type="wildcard"> <rule> 1234 /pr oduct/ <from>/resources/**</from> <to>/resources/$1</to> /1234 </rule> uct /ap p/prod <rule> <from>/**</from> <to>/app/$1</to> </rule> <outbound-rule> <from>/app/**</from> <to>/$1</to> </outbound-rule> </urlrewrite> E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 14. Essential Configuration Scan for controller (and other) components <context:component-scan base-package="com.habuma.sample.mvc" /> Resolve JSP views <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> Handle annotation-driven request mappings <mvc:annotation-driven/> E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 15. Use-case-based controllers VERB!!! @Controller public class DisplayProductController { @RequestMapping(value="/displayProduct.htm") public String showProductBySku(String sku, Map<String,Object> model) { Product product = // ... lookup product ... model.put("product", product); return "product"; } // ... } http://host/myApp/displayProduct.htm?sku=1234 E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 16. Resource-oriented controller Noun @Controller Verb @RequestMapping("/product") public class ProductController { @RequestMapping(value="/{sku}", method=GET) public String showProductBySku( @PathVariable String sku, Map<String,Object> model) { Product product = // ... lookup product ... model.put("product", product); return "product"; } } http://host/myApp/product/1234 E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 17. HTTP Methods GET, DELETE, PUT Idempotent Transfers state of resource POST Not Idempotent Sends data (not nec. state) E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 18. PUT vs. POST PUT Used to transfer state to server Useful when the resource’s URL is known POST Used to send data to server Useful when the resource’s URL is unknown or when transferring partial state E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 19. Handling DELETE @Controller @RequestMapping("/product") public class ProductController { ... @RequestMapping(value="/{sku}", method=DELETE) public String deleteProduct( @PathVariable String sku) { // ... delete product ... return "redirect:home"; } } http://host/myApp/product/1234 E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 20. Handling PUT @Controller @RequestMapping("/product") public class ProductController { ... @RequestMapping(value="/{sku}", method=PUT) public String saveProduct( @PathVariable String sku, Product product) { // ... save product ... return "redirect:/product/" + sku; } } http://host/myApp/product/1234 E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 21. Handling POST @Controller @RequestMapping("/product") public class ProductController { ... @RequestMapping(method=POST) public String setPrice(String sku, double price) { // ... update price ... return "redirect:/product/" + sku; } } http://host/myApp/product FORM DATA: sku=1234 price=5.99 E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 22. Using PUT/DELETE in forms Most browsers only support GET and POST Spring’s <form:form> supports all <form:form method="DELETE" action="http://host/myApp/product/1234"> ... </form:form> Hidden method field <form method="POST" action="http://host/myApp/product/1234"> <input type="hidden" name="_method" value="DELETE"> ... </form> E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 23. HiddenHttpMethodFilter <filter> <filter-name>httpMethodFilter</filter-name> <filter-class> org.springframework.web.filter.HiddenHttpMethodFilter </filter-class> </filter> <filter-mapping> <filter-name>httpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> HiddenHttpMethodFilter POST DELETE _method=DELETE E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 24. Data representation PDF RSS/Atom Spring MVC Views JSON Excel E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 25. Negotiating Content Request Content Negotiating View Resolver E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 26. Choosing a view 1. Determine the media type URL path extension/mediaTypes format parameter URL path extension/JAF HTTP Accept header 2. Find a view resolver that serves that media type E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 27. ContentNegotiatingViewResolver <bean class="org.springframework.web.servlet.view. ContentNegotiatingViewResolver"> <property name="mediaTypes"> <map> <entry key="htm" value="text/html"/> <entry key="json" value="application/json"/> </map> </property> <property name="defaultViews"> <list> <bean class="org.springframework.web.servlet.view.json. MappingJacksonJsonView" /> </list> </property> </bean> <bean id="spittles" class="com.habuma.spitter.mvc.view.SpittlesAtomView"/> E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 28. Spring’s new views MappingJacksonJsonView MarshallingView AbstractAtomFeedView AbstractRssFeedView E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 29. XML Marshalling View <bean id="oxmMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller" /> <bean id="marshallingHttpMessageConverter" class="org.springframework.http.converter.xml. MarshallingHttpMessageConverter"> <property name="marshaller" ref="oxmMarshaller" /> <property name="unmarshaller" ref="oxmMarshaller" /> </bean> E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 30. Sample RSS View public class SpittlesRssView extends AbstractRssFeedView { @Override protected List<Item> buildFeedItems( Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { @SuppressWarnings("unchecked") List<Spittle> spittles = (List<Spittle>) model.get("spittles"); List<Item> items = new ArrayList<Item>(); for (Spittle spittle : spittles) { Item item = new Item(); item.setTitle(spittle.getText()); item.setPubDate(spittle.getWhen()); item.setAuthor(spittle.getSpitter().getFullName()); items.add(item); } return items; } } E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 31. Sample Atom View public class SpittlesAtomView extends AbstractAtomFeedView { @Override protected List<Entry> buildFeedEntries( Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception { @SuppressWarnings("unchecked") List<Spittle> spittles = (List<Spittle>) model.get("spittles"); List<Entry> entries = new ArrayList<Entry>(); for (Spittle spittle : spittles) { Entry entry = new Entry(); entry.setTitle(spittle.getText()); entry.setCreated(spittle.getWhen()); entry.setAuthors(asList(spittle.getSpitter().getFullName())); entries.add(entry); } return entries; } } E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 32. ETags Returns HTTP 304 if content is unmodified if-none-match (MD5 Hash comparison) Saves bandwidth <filter> <filter-name>etagFilter</filter-name> <filter-class>org.springframework.web.filter.ShallowEtagHeaderFilter</filter-class> </filter> <filter-mapping> <filter-name>etagFilter</filter-name> <servlet-name>spitter</servlet-name> </filter-mapping> E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 33. RestTemplate In Spring context: (or yes, it could just be new’d up in Java) <bean id="restTemplate" class="org.springframework.web.client.RestTemplate"> In Java: RestTemplate rest = (RestTemplate) context.getBean("restTemplate"); Map result = rest.getForObject( "http://localhost:8080/mugbooks/book/1.json", Map.class); E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma
  • 34. Summary • Spring provides a flexible web MVC framework • Full support for REST as of Spring 3.0 • Can consume REST services via a template E-mail: craig@habuma.com Blog: http://www.springinaction.com Twitter: habuma