SlideShare uma empresa 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;
}

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Spring boot Introduction
Spring boot IntroductionSpring boot Introduction
Spring boot Introduction
 
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
 
15. DateTime API.ppt
15. DateTime API.ppt15. DateTime API.ppt
15. DateTime API.ppt
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Java 8 - Features Overview
Java 8 - Features OverviewJava 8 - Features Overview
Java 8 - Features Overview
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of ControlJava Spring framework, Dependency Injection, DI, IoC, Inversion of Control
Java Spring framework, Dependency Injection, DI, IoC, Inversion of Control
 
Spring boot - an introduction
Spring boot - an introductionSpring boot - an introduction
Spring boot - an introduction
 
Spring boot introduction
Spring boot introductionSpring boot introduction
Spring boot introduction
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring boot
Spring bootSpring boot
Spring boot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Boot and REST API
Spring Boot and REST APISpring Boot and REST API
Spring Boot and REST API
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 
Java 8 features
Java 8 featuresJava 8 features
Java 8 features
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 

Destaque

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
 

Destaque (18)

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

Semelhante 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
 

Semelhante 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

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
 
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
 
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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilV3cube
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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.pptxEarley Information Science
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
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
 

Último (20)

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
 
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...
 
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
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
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
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 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
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
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
 

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