SlideShare a Scribd company logo
Spring MVC Annotations
Contents

●   Introduction
●   DispatcherServlet
●   Controller
●   RequestMapping
●   RequestParam
●   RequestBody
●   ResponseBody
Spring MVC Controller Annotations



●   Introduced in Spring 2.5
●   Available for both Servlet MVC and Portlet MVC
●   No need to extend specific base classes or implement specific
    interfaces
●   No direct dependencies on Servlet or Portlet APIs
Dispatcher Servlet
Configuring DispatcherServlet

web.xml
<web-app>
    <servlet>
        <servlet-name>example</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>example</servlet-name>
        <url-pattern>/example/*</url-pattern>
    </servlet-mapping>
</web-app>



/WEB-INF/example-servlet.xml
<?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/beans
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.0.xsd">

    <context:component-scan base-package="ee.ignite.example.web"/>

    <!-- ... -->
</beans>
@Controler


    package ee.ignite.example.web;

    import org.springframework.stereotype.Controller;

    @Controller
    public class HelloWorldController {

    }




●       Flexible controller name
●       No need to extend specific base classes or implement specific
        interfaces
@RequestMapping
@Controller
@RequestMapping("/appointments")
public class AppointmentsController {

    private final AppointmentBook appointmentBook;

    @Autowired
    public AppointmentsController(AppointmentBook appointmentBook) {
        this.appointmentBook = appointmentBook;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Map<String, Appointment> get() {
        return appointmentBook.getAppointmentsForToday();
    }

    @RequestMapping(value="/{day}", method = RequestMethod.GET)
    public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
        return appointmentBook.getAppointmentsForDay(day);
    }

    @RequestMapping(value="/new", method = RequestMethod.GET)
    public AppointmentForm getNewForm() {
        return new AppointmentForm();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String add(@Validated AppointmentForm appointment, BindingResult result) {
        if (result.hasErrors()) {
            return "appointments/new";
        }
        appointmentBook.addAppointment(appointment);
        return "redirect:/appointments";
    }
}
@PathVariable
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
  Owner owner = ownerService.findOwner(ownerId);
  model.addAttribute("owner", owner);
  return "displayOwner";
}


URI template variable name must match with parameter variable name
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable("ownerId") String theOwner, Model model) {
  Owner owner = ownerService.findOwner(theOwner);
  model.addAttribute("owner", owner);
  return "displayOwner";
}


Multiple path variables
@RequestMapping(value="/owners/{ownerId}/pets/{petId}", method=RequestMethod.GET)
public String findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
  Owner owner = ownerService.findOwner(ownerId);
  Pet pet = owner.getPet(petId);
  model.addAttribute("pet", pet);
  return "displayPet";
}


Multiple values
@RequestMapping(value={"/new", "/novo", "/nuevo"})
public AppointmentForm getNewForm() {
    return new AppointmentForm();
}
Class level
@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {

    @RequestMapping("/pets/{petId}")
    public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
      // implementation omitted
    }
}
●   @PathVariable argument can be of any simple type such as int, long, Date and so on
●   It is possible to add support for additional data types (WebDataBinder or Formatters)
●   TypeMismatchException is thrown if conversion type fails

Regular Expressions

      {varName:regex}
@RequestMapping("{version:d.d.d}{extension:.[a-z]}")
public void handle(@PathVariable String version, @PathVariable String extension) {
}

Path Patterns
@RequestMapping(value="/*/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable("ownerId") String theOwner, Model model) {
}

@RequestMapping(value="/pets/*.do}", method=RequestMethod.GET)
public String findOwner(@PathVariable("ownerId") String theOwner, Model model) {
}
Consumable Media Types
     ●The request will be matched only if the Content-Type request header matches one
     of the specified media types.
     ●The consumes condition is supported on the class and on the method level.
     Method-level consumable types override the class-level consumable type.
                                                                       type
     ●   Can be negated as in !text/plain
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {
}


Producible Media Types
     ●The request will be matched only if the Accept request header matches one of the
     specified media type.
     ●The consumes condition is supported on the class and on the method level.
     Method-level consumable types override the class-level consumable type.
                                                                       type
     ●   Can be negated as in !text/plain
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {
}
Request Parameters and Header Values
     ● Presence of a param: paramName
     ● Absence of a param: !paramName

     ● Specific value: paramName=value




@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
}

@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="myHeader=myValue")
public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {
}
Supported method argument types
 ●   Request or response objects (Servlet API)
 ●   Session object (Servlet API)
 ●   org.springframework.web.context.request.WebRequest or
     org.springframework.web.context.request.NativeWebRequest
 ●   java.util.Locale
 ●   java.io.InputStream / java.io.Reader
 ●   java.io.OutputStream / java.io.Writer
 ●   java.security.Principal
 ●   HttpEntity<?>
 ●   java.util.Map / org.springframework.ui.Model / org.springframework.ui.ModelMap
 ●   org.springframework.web.servlet.mvc.support.RedirectAttributes
 ●   org.springframework.validation.Errors / org.springframework.validation.BindingResult
 ●   org.springframework.web.bind.support.SessionStatus
 ●   org.springframework.web.util.UriComponentsBuilder



The Errors or BindingResult parameters have to follow the model object that is being bound
immediately
Supported method return types

 ●   ModelAndView
 ●   Model
 ●   Map
 ●   View
 ●   String
 ●   Void
 ●   HttpEntity<?> or ResponseEntity<?>
@RequestParam



●   Bind request parameters to a method parameter
●   Required by default.
●   @RequestParam(value="id", required=false) specifies parameter as
    optional
@RequestMapping(method = RequestMethod.GET)
    public String setupForm(@RequestParam("petId") int petId, ModelMap model) {
        Pet pet = this.clinic.loadPet(petId);
        model.addAttribute("pet", pet);
        return "petForm";
    }
@RequestBody



●     Indicates that a method parameter should be bound to the value of the
      HTTP request body
●     HttpMessageConverter is used to convert the request body to the
      method argument

Default Converters

 ●   ByteArrayHttpMessageConverter converts byte arrays
 ●   StringHttpMessageConverter converts strings
 ●   FormHttpMessageConverter converts form data to/from a MultiValueMap<String, String>
 ●   SourceHttpMessageConverter converts to/from a javax.xml.transform.Source
@ResponseBody



●   Indicates that the return type should be written straight to the HTTP
    response body
●   Uses HttpMessageConverter to convert the returned object to a
    response body
@RequestMapping(value = "/something", method = RequestMethod.PUT)
@ResponseBody
public String helloWorld() {
  return "Hello World";
}

More Related Content

PPT
Spring MVC Basics
PDF
Introduction to Spring MVC
PPT
Spring 3.x - Spring MVC
PPT
PPTX
Spring MVC Architecture Tutorial
PPTX
Spring MVC
ODP
Java Spring MVC Framework with AngularJS by Google and HTML5
PDF
Spring annotation
Spring MVC Basics
Introduction to Spring MVC
Spring 3.x - Spring MVC
Spring MVC Architecture Tutorial
Spring MVC
Java Spring MVC Framework with AngularJS by Google and HTML5
Spring annotation

What's hot (19)

PPT
Java Server Faces (JSF) - advanced
PDF
Spring mvc
PDF
Spring MVC 3.0 Framework (sesson_2)
PDF
What's Coming in Spring 3.0
ODP
springmvc-150923124312-lva1-app6892
PPT
Struts,Jsp,Servlet
PDF
Spring 4 Web App
PPTX
ASP.NET Routing & MVC
PPTX
Integration of Backbone.js with Spring 3.1
PPTX
Implicit object.pptx
PPT
Backbone js
PPTX
Implicit objects advance Java
ODP
Annotation-Based Spring Portlet MVC
PPT
JSF Component Behaviors
ODP
Spray - Build RESTfull services in scala
PPT
Data Access with JDBC
PPTX
Introduction to JSP
PDF
AngularJS Basic Training
PPTX
Rest with Java EE 6 , Security , Backbone.js
Java Server Faces (JSF) - advanced
Spring mvc
Spring MVC 3.0 Framework (sesson_2)
What's Coming in Spring 3.0
springmvc-150923124312-lva1-app6892
Struts,Jsp,Servlet
Spring 4 Web App
ASP.NET Routing & MVC
Integration of Backbone.js with Spring 3.1
Implicit object.pptx
Backbone js
Implicit objects advance Java
Annotation-Based Spring Portlet MVC
JSF Component Behaviors
Spray - Build RESTfull services in scala
Data Access with JDBC
Introduction to JSP
AngularJS Basic Training
Rest with Java EE 6 , Security , Backbone.js
Ad

Viewers also liked (16)

PPTX
Introduction to Spring Framework
PPTX
Next stop: Spring 4
PDF
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
PPTX
Spring Web MVC
PPTX
Spring Social - Messaging Friends & Influencing People
PPTX
Flexible validation with Hibernate Validator 5.x.
PDF
Spring4 whats up doc?
PPTX
Sectors of indian economy
PPTX
nationalism movement in Indochina
PPTX
Physicalfeaturesofindia
PDF
Spring mvc my Faviourite Slide
DOCX
02 java spring-hibernate-experience-questions
PDF
Spring 3 Annotated Development
PDF
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
PDF
What's new in Spring 3?
PPTX
Spring @Transactional Explained
Introduction to Spring Framework
Next stop: Spring 4
Spring Framework 4.0 - The Next Generation - Soft-Shake 2013
Spring Web MVC
Spring Social - Messaging Friends & Influencing People
Flexible validation with Hibernate Validator 5.x.
Spring4 whats up doc?
Sectors of indian economy
nationalism movement in Indochina
Physicalfeaturesofindia
Spring mvc my Faviourite Slide
02 java spring-hibernate-experience-questions
Spring 3 Annotated Development
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
What's new in Spring 3?
Spring @Transactional Explained
Ad

Similar to Spring MVC Annotations (20)

PDF
REST based web applications with Spring 3
PPT
Spring-training-in-bangalore
PDF
Introducing spring
PDF
Spring MVC - Web Forms
PDF
Multi Client Development with Spring - Josh Long
PDF
Spring tutorial
PPT
Spring training
KEY
Multi Client Development with Spring
KEY
Domain Specific Languages (EclipseCon 2012)
PDF
Extending spring
PDF
Spring MVC to iOS and the REST
PPT
Spring training
PDF
Spring 3.1 in a Nutshell
PPTX
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
PDF
Spring Reference
PPT
Spring Basics
PDF
Manual tutorial-spring-java
PDF
Spring Reference
PDF
quickguide-einnovator-7-spring-mvc
PPTX
Spring MVC 5 & Hibernate 5 Integration
REST based web applications with Spring 3
Spring-training-in-bangalore
Introducing spring
Spring MVC - Web Forms
Multi Client Development with Spring - Josh Long
Spring tutorial
Spring training
Multi Client Development with Spring
Domain Specific Languages (EclipseCon 2012)
Extending spring
Spring MVC to iOS and the REST
Spring training
Spring 3.1 in a Nutshell
Spring 3.1 to 3.2 in a Nutshell - Spring I/O 2012
Spring Reference
Spring Basics
Manual tutorial-spring-java
Spring Reference
quickguide-einnovator-7-spring-mvc
Spring MVC 5 & Hibernate 5 Integration

Recently uploaded (20)

PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PDF
CIFDAQ's Market Insight: SEC Turns Pro Crypto
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Modernizing your data center with Dell and AMD
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
MYSQL Presentation for SQL database connectivity
PDF
Spectral efficient network and resource selection model in 5G networks
PPT
Teaching material agriculture food technology
PDF
Approach and Philosophy of On baking technology
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
cuic standard and advanced reporting.pdf
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PDF
Machine learning based COVID-19 study performance prediction
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
CIFDAQ's Market Insight: SEC Turns Pro Crypto
Encapsulation_ Review paper, used for researhc scholars
20250228 LYD VKU AI Blended-Learning.pptx
Modernizing your data center with Dell and AMD
Understanding_Digital_Forensics_Presentation.pptx
Digital-Transformation-Roadmap-for-Companies.pptx
MYSQL Presentation for SQL database connectivity
Spectral efficient network and resource selection model in 5G networks
Teaching material agriculture food technology
Approach and Philosophy of On baking technology
Building Integrated photovoltaic BIPV_UPV.pdf
cuic standard and advanced reporting.pdf
Reach Out and Touch Someone: Haptics and Empathic Computing
Chapter 3 Spatial Domain Image Processing.pdf
Dropbox Q2 2025 Financial Results & Investor Presentation
Unlocking AI with Model Context Protocol (MCP)
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
Machine learning based COVID-19 study performance prediction
Per capita expenditure prediction using model stacking based on satellite ima...

Spring MVC Annotations

  • 2. Contents ● Introduction ● DispatcherServlet ● Controller ● RequestMapping ● RequestParam ● RequestBody ● ResponseBody
  • 3. Spring MVC Controller Annotations ● Introduced in Spring 2.5 ● Available for both Servlet MVC and Portlet MVC ● No need to extend specific base classes or implement specific interfaces ● No direct dependencies on Servlet or Portlet APIs
  • 5. Configuring DispatcherServlet web.xml <web-app> <servlet> <servlet-name>example</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>example</servlet-name> <url-pattern>/example/*</url-pattern> </servlet-mapping> </web-app> /WEB-INF/example-servlet.xml <?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/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"> <context:component-scan base-package="ee.ignite.example.web"/> <!-- ... --> </beans>
  • 6. @Controler package ee.ignite.example.web; import org.springframework.stereotype.Controller; @Controller public class HelloWorldController { } ● Flexible controller name ● No need to extend specific base classes or implement specific interfaces
  • 7. @RequestMapping @Controller @RequestMapping("/appointments") public class AppointmentsController { private final AppointmentBook appointmentBook; @Autowired public AppointmentsController(AppointmentBook appointmentBook) { this.appointmentBook = appointmentBook; } @RequestMapping(method = RequestMethod.GET) public Map<String, Appointment> get() { return appointmentBook.getAppointmentsForToday(); } @RequestMapping(value="/{day}", method = RequestMethod.GET) public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) { return appointmentBook.getAppointmentsForDay(day); } @RequestMapping(value="/new", method = RequestMethod.GET) public AppointmentForm getNewForm() { return new AppointmentForm(); } @RequestMapping(method = RequestMethod.POST) public String add(@Validated AppointmentForm appointment, BindingResult result) { if (result.hasErrors()) { return "appointments/new"; } appointmentBook.addAppointment(appointment); return "redirect:/appointments"; } }
  • 8. @PathVariable @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET) public String findOwner(@PathVariable String ownerId, Model model) { Owner owner = ownerService.findOwner(ownerId); model.addAttribute("owner", owner); return "displayOwner"; } URI template variable name must match with parameter variable name @RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET) public String findOwner(@PathVariable("ownerId") String theOwner, Model model) { Owner owner = ownerService.findOwner(theOwner); model.addAttribute("owner", owner); return "displayOwner"; } Multiple path variables @RequestMapping(value="/owners/{ownerId}/pets/{petId}", method=RequestMethod.GET) public String findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { Owner owner = ownerService.findOwner(ownerId); Pet pet = owner.getPet(petId); model.addAttribute("pet", pet); return "displayPet"; } Multiple values @RequestMapping(value={"/new", "/novo", "/nuevo"}) public AppointmentForm getNewForm() { return new AppointmentForm(); }
  • 9. Class level @Controller @RequestMapping("/owners/{ownerId}") public class RelativePathUriTemplateController { @RequestMapping("/pets/{petId}") public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { // implementation omitted } } ● @PathVariable argument can be of any simple type such as int, long, Date and so on ● It is possible to add support for additional data types (WebDataBinder or Formatters) ● TypeMismatchException is thrown if conversion type fails Regular Expressions {varName:regex} @RequestMapping("{version:d.d.d}{extension:.[a-z]}") public void handle(@PathVariable String version, @PathVariable String extension) { } Path Patterns @RequestMapping(value="/*/{ownerId}", method=RequestMethod.GET) public String findOwner(@PathVariable("ownerId") String theOwner, Model model) { } @RequestMapping(value="/pets/*.do}", method=RequestMethod.GET) public String findOwner(@PathVariable("ownerId") String theOwner, Model model) { }
  • 10. Consumable Media Types ●The request will be matched only if the Content-Type request header matches one of the specified media types. ●The consumes condition is supported on the class and on the method level. Method-level consumable types override the class-level consumable type. type ● Can be negated as in !text/plain @RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json") public void addPet(@RequestBody Pet pet, Model model) { } Producible Media Types ●The request will be matched only if the Accept request header matches one of the specified media type. ●The consumes condition is supported on the class and on the method level. Method-level consumable types override the class-level consumable type. type ● Can be negated as in !text/plain @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json") @ResponseBody public Pet getPet(@PathVariable String petId, Model model) { }
  • 11. Request Parameters and Header Values ● Presence of a param: paramName ● Absence of a param: !paramName ● Specific value: paramName=value @RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue") public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { } @RequestMapping(value = "/pets", method = RequestMethod.GET, headers="myHeader=myValue") public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) { }
  • 12. Supported method argument types ● Request or response objects (Servlet API) ● Session object (Servlet API) ● org.springframework.web.context.request.WebRequest or org.springframework.web.context.request.NativeWebRequest ● java.util.Locale ● java.io.InputStream / java.io.Reader ● java.io.OutputStream / java.io.Writer ● java.security.Principal ● HttpEntity<?> ● java.util.Map / org.springframework.ui.Model / org.springframework.ui.ModelMap ● org.springframework.web.servlet.mvc.support.RedirectAttributes ● org.springframework.validation.Errors / org.springframework.validation.BindingResult ● org.springframework.web.bind.support.SessionStatus ● org.springframework.web.util.UriComponentsBuilder The Errors or BindingResult parameters have to follow the model object that is being bound immediately
  • 13. Supported method return types ● ModelAndView ● Model ● Map ● View ● String ● Void ● HttpEntity<?> or ResponseEntity<?>
  • 14. @RequestParam ● Bind request parameters to a method parameter ● Required by default. ● @RequestParam(value="id", required=false) specifies parameter as optional @RequestMapping(method = RequestMethod.GET) public String setupForm(@RequestParam("petId") int petId, ModelMap model) { Pet pet = this.clinic.loadPet(petId); model.addAttribute("pet", pet); return "petForm"; }
  • 15. @RequestBody ● Indicates that a method parameter should be bound to the value of the HTTP request body ● HttpMessageConverter is used to convert the request body to the method argument Default Converters ● ByteArrayHttpMessageConverter converts byte arrays ● StringHttpMessageConverter converts strings ● FormHttpMessageConverter converts form data to/from a MultiValueMap<String, String> ● SourceHttpMessageConverter converts to/from a javax.xml.transform.Source
  • 16. @ResponseBody ● Indicates that the return type should be written straight to the HTTP response body ● Uses HttpMessageConverter to convert the returned object to a response body @RequestMapping(value = "/something", method = RequestMethod.PUT) @ResponseBody public String helloWorld() { return "Hello World"; }