SlideShare ist ein Scribd-Unternehmen logo
1 von 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;
}

Weitere ähnliche Inhalte

Was ist angesagt?

Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesGanesh Samarthyam
 
Spring boot
Spring bootSpring boot
Spring bootsdeeg
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootJosué Neis
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepGuo Albert
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework tola99
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Edureka!
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionRichard Paul
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafThymeleaf
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 

Was ist angesagt? (20)

Java 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional InterfacesJava 8 Lambda Built-in Functional Interfaces
Java 8 Lambda Built-in Functional Interfaces
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring boot
Spring bootSpring boot
Spring boot
 
PUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBootPUC SE Day 2019 - SpringBoot
PUC SE Day 2019 - SpringBoot
 
Java Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By StepJava Persistence API (JPA) Step By Step
Java Persistence API (JPA) Step By Step
 
Spring MVC 3.0 Framework
Spring MVC 3.0 FrameworkSpring MVC 3.0 Framework
Spring MVC 3.0 Framework
 
Spring framework core
Spring framework coreSpring framework core
Spring framework core
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Spring Framework
Spring Framework  Spring Framework
Spring Framework
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
15. DateTime API.ppt
15. DateTime API.ppt15. DateTime API.ppt
15. DateTime API.ppt
 
Java 8 Lambda and Streams
Java 8 Lambda and StreamsJava 8 Lambda and Streams
Java 8 Lambda and Streams
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
Lambda Expressions in Java | Java Lambda Tutorial | Java Certification Traini...
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with ThymeleafSpring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
Spring I/O 2012: Natural Templating in Spring MVC with Thymeleaf
 
Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring boot
Spring bootSpring boot
Spring boot
 

Andere mochten auch

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
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
 
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
 

Andere mochten auch (19)

Spring 3.x - Spring MVC
Spring 3.x - Spring MVCSpring 3.x - Spring MVC
Spring 3.x - Spring MVC
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web 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
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
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
 

Ähnlich wie 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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
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 Servicegiselly40
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
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.pdfEnterprise Knowledge
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 

Kürzlich hochgeladen (20)

Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
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
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
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
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
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
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 

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