SlideShare a Scribd company logo
1 of 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;
}

More Related Content

What's hot

Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
Jakub Kubrynski
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
habib_786
 

What's hot (20)

Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Asp.net MVC training session
Asp.net MVC training sessionAsp.net MVC training session
Asp.net MVC training session
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Introduction to Spring Boot!
Introduction to Spring Boot!Introduction to Spring Boot!
Introduction to Spring Boot!
 
Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Introduction to Java 11
Introduction to Java 11 Introduction to Java 11
Introduction to Java 11
 
Spring jdbc
Spring jdbcSpring jdbc
Spring jdbc
 
ASP.NET Web API
ASP.NET Web APIASP.NET Web API
ASP.NET Web API
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Introduction to Spring Boot
Introduction to Spring BootIntroduction to Spring Boot
Introduction to Spring Boot
 
Introduction to ASP.NET Core
Introduction to ASP.NET CoreIntroduction to ASP.NET Core
Introduction to ASP.NET Core
 
Asp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity FrameworkAsp.Net Core MVC with Entity Framework
Asp.Net Core MVC with Entity Framework
 

Viewers also liked

Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVC
Guy 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 HTML5
Tuna Tore
 
Spring mvc my Faviourite Slide
Spring mvc my Faviourite SlideSpring mvc my Faviourite Slide
Spring mvc my Faviourite Slide
Daniel Adenew
 
02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions02 java spring-hibernate-experience-questions
02 java spring-hibernate-experience-questions
Dhiraj Champawat
 

Viewers also liked (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 to Spring 3.x - Spring MVC - Advanced topics

MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
Dilip Patel
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
Tuna Tore
 

Similar to 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
 

Recently uploaded

Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
Joaquim Jorge
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
giselly40
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
Earley Information Science
 

Recently uploaded (20)

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
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
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...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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)
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
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
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
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?
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 

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; }