SlideShare una empresa de Scribd logo
1 de 35
Spring MVC – Advanced topics
             Guy Nir
          January 2012
Spring MVC

Agenda
» Annotation driven controllers
» Arguments and return types
» Validation
Annotation driven
   controllers
Spring MVC – Advanced topics

Annotation driven controllers
»   @Controller
»   @RequestMapping (class-level and method-level)
»   @PathVariable (URI template)
»   @ModelAttribute (method-level, argument-level)
»   @CookieValue, @HeaderValue
»   @DateTimeFormat
»   @RequestBody
»   @ResponseBody
Spring MVC – Advanced topics

Annotation driven controllers
@Controller
» Spring stereotype that identify a class as being a Spring
  Bean.
» Has an optional ‘value’ property.
// Bean name is ‘loginController’
@Controller
public class LoginController {
}

// Bean name is ‘portal’.
@Controller(‚portal‛)
public class PortalController {
}
Spring MVC – Advanced topics

Annotation driven controllers
@RequestMapping
» Define URL mapping for a class and/or method.
// Controller root URL: http://host.com/portal
@Controller
@RequestMapping(‚/portal‛)
public class PortalController {

    // Handle [GET] http://host.com/portal
    @RequestMapping(method = RequestMethod.GET)
    public String enterPortal() { ... }

    // Handle [GET] http://host.com/portal/userProfile
    @RequestMapping(‚/userProfile‛)
    public String processUserProfileRequest() { ... }
}


» Support deterministic and Ant-style mapping
Spring MVC – Advanced topics

Annotation driven controllers
@RequestMapping
» Available properties:
     method – List of supported HTTP method (GET, POST, ...).
     produces/consumes – define expected content types.

GET http://google.com/ HTTP/1.1
Accept: text/html, application/xhtml+xml, */*           HTTP
Accept-Language: he-IL                                 request
Accept-Encoding: gzip, deflate


HTTP/1.1 200 OK
Content-Type: text/html; charset=UTF-8                  HTTP
Date: Sun, 29 Jan 2012 19:45:21 GMT                   response
Expires: Tue, 28 Feb 2012 19:45:21 GMT
Spring MVC – Advanced topics

Annotation driven controllers
@RequestMapping
@Controller
@RequestMapping(‚/portal‛)
public class UserInfoController {

    @RequestMapping(value = ‚/userInfo/xml‚,
                    consumes = ‚application/json‛,
                    produces = ‚application/xml‛)
    public UserInformation getUserInformationAsXML() {    Requires message
    }
                                                             converters

    @RequestMapping(value = ‚/userInfo/yaml‚,
                    consumes = ‚application/json‛,
                    produces = ‚application/Json‛)
    public UserInformation getUserInformationAsJSon() {
    }
}
Spring MVC – Advanced topics

Annotation driven controllers
@RequestMapping
» Required parameters.
// URL must in a form of: http://host.com/?userId=...&username=admin
@RequestMapping(value = ‚/‚, params = { ‚userId‛, ‚username!=guest‛, ‚!password‛ })
public UserInformation getUserInformationAsXML() {
}




» Required headers
@RequestMapping(value = ‚/userInfo‚, headers = { ‚Accept-Language=he-IL‛ })
public UserInformation getUserInformationAsXML() {
}                                                     GET http://google.com/ HTTP/1.1
                                                      Accept-Language: he-IL
                                                      Accept-Encoding: gzip, deflate
Spring MVC – Advanced topics

Annotation driven controllers
URI templates (@PathVariable)
» Allow us to define part of the URI as a template token.
» Support regular expressions to narrow scope of values.
» Only for simple types, java.lang.String or Date variant.
» Throw TypeMismatchException on failure to convert.
// Handle ‘userId’ with positive numbers only (0 or greater).
@RequestMapping(‚/users/{userId:[0-9]+})
public void processUserRequest(@PathVariable(‚userId‛) int userId) { ... }

// Handle ‘userId’ with negative numbers only.
@RequestMapping(‚/users/{userId:-[0-9]+})
public void processUserRequest(@PathVariable(‚userId‛) int userId) { ... }
Spring MVC – Advanced topics

Annotation driven controllers
@ModelAttribute
» Define a new model attribute.
    Single attribute approach
    Multiple attributes approach
» Access existing model attribute.
Spring MVC – Advanced topics

Annotation driven controllers
@ModelAttribute
» Definition of a single model attribute
@Controller
public class PrepareFormController

    @Override
    public ModelAndView prepareForm() {
        ModelAndView mav = new ModelAndView("details");
        mav.addObject("userDetails", new UserDetails());

        mav.addObject("months", createIntegerList(1, 12));
        mav.addObject("years", createIntegerList(1940, 2011));
        return mav;
    }
}
Spring MVC – Advanced topics

Annotation driven controllers
@ModelAttribute
» Definition of a single model attribute
@Controller
public class PrepareFormController

    @ModelAttribute("userDetails")
    public UserDetails newUserDetails() {
        return new UserDetails();
    }

    @ModelAttribute("months")
    public int[] getMonthList() {
        return new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
    }
}
Spring MVC – Advanced topics

Annotation driven controllers
@ModelAttribute
» Definition of a single model attribute
@Controller
public class ValidateUserFormController

    @RequestMapping(method = RequestMethod.GET)
    public String validateForm(HttpServletRequest request, HttpServletResponse ...) {
        String firstName = request.getParameter(‚firstName‛);
        String lastName = request.getParameter(‚lastName‛);

        // ...
    }
}
Spring MVC – Advanced topics

Annotation driven controllers
@ModelAttribute
» Definition of a single model attribute
@Controller
public class ValidateUserFormController

    @RequestMapping(method = RequestMethod.GET)
    public String validateForm(@ModelAttribute("userDetails") UserDetails details) {
        // ...
    }

    @ModelAttribute("userDetails")
    public UserDetails getUserDetails(HttpServletRequest request) {
        UserDetails user = new UserDetails();
        user.setFirstName(request.getParameter("firstName"));
        return user;
    }
}
Spring MVC – Advanced topics

Annotation driven controllers
@ModelAttribute
» Definition of a single model attribute
public class UserFormControllerTest {

    @Test
    public void testValidateForm() {
        UserFormController formController = new UserFormController();
        UserDetails userDetails = new UserDetails();
        // ...

        // Simple way to test a method.
        String viewName = formController.validateForm(userDetails);

        Assert.assertEquals("OK", viewName);
    }
}
Spring MVC – Advanced topics

Annotation driven controllers
@ModelAttribute
» Definition of a multiple model attribute
@ModelAttribute("months")
public int[] getMonthList() {
    return new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
}

@ModelAttribute("months")
public int[] getYears() {
    return new int[] { 1940, 1941, ... };
}

@ModelAttribute
public void populateAllAttributes(Model model, HttpServletRequest ...) {
    model.addAttribute(‚years", new int[] { ... });
    model.addAttribute(‚months", new int[] { ... });
Spring MVC – Advanced topics

Annotation driven controllers
@ModelAttribute
» Session attribute binding
@Controller
@SessionAttributes("userDetails");
public class ValidateUserFormController {

    // UserDetails instance is extracted from the session.
    @RequestMapping(method = RequestMethod.GET)
    public String validateForm(@ModelAttribute("userDetails") UserDetails details) {
        // ...
    }
}
Spring MVC – Advanced topics

Annotation driven controllers
@CookieValue, @HeaderValue
» @CookieValue provide access to client-side cookies.
» @HeaderValue provide access to HTTP request header
  values.
Spring MVC – Advanced topics

Annotation driven controllers
@DateTimeFormat
» Allow conversion of a string to date-class type.
    long/java.lang.Long,
    java.util.Date, java.sql.Date,
     java.util.Calendar,
    Joda time
» Applies to @RequstParam and @PathVariable
» Support various conventions.
Spring MVC – Advanced topics

Annotation driven controllers
@DateTimeFormat

@Controller
public class CheckDatesRangeController {

    // http://host.com/checkDate?birthDate=1975/02/31
    @RequestMapping
    public String checkDateRange(
        @RequestParam("birthdate")
        @DateTimeFormat(pattren = "yyyy/mm/dd") Date birthDate) {
        // ...
    }
}
Spring MVC – Advanced topics

Annotation driven controllers
@RequestBody
» Provide access to HTTP request body.
@Controller
public class PersistCommentController {

    @RequestMapping(method = RequestMethod.POST)
    public String checkDateRange(@RequestBody String contents) {
        // ...
    }
}


» Also supported:
     Byte array, Form, javax.xml.transform.Source
Spring MVC – Advanced topics

Annotation driven controllers
@ResponseBody
» Convert return value to HTTP response body.
@Controller
public class FetchCommentController {

    @RequestMapping
    @ResponseBody
    public String fetchComment(@RequestMapping (‚commentId") int commentId) {
        // ...
    }

    @RequestMapping
    @ResponseBody
    public byte[] fetchAsBinary(@RequestMapping (‚commentId") int commentId) {
        // ...
    }
}
Arguments and return
      types
Spring MVC – Advanced topics

Arguments and return types


@Controller
public class SomeController {

    @RequestMapping
    public String someMethod(...) { ... }

}




      Return                           Arguments
       value
Spring MVC – Advanced topics

Arguments and return types
Allowed arguments
» HttpServletRequest, HttpServletResponse, HttpSession
    Servlet API
» WebRequest, NativeWebRequest
    Spring framework API
» java.util.Locale
» java.io.InputStream, java.io.Reader
» java.io.OutputStream, java.io.Writer
Spring MVC – Advanced topics

Arguments and return types
Allowed arguments
» java.security.Principle
» HttpEntity
    Spring framework API
» java.util.Map, Model, ModelMap
    Allow access to the current model.
» Errors, BindingResult
Spring MVC – Advanced topics

Arguments and return types
Allowed return types
» ModelAndView, Model, java.util.Map, View
» String
    Represents a view name, if not specified otherwise.
» void
» HttpEntity<?>, ResponseEntity<?>
» Any other type that has a conversion.
Validation
Spring MVC – Advanced topics

Validation
» Allow us to validate form in a discipline manner.
» Provide a convenient and consistent way to validate
  input.
» Support JSR-303 (not covered by this presentation).
Spring MVC – Advanced topics

Validation
Declaring binding process

@Controller
public class ValidateFormController {

    @RequestMapping
    public String validateForm(UserDetails details, Errors errors) {
        if (details.getFirstName() == null) {
            errors.rejectValue("firstName", null, "Missing first name.");
        }
    }
}
Spring MVC – Advanced topics

Validation
Declaring binding process

@Controller
public class ValidateFormController {

    @RequestMapping
    public String validateForm(UserDetails details, Errors errors) {
        ValidationUtils.rejectIfEmpty(errors,
                                      "firstName",
                                      null,
                                      "Missing first name.");
    }
}
Spring MVC – Advanced topics

Validation
Declaring binding process

<form:form action="form/validate.do" method="POST" modelAttribute="userDetails">

    <!-- Prompt for user input -->
    First name: <form:input path="firstName" />

    <!-- Display errors related to ‘firstName’ field -->
    <form:errors path="firstName"/>

</form:form>
Spring MVC – Advanced topics

Validation
JSR-303 based validation
» Spring framework support 3rd-party JSR-303
  integration.
» Requires additional artifacts JSR-303 spec artifacts.
» Requires RI (reference implementation)
    e.g: Hibernate Validation
Spring MVC – Advanced topics

Validation
JSR-303 based validation
@RequestMapping
public String validateForm(@Valid UserDetails details, Errors errors) { ... }



public class UserDetails {

    @NotNull // JSR-303 annotation.
    private String firstName;

    @Size(min = 2, max = 64) // JSR-303 annotations.
    private String lastName;

    @Min(1) @Max(12) // JSR-303 annotations.
    private int birthMonth;
}

Más contenido relacionado

La actualidad más candente (20)

Spring data presentation
Spring data presentationSpring data presentation
Spring data presentation
 
Spring User Guide
Spring User GuideSpring User Guide
Spring User Guide
 
Spring AOP in Nutshell
Spring AOP in Nutshell Spring AOP in Nutshell
Spring AOP in Nutshell
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Java Spring
Java SpringJava Spring
Java Spring
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Spring Boot Tutorial
Spring Boot TutorialSpring Boot Tutorial
Spring Boot Tutorial
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Spring Boot in Action
Spring Boot in Action Spring Boot in Action
Spring Boot in Action
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 

Destacado

Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVCGuy Nir
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Tuna Tore
 
Cluster imee de sousse
Cluster imee de sousseCluster imee de sousse
Cluster imee de sousseMariem Chaaben
 
Etude de-cas-cellule-de-veille
Etude de-cas-cellule-de-veilleEtude de-cas-cellule-de-veille
Etude de-cas-cellule-de-veilleMariem Chaaben
 
Spring 3 MVC CodeMash 2009
Spring 3 MVC   CodeMash 2009Spring 3 MVC   CodeMash 2009
Spring 3 MVC CodeMash 2009kensipe
 
Spring mvc my Faviourite Slide
Spring mvc my Faviourite SlideSpring mvc my Faviourite Slide
Spring mvc my Faviourite SlideDaniel Adenew
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questionsDhiraj Champawat
 
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorialsSpring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorialsRaghavan Mohan
 
Spring 3 Annotated Development
Spring 3 Annotated DevelopmentSpring 3 Annotated Development
Spring 3 Annotated Developmentkensipe
 
Spring @Transactional Explained
Spring @Transactional ExplainedSpring @Transactional Explained
Spring @Transactional ExplainedSmita Prasad
 
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
 
Spring MVC Architecture Tutorial
Spring MVC Architecture TutorialSpring MVC Architecture Tutorial
Spring MVC Architecture TutorialJava Success Point
 
MVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVCMVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVCAnton Krasnoshchok
 
Veille en médias sociaux
Veille en médias sociauxVeille en médias sociaux
Veille en médias sociauxSoulef riahi
 

Destacado (17)

Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVC
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Spring MVC Basics
Spring MVC BasicsSpring MVC Basics
Spring MVC Basics
 
Cluster imee de sousse
Cluster imee de sousseCluster imee de sousse
Cluster imee de sousse
 
Etude de-cas-cellule-de-veille
Etude de-cas-cellule-de-veilleEtude de-cas-cellule-de-veille
Etude de-cas-cellule-de-veille
 
Knowledge management
Knowledge managementKnowledge management
Knowledge management
 
Modele mvc
Modele mvcModele mvc
Modele mvc
 
Spring 3 MVC CodeMash 2009
Spring 3 MVC   CodeMash 2009Spring 3 MVC   CodeMash 2009
Spring 3 MVC CodeMash 2009
 
Spring mvc my Faviourite Slide
Spring mvc my Faviourite SlideSpring mvc my Faviourite Slide
Spring mvc my Faviourite Slide
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
 
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorialsSpring Web Service, Spring JMS, Eclipse & Maven tutorials
Spring Web Service, Spring JMS, Eclipse & Maven tutorials
 
Spring 3 Annotated Development
Spring 3 Annotated DevelopmentSpring 3 Annotated Development
Spring 3 Annotated Development
 
Spring @Transactional Explained
Spring @Transactional ExplainedSpring @Transactional Explained
Spring @Transactional Explained
 
What's new in Spring 3?
What's new in Spring 3?What's new in Spring 3?
What's new in Spring 3?
 
Spring MVC Architecture Tutorial
Spring MVC Architecture TutorialSpring MVC Architecture Tutorial
Spring MVC Architecture Tutorial
 
MVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVCMVC Pattern. Flex implementation of MVC
MVC Pattern. Flex implementation of MVC
 
Veille en médias sociaux
Veille en médias sociauxVeille en médias sociaux
Veille en médias sociaux
 

Similar a Spring 3.x - Spring MVC - Advanced topics

Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVCIndicThreads
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVCRichard Paul
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web FrameworkLuther Baker
 
Summer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and ScalaSummer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and Scalarostislav
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSam Brannen
 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0Matt Raible
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with SpringJoshua Long
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_HourDilip Patel
 
Применение паттерна Page Object для автоматизации веб сервисов
Применение паттерна Page Object для автоматизации веб сервисовПрименение паттерна Page Object для автоматизации веб сервисов
Применение паттерна Page Object для автоматизации веб сервисовCOMAQA.BY
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Michael Plöd
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web servicesnbuddharaju
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel.NET Conf UY
 
Spring MVC Annotations
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC AnnotationsJordan Silva
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with SpringJoshua Long
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 

Similar a Spring 3.x - Spring MVC - Advanced topics (20)

Day7
Day7Day7
Day7
 
Building RESTful applications using Spring MVC
Building RESTful applications using Spring MVCBuilding RESTful applications using Spring MVC
Building RESTful applications using Spring MVC
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web Framework
 
Codemotion appengine
Codemotion appengineCodemotion appengine
Codemotion appengine
 
Summer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and ScalaSummer - The HTML5 Library for Java and Scala
Summer - The HTML5 Library for Java and Scala
 
Spring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. RESTSpring Web Services: SOAP vs. REST
Spring Web Services: SOAP vs. REST
 
What's Coming in Spring 3.0
What's Coming in Spring 3.0What's Coming in Spring 3.0
What's Coming in Spring 3.0
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 
Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
Применение паттерна Page Object для автоматизации веб сервисов
Применение паттерна Page Object для автоматизации веб сервисовПрименение паттерна Page Object для автоматизации веб сервисов
Применение паттерна Page Object для автоматизации веб сервисов
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6
 
Overview of RESTful web services
Overview of RESTful web servicesOverview of RESTful web services
Overview of RESTful web services
 
Unit 07: Design Patterns and Frameworks (3/3)
Unit 07: Design Patterns and Frameworks (3/3)Unit 07: Design Patterns and Frameworks (3/3)
Unit 07: Design Patterns and Frameworks (3/3)
 
Building Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel AppelBuilding Modern Websites with ASP.NET by Rachel Appel
Building Modern Websites with ASP.NET by Rachel Appel
 
Spring MVC Annotations
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC Annotations
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 

Último

HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobeapidays
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...Martijn de Jong
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Último (20)

HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

Spring 3.x - Spring MVC - Advanced topics

  • 1. Spring MVC – Advanced topics Guy Nir January 2012
  • 2. Spring MVC Agenda » Annotation driven controllers » Arguments and return types » Validation
  • 3. Annotation driven controllers
  • 4. Spring MVC – Advanced topics Annotation driven controllers » @Controller » @RequestMapping (class-level and method-level) » @PathVariable (URI template) » @ModelAttribute (method-level, argument-level) » @CookieValue, @HeaderValue » @DateTimeFormat » @RequestBody » @ResponseBody
  • 5. Spring MVC – Advanced topics Annotation driven controllers @Controller » Spring stereotype that identify a class as being a Spring Bean. » Has an optional ‘value’ property. // Bean name is ‘loginController’ @Controller public class LoginController { } // Bean name is ‘portal’. @Controller(‚portal‛) public class PortalController { }
  • 6. Spring MVC – Advanced topics Annotation driven controllers @RequestMapping » Define URL mapping for a class and/or method. // Controller root URL: http://host.com/portal @Controller @RequestMapping(‚/portal‛) public class PortalController { // Handle [GET] http://host.com/portal @RequestMapping(method = RequestMethod.GET) public String enterPortal() { ... } // Handle [GET] http://host.com/portal/userProfile @RequestMapping(‚/userProfile‛) public String processUserProfileRequest() { ... } } » Support deterministic and Ant-style mapping
  • 7. Spring MVC – Advanced topics Annotation driven controllers @RequestMapping » Available properties:  method – List of supported HTTP method (GET, POST, ...).  produces/consumes – define expected content types. GET http://google.com/ HTTP/1.1 Accept: text/html, application/xhtml+xml, */* HTTP Accept-Language: he-IL request Accept-Encoding: gzip, deflate HTTP/1.1 200 OK Content-Type: text/html; charset=UTF-8 HTTP Date: Sun, 29 Jan 2012 19:45:21 GMT response Expires: Tue, 28 Feb 2012 19:45:21 GMT
  • 8. Spring MVC – Advanced topics Annotation driven controllers @RequestMapping @Controller @RequestMapping(‚/portal‛) public class UserInfoController { @RequestMapping(value = ‚/userInfo/xml‚, consumes = ‚application/json‛, produces = ‚application/xml‛) public UserInformation getUserInformationAsXML() { Requires message } converters @RequestMapping(value = ‚/userInfo/yaml‚, consumes = ‚application/json‛, produces = ‚application/Json‛) public UserInformation getUserInformationAsJSon() { } }
  • 9. Spring MVC – Advanced topics Annotation driven controllers @RequestMapping » Required parameters. // URL must in a form of: http://host.com/?userId=...&username=admin @RequestMapping(value = ‚/‚, params = { ‚userId‛, ‚username!=guest‛, ‚!password‛ }) public UserInformation getUserInformationAsXML() { } » Required headers @RequestMapping(value = ‚/userInfo‚, headers = { ‚Accept-Language=he-IL‛ }) public UserInformation getUserInformationAsXML() { } GET http://google.com/ HTTP/1.1 Accept-Language: he-IL Accept-Encoding: gzip, deflate
  • 10. Spring MVC – Advanced topics Annotation driven controllers URI templates (@PathVariable) » Allow us to define part of the URI as a template token. » Support regular expressions to narrow scope of values. » Only for simple types, java.lang.String or Date variant. » Throw TypeMismatchException on failure to convert. // Handle ‘userId’ with positive numbers only (0 or greater). @RequestMapping(‚/users/{userId:[0-9]+}) public void processUserRequest(@PathVariable(‚userId‛) int userId) { ... } // Handle ‘userId’ with negative numbers only. @RequestMapping(‚/users/{userId:-[0-9]+}) public void processUserRequest(@PathVariable(‚userId‛) int userId) { ... }
  • 11. Spring MVC – Advanced topics Annotation driven controllers @ModelAttribute » Define a new model attribute.  Single attribute approach  Multiple attributes approach » Access existing model attribute.
  • 12. Spring MVC – Advanced topics Annotation driven controllers @ModelAttribute » Definition of a single model attribute @Controller public class PrepareFormController @Override public ModelAndView prepareForm() { ModelAndView mav = new ModelAndView("details"); mav.addObject("userDetails", new UserDetails()); mav.addObject("months", createIntegerList(1, 12)); mav.addObject("years", createIntegerList(1940, 2011)); return mav; } }
  • 13. Spring MVC – Advanced topics Annotation driven controllers @ModelAttribute » Definition of a single model attribute @Controller public class PrepareFormController @ModelAttribute("userDetails") public UserDetails newUserDetails() { return new UserDetails(); } @ModelAttribute("months") public int[] getMonthList() { return new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; } }
  • 14. Spring MVC – Advanced topics Annotation driven controllers @ModelAttribute » Definition of a single model attribute @Controller public class ValidateUserFormController @RequestMapping(method = RequestMethod.GET) public String validateForm(HttpServletRequest request, HttpServletResponse ...) { String firstName = request.getParameter(‚firstName‛); String lastName = request.getParameter(‚lastName‛); // ... } }
  • 15. Spring MVC – Advanced topics Annotation driven controllers @ModelAttribute » Definition of a single model attribute @Controller public class ValidateUserFormController @RequestMapping(method = RequestMethod.GET) public String validateForm(@ModelAttribute("userDetails") UserDetails details) { // ... } @ModelAttribute("userDetails") public UserDetails getUserDetails(HttpServletRequest request) { UserDetails user = new UserDetails(); user.setFirstName(request.getParameter("firstName")); return user; } }
  • 16. Spring MVC – Advanced topics Annotation driven controllers @ModelAttribute » Definition of a single model attribute public class UserFormControllerTest { @Test public void testValidateForm() { UserFormController formController = new UserFormController(); UserDetails userDetails = new UserDetails(); // ... // Simple way to test a method. String viewName = formController.validateForm(userDetails); Assert.assertEquals("OK", viewName); } }
  • 17. Spring MVC – Advanced topics Annotation driven controllers @ModelAttribute » Definition of a multiple model attribute @ModelAttribute("months") public int[] getMonthList() { return new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 }; } @ModelAttribute("months") public int[] getYears() { return new int[] { 1940, 1941, ... }; } @ModelAttribute public void populateAllAttributes(Model model, HttpServletRequest ...) { model.addAttribute(‚years", new int[] { ... }); model.addAttribute(‚months", new int[] { ... });
  • 18. Spring MVC – Advanced topics Annotation driven controllers @ModelAttribute » Session attribute binding @Controller @SessionAttributes("userDetails"); public class ValidateUserFormController { // UserDetails instance is extracted from the session. @RequestMapping(method = RequestMethod.GET) public String validateForm(@ModelAttribute("userDetails") UserDetails details) { // ... } }
  • 19. Spring MVC – Advanced topics Annotation driven controllers @CookieValue, @HeaderValue » @CookieValue provide access to client-side cookies. » @HeaderValue provide access to HTTP request header values.
  • 20. Spring MVC – Advanced topics Annotation driven controllers @DateTimeFormat » Allow conversion of a string to date-class type.  long/java.lang.Long,  java.util.Date, java.sql.Date, java.util.Calendar,  Joda time » Applies to @RequstParam and @PathVariable » Support various conventions.
  • 21. Spring MVC – Advanced topics Annotation driven controllers @DateTimeFormat @Controller public class CheckDatesRangeController { // http://host.com/checkDate?birthDate=1975/02/31 @RequestMapping public String checkDateRange( @RequestParam("birthdate") @DateTimeFormat(pattren = "yyyy/mm/dd") Date birthDate) { // ... } }
  • 22. Spring MVC – Advanced topics Annotation driven controllers @RequestBody » Provide access to HTTP request body. @Controller public class PersistCommentController { @RequestMapping(method = RequestMethod.POST) public String checkDateRange(@RequestBody String contents) { // ... } } » Also supported:  Byte array, Form, javax.xml.transform.Source
  • 23. Spring MVC – Advanced topics Annotation driven controllers @ResponseBody » Convert return value to HTTP response body. @Controller public class FetchCommentController { @RequestMapping @ResponseBody public String fetchComment(@RequestMapping (‚commentId") int commentId) { // ... } @RequestMapping @ResponseBody public byte[] fetchAsBinary(@RequestMapping (‚commentId") int commentId) { // ... } }
  • 25. Spring MVC – Advanced topics Arguments and return types @Controller public class SomeController { @RequestMapping public String someMethod(...) { ... } } Return Arguments value
  • 26. Spring MVC – Advanced topics Arguments and return types Allowed arguments » HttpServletRequest, HttpServletResponse, HttpSession  Servlet API » WebRequest, NativeWebRequest  Spring framework API » java.util.Locale » java.io.InputStream, java.io.Reader » java.io.OutputStream, java.io.Writer
  • 27. Spring MVC – Advanced topics Arguments and return types Allowed arguments » java.security.Principle » HttpEntity  Spring framework API » java.util.Map, Model, ModelMap  Allow access to the current model. » Errors, BindingResult
  • 28. Spring MVC – Advanced topics Arguments and return types Allowed return types » ModelAndView, Model, java.util.Map, View » String  Represents a view name, if not specified otherwise. » void » HttpEntity<?>, ResponseEntity<?> » Any other type that has a conversion.
  • 30. Spring MVC – Advanced topics Validation » Allow us to validate form in a discipline manner. » Provide a convenient and consistent way to validate input. » Support JSR-303 (not covered by this presentation).
  • 31. Spring MVC – Advanced topics Validation Declaring binding process @Controller public class ValidateFormController { @RequestMapping public String validateForm(UserDetails details, Errors errors) { if (details.getFirstName() == null) { errors.rejectValue("firstName", null, "Missing first name."); } } }
  • 32. Spring MVC – Advanced topics Validation Declaring binding process @Controller public class ValidateFormController { @RequestMapping public String validateForm(UserDetails details, Errors errors) { ValidationUtils.rejectIfEmpty(errors, "firstName", null, "Missing first name."); } }
  • 33. Spring MVC – Advanced topics Validation Declaring binding process <form:form action="form/validate.do" method="POST" modelAttribute="userDetails"> <!-- Prompt for user input --> First name: <form:input path="firstName" /> <!-- Display errors related to ‘firstName’ field --> <form:errors path="firstName"/> </form:form>
  • 34. Spring MVC – Advanced topics Validation JSR-303 based validation » Spring framework support 3rd-party JSR-303 integration. » Requires additional artifacts JSR-303 spec artifacts. » Requires RI (reference implementation)  e.g: Hibernate Validation
  • 35. Spring MVC – Advanced topics Validation JSR-303 based validation @RequestMapping public String validateForm(@Valid UserDetails details, Errors errors) { ... } public class UserDetails { @NotNull // JSR-303 annotation. private String firstName; @Size(min = 2, max = 64) // JSR-303 annotations. private String lastName; @Min(1) @Max(12) // JSR-303 annotations. private int birthMonth; }