SlideShare a Scribd company logo
Restful applications using Spring MVC




Kamal Govindraj
TenXperts Technologies
About Me
   Programming for 13 Years
   Architect @ TenXperts Technologies
   Trainer / Consultant @ SpringPeople
    Technologies
   Enteprise applications leveraging open source
    frameworks (spring,hibernate, gwt,jbpm..)
   Key contributor to InfraRED & Grails jBPM
    plugin (open source)
Agenda
   What is REST?
   REST Concepts
   RESTful Architecture Design
   Spring @MVC
   Implement REST api using Spring @MVC 3.0
What is REST?
   Representational State Transfer
   Term coined up by Roy Fielding
    −   Author of HTTP spec
   Architectural style
   Architectural basis for HTTP
    −   Defined a posteriori
Core REST Concepts
 Identifiable Resources
 Uniform interface

 Stateless conversation

 Resource representations

 Hypermedia
Identifiable Resources
   Everything is a resource
    −   Customer
    −   Order
    −   Catalog Item
   Resources are accessed by URIs
Uniform interface
   Interact with Resource using single, fixed
    interface
   GET /orders - fetch list of orders
   GET /orders/1 - fetch order with id 1
   POST /orders – create new order
   PUT /orders/1 – update order with id 1
   DELETE /orders/1 – delete order with id 1
   GET /customers/1/order – all orders for
    customer with id 1
Resource representations
   More that one representation possible
    −   text/html, image/gif, application/pdf
   Desired representation set in Accept HTTP
    header
    −   Or file extension
   Delivered representation show in Content-
    Type
   Access resources through representation
   Prefer well-known media types
Stateless conversation
   Server does not maintain state
    −   Don’t use the Session!
   Client maintains state through links
   Very scalable
   Enforces loose coupling (no shared session
    knowledge)
Hypermedia
   Resources contain links
   Client state transitions are made through these links
   Links are provided by server
   Example

    <oder ref=”/order/1”>
        <customer ref=”/customers/1”/>
        <lineItems>
             <lineItem item=”/catalog/item/125” qty=”10”/>
             <lineItem item=”/catalog/item/150” qty=”5”>
        </lineItems>
    </oder>
RESTful Architecture
RESTful application design
   Identify resources
    −   Design URIs
   Select representations
    −   Or create new ones
   Identify method semantics
   Select response codes
Implement Restful API using Spring MVC
Spring @MVC
@Controller
public class AccountController {
     @Autowired AccountService accountService;

     @RequestMapping("/details")
     public String details(@RequestParam("id")Long id,
                     Model model) {
          Account account = accountService.findAccount(id);
          model.addAttribute(account);
          return "account/details";
     }
}

account/details.jsp
    <h1>Account Details</h1>
    <p>Name : ${account.name}</p>
    <p>Balance : ${account.balance}</p>

../details?id=1
RESTful support in Spring 3.0
   Extends Spring @MVC to handle URL
    templates - @PathVariable
   Leverages Spring OXM module to provide
    marshalling / unmarshalling (castor, xstream,
    jaxb etc)
   @RequestBody – extract request body to
    method parameter
   @ResponseBody – render return value to
    response body using converter – no views
    required
REST controller
@Controller public class AccountController {

      @RequestMapping(value="/accounts",method=RequestMethod.GET)
      @ResponseBody public AccountList getAllAcccount() {
      }

      @RequestMapping(value="/accounts/${id}",method=RequestMethod.GET)
      @ResponseBody public Account getAcccount(@PathVariable("id")Long id) {
      }

      @RequestMapping(value="/accounts/",method=RequestMethod.POST)
      @ResponseBody public Long createAcccount(@RequestBody Account account) {
      }

      @RequestMapping(value="/accounts/${id}",method=RequestMethod.PUT)
      @ResponseBody public Account updateAcccount(@PathVariable("id")Long id, @RequestBody Account account) {
      }

      @RequestMapping(value="/accounts/${id}",method=RequestMethod.DELETE)
      @ResponseBody public void deleteAcccount(@PathVariable("id")Long id) {
      }
}
web.xml

<servlet>
    <servlet-name>rest-api</servlet-name>
    <servlet-class>org....web.servlet.DispatcherServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
</servlet>

<servlet-mapping>
    <servlet-name>rest-api</servlet-name>
    <url-pattern>/rest/*</url-pattern>
</servlet-mapping>
rest-api-servlet-context.xml

<bean id="marshaller" class="...oxm.xstream.XStreamMarshaller">
   <property name="aliases">
       <map>
          <entry key="category" value="...domain.Category"/>
          <entry key="catalogItem" value="...domain.CatalogItem"/>
       </map>
   </property>
</bean>
rest-api-servlet-context.xml
<bean
    class="...mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <util:list>
              <bean
                    class="...http.converter.xml.MarshallingHttpMessageConverter">
                    <constructor-arg ref="marshaller" />
              </bean>
              <bean
                    class="...http.converter.StringHttpMessageConverter" />
        </util:list>
    </property>
</bean>
Invoke REST services
   The new RestTemplate class provides client-
    side invocation of a RESTful web-service
     HTTP                       RestTemplate Method
    Method
    DELETE    delete(String url, String... urlVariables)
    GET       getForObject(String url, Class<t> responseType, String …
              urlVariables)
    HEAD      headForHeaders(String url, String… urlVariables)
    OPTIONS   optionsForAllow(String url, String… urlVariables)
    POST      postForLocation(String url, Object request, String…
              urlVariables)

    PUT       put(String url, Object request, String…urlVariables)
REST template example

AccountList accounts = restTemplate.getForObject("/accounts/",AccountList.class);

Account account = restTemplate.getForObject("/accounts/${id}",Account.class ,"1");

restTemplate.postForLocation("/accounts/", account);

restTemplate.put("/accounts/${id}",account,"1");

restTemplate.delete("/accounts/${id}", "1");
Demo
Questions?
Thank You

More Related Content

PPTX
Reactjs
PPTX
PPTX
PPT
Spring ppt
PPTX
Spring boot Introduction
PPTX
Introduction to spring boot
PPT
Advanced Javascript
PPT
Spring Boot in Action
Reactjs
Spring ppt
Spring boot Introduction
Introduction to spring boot
Advanced Javascript
Spring Boot in Action

What's hot (20)

PPTX
PDF
Spring MVC
PPTX
Intro to React
PPT
Spring Framework
PPTX
Laravel Tutorial PPT
PPTX
Introduction to EJB
PPTX
Spring Web MVC
PPTX
Introduction à spring boot
PPTX
Laravel overview
PDF
JavaScript guide 2020 Learn JavaScript
PPT
React js
PPTX
Spring mvc
PDF
Hibernate Presentation
PPS
Jdbc architecture and driver types ppt
PPTX
Spring beans
PPT
Formation jpa-hibernate-spring-data
PPT
Java EE Introduction
PDF
JavaScript Fetch API
PPTX
Spring data jpa
PPTX
Sharing Data Between Angular Components
Spring MVC
Intro to React
Spring Framework
Laravel Tutorial PPT
Introduction to EJB
Spring Web MVC
Introduction à spring boot
Laravel overview
JavaScript guide 2020 Learn JavaScript
React js
Spring mvc
Hibernate Presentation
Jdbc architecture and driver types ppt
Spring beans
Formation jpa-hibernate-spring-data
Java EE Introduction
JavaScript Fetch API
Spring data jpa
Sharing Data Between Angular Components
Ad

Viewers also liked (20)

PDF
RESTful Web Services with Spring MVC
PDF
REST APIs with Spring
PDF
Spring Web Services: SOAP vs. REST
PDF
Microservices with Spring Boot
PDF
RESTful Web Services
PDF
Java 8 - New Features
PDF
That old Spring magic has me in its SpEL
KEY
Modular Java - OSGi
PDF
Spring boot
PDF
Java Configuration Deep Dive with Spring
PDF
Boot It Up
PPT
Spring MVC
PPTX
Level 3 REST Makes Your API Browsable
PDF
Spring MVC
PDF
Spring MVC - Web Forms
PDF
Testing Spring MVC and REST Web Applications
PPTX
REST Enabling Your Oracle Database
PPTX
Make Your API Irresistible
PPTX
Soap and restful webservice
PPT
Struts 2 + Spring
RESTful Web Services with Spring MVC
REST APIs with Spring
Spring Web Services: SOAP vs. REST
Microservices with Spring Boot
RESTful Web Services
Java 8 - New Features
That old Spring magic has me in its SpEL
Modular Java - OSGi
Spring boot
Java Configuration Deep Dive with Spring
Boot It Up
Spring MVC
Level 3 REST Makes Your API Browsable
Spring MVC
Spring MVC - Web Forms
Testing Spring MVC and REST Web Applications
REST Enabling Your Oracle Database
Make Your API Irresistible
Soap and restful webservice
Struts 2 + Spring
Ad

Similar to Building RESTful applications using Spring MVC (20)

PPTX
PPTX
Rest with Java EE 6 , Security , Backbone.js
PPTX
Overview of RESTful web services
PPTX
JAX-RS 2.0 and OData
PDF
ODP
Services Stanford 2012
PDF
May 2010 - RestEasy
PPTX
PPTX
Rest presentation
PPTX
Spring 3.x - Spring MVC - Advanced topics
ODP
RESTing with JAX-RS
PPTX
Introduction to the SharePoint Client Object Model and REST API
PDF
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
PPTX
Mastering-ASPNET-Web-API-and-RESTful-Patterns.pptx
ODP
RESTful Web Services with JAX-RS
PDF
Rest with Spring
PPTX
Ppt on web development and this has all details
PDF
CDI, Seam & RESTEasy: You haven't seen REST yet!
PDF
Spark IT 2011 - Developing RESTful Web services with JAX-RS
PDF
Services in Drupal 8
Rest with Java EE 6 , Security , Backbone.js
Overview of RESTful web services
JAX-RS 2.0 and OData
Services Stanford 2012
May 2010 - RestEasy
Rest presentation
Spring 3.x - Spring MVC - Advanced topics
RESTing with JAX-RS
Introduction to the SharePoint Client Object Model and REST API
Multi Client Development with Spring for SpringOne 2GX 2013 with Roy Clarkson
Mastering-ASPNET-Web-API-and-RESTful-Patterns.pptx
RESTful Web Services with JAX-RS
Rest with Spring
Ppt on web development and this has all details
CDI, Seam & RESTEasy: You haven't seen REST yet!
Spark IT 2011 - Developing RESTful Web services with JAX-RS
Services in Drupal 8

More from IndicThreads (20)

PPTX
Http2 is here! And why the web needs it
ODP
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
PPT
Go Programming Language - Learning The Go Lang way
PPT
Building Resilient Microservices
PPT
App using golang indicthreads
PDF
Building on quicksand microservices indicthreads
PDF
How to Think in RxJava Before Reacting
PPT
Iot secure connected devices indicthreads
PDF
Real world IoT for enterprises
PPT
IoT testing and quality assurance indicthreads
PPT
Functional Programming Past Present Future
PDF
Harnessing the Power of Java 8 Streams
PDF
Building & scaling a live streaming mobile platform - Gr8 road to fame
PPTX
Internet of things architecture perspective - IndicThreads Conference
PDF
Cars and Computers: Building a Java Carputer
PPTX
Scrap Your MapReduce - Apache Spark
PPT
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
PPTX
Speed up your build pipeline for faster feedback
PPT
Unraveling OpenStack Clouds
PPTX
Digital Transformation of the Enterprise. What IT leaders need to know!
Http2 is here! And why the web needs it
Understanding Bitcoin (Blockchain) and its Potential for Disruptive Applications
Go Programming Language - Learning The Go Lang way
Building Resilient Microservices
App using golang indicthreads
Building on quicksand microservices indicthreads
How to Think in RxJava Before Reacting
Iot secure connected devices indicthreads
Real world IoT for enterprises
IoT testing and quality assurance indicthreads
Functional Programming Past Present Future
Harnessing the Power of Java 8 Streams
Building & scaling a live streaming mobile platform - Gr8 road to fame
Internet of things architecture perspective - IndicThreads Conference
Cars and Computers: Building a Java Carputer
Scrap Your MapReduce - Apache Spark
Continuous Integration (CI) and Continuous Delivery (CD) using Jenkins & Docker
Speed up your build pipeline for faster feedback
Unraveling OpenStack Clouds
Digital Transformation of the Enterprise. What IT leaders need to know!

Recently uploaded (20)

PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Electronic commerce courselecture one. Pdf
PDF
Chapter 2 Digital Image Fundamentals.pdf
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
NewMind AI Monthly Chronicles - July 2025
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Advanced Soft Computing BINUS July 2025.pdf
PDF
Empathic Computing: Creating Shared Understanding
PDF
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PPT
Teaching material agriculture food technology
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....
“AI and Expert System Decision Support & Business Intelligence Systems”
Advanced methodologies resolving dimensionality complications for autism neur...
How Onsite IT Support Drives Business Efficiency, Security, and Growth.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Electronic commerce courselecture one. Pdf
Chapter 2 Digital Image Fundamentals.pdf
Understanding_Digital_Forensics_Presentation.pptx
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
20250228 LYD VKU AI Blended-Learning.pptx
NewMind AI Monthly Chronicles - July 2025
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Advanced Soft Computing BINUS July 2025.pdf
Empathic Computing: Creating Shared Understanding
Shreyas Phanse Resume: Experienced Backend Engineer | Java • Spring Boot • Ka...
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Teaching material agriculture food technology
Per capita expenditure prediction using model stacking based on satellite ima...
NewMind AI Weekly Chronicles - August'25 Week I
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
breach-and-attack-simulation-cybersecurity-india-chennai-defenderrabbit-2025....

Building RESTful applications using Spring MVC

  • 1. Restful applications using Spring MVC Kamal Govindraj TenXperts Technologies
  • 2. About Me  Programming for 13 Years  Architect @ TenXperts Technologies  Trainer / Consultant @ SpringPeople Technologies  Enteprise applications leveraging open source frameworks (spring,hibernate, gwt,jbpm..)  Key contributor to InfraRED & Grails jBPM plugin (open source)
  • 3. Agenda  What is REST?  REST Concepts  RESTful Architecture Design  Spring @MVC  Implement REST api using Spring @MVC 3.0
  • 4. What is REST?  Representational State Transfer  Term coined up by Roy Fielding − Author of HTTP spec  Architectural style  Architectural basis for HTTP − Defined a posteriori
  • 5. Core REST Concepts  Identifiable Resources  Uniform interface  Stateless conversation  Resource representations  Hypermedia
  • 6. Identifiable Resources  Everything is a resource − Customer − Order − Catalog Item  Resources are accessed by URIs
  • 7. Uniform interface  Interact with Resource using single, fixed interface  GET /orders - fetch list of orders  GET /orders/1 - fetch order with id 1  POST /orders – create new order  PUT /orders/1 – update order with id 1  DELETE /orders/1 – delete order with id 1  GET /customers/1/order – all orders for customer with id 1
  • 8. Resource representations  More that one representation possible − text/html, image/gif, application/pdf  Desired representation set in Accept HTTP header − Or file extension  Delivered representation show in Content- Type  Access resources through representation  Prefer well-known media types
  • 9. Stateless conversation  Server does not maintain state − Don’t use the Session!  Client maintains state through links  Very scalable  Enforces loose coupling (no shared session knowledge)
  • 10. Hypermedia  Resources contain links  Client state transitions are made through these links  Links are provided by server  Example <oder ref=”/order/1”> <customer ref=”/customers/1”/> <lineItems> <lineItem item=”/catalog/item/125” qty=”10”/> <lineItem item=”/catalog/item/150” qty=”5”> </lineItems> </oder>
  • 12. RESTful application design  Identify resources − Design URIs  Select representations − Or create new ones  Identify method semantics  Select response codes
  • 13. Implement Restful API using Spring MVC
  • 14. Spring @MVC @Controller public class AccountController { @Autowired AccountService accountService; @RequestMapping("/details") public String details(@RequestParam("id")Long id, Model model) { Account account = accountService.findAccount(id); model.addAttribute(account); return "account/details"; } } account/details.jsp <h1>Account Details</h1> <p>Name : ${account.name}</p> <p>Balance : ${account.balance}</p> ../details?id=1
  • 15. RESTful support in Spring 3.0  Extends Spring @MVC to handle URL templates - @PathVariable  Leverages Spring OXM module to provide marshalling / unmarshalling (castor, xstream, jaxb etc)  @RequestBody – extract request body to method parameter  @ResponseBody – render return value to response body using converter – no views required
  • 16. REST controller @Controller public class AccountController { @RequestMapping(value="/accounts",method=RequestMethod.GET) @ResponseBody public AccountList getAllAcccount() { } @RequestMapping(value="/accounts/${id}",method=RequestMethod.GET) @ResponseBody public Account getAcccount(@PathVariable("id")Long id) { } @RequestMapping(value="/accounts/",method=RequestMethod.POST) @ResponseBody public Long createAcccount(@RequestBody Account account) { } @RequestMapping(value="/accounts/${id}",method=RequestMethod.PUT) @ResponseBody public Account updateAcccount(@PathVariable("id")Long id, @RequestBody Account account) { } @RequestMapping(value="/accounts/${id}",method=RequestMethod.DELETE) @ResponseBody public void deleteAcccount(@PathVariable("id")Long id) { } }
  • 17. web.xml <servlet> <servlet-name>rest-api</servlet-name> <servlet-class>org....web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>rest-api</servlet-name> <url-pattern>/rest/*</url-pattern> </servlet-mapping>
  • 18. rest-api-servlet-context.xml <bean id="marshaller" class="...oxm.xstream.XStreamMarshaller"> <property name="aliases"> <map> <entry key="category" value="...domain.Category"/> <entry key="catalogItem" value="...domain.CatalogItem"/> </map> </property> </bean>
  • 19. rest-api-servlet-context.xml <bean class="...mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <util:list> <bean class="...http.converter.xml.MarshallingHttpMessageConverter"> <constructor-arg ref="marshaller" /> </bean> <bean class="...http.converter.StringHttpMessageConverter" /> </util:list> </property> </bean>
  • 20. Invoke REST services  The new RestTemplate class provides client- side invocation of a RESTful web-service HTTP RestTemplate Method Method DELETE delete(String url, String... urlVariables) GET getForObject(String url, Class<t> responseType, String … urlVariables) HEAD headForHeaders(String url, String… urlVariables) OPTIONS optionsForAllow(String url, String… urlVariables) POST postForLocation(String url, Object request, String… urlVariables) PUT put(String url, Object request, String…urlVariables)
  • 21. REST template example AccountList accounts = restTemplate.getForObject("/accounts/",AccountList.class); Account account = restTemplate.getForObject("/accounts/${id}",Account.class ,"1"); restTemplate.postForLocation("/accounts/", account); restTemplate.put("/accounts/${id}",account,"1"); restTemplate.delete("/accounts/${id}", "1");
  • 22. Demo