SlideShare uma empresa Scribd logo
1 de 35
Baixar para ler offline
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 MVC
Spring MVCSpring MVC
Spring MVC
 
Introduction to Spring MVC
Introduction to Spring MVCIntroduction to Spring MVC
Introduction to Spring MVC
 
Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)Spring MVC 3.0 Framework (sesson_2)
Spring MVC 3.0 Framework (sesson_2)
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
SpringMVC
SpringMVCSpringMVC
SpringMVC
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
Spring MVC Annotations
Spring MVC AnnotationsSpring MVC Annotations
Spring MVC Annotations
 
Spring 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
 
Java Server Faces (JSF) - Basics
Java Server Faces (JSF) - BasicsJava Server Faces (JSF) - Basics
Java Server Faces (JSF) - Basics
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
 
Spring Core
Spring CoreSpring Core
Spring Core
 
Spring MVC Framework
Spring MVC FrameworkSpring MVC Framework
Spring MVC Framework
 
Spring framework in depth
Spring framework in depthSpring framework in depth
Spring framework in depth
 
Struts,Jsp,Servlet
Struts,Jsp,ServletStruts,Jsp,Servlet
Struts,Jsp,Servlet
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Java Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC FrameworkJava Server Faces + Spring MVC Framework
Java Server Faces + Spring MVC Framework
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
 

Destaque

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
 
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 (13)

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?
 
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
 
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
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with SpringJoshua Long
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's NewTed Pennings
 
Introduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersIntroduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersAoteaStudios
 

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
 
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
 
Multi Client Development with Spring
Multi Client Development with SpringMulti Client Development with Spring
Multi Client Development with Spring
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
 
Introduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developersIntroduction to Backbone.js for Rails developers
Introduction to Backbone.js for Rails developers
 

Último

COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaborationbruanjhuli
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesMd Hossain Ali
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServiceRenan Moreira de Oliveira
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1DianaGray10
 
Spring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfSpring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfAnna Loughnan Colquhoun
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Websitedgelyza
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfAijun Zhang
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum ComputingGDSC PJATK
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfinfogdgmi
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesDavid Newbury
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsSeth Reyes
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxMatsuo Lab
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Adtran
 
Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?SANGHEE SHIN
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...DianaGray10
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIUdaiappa Ramachandran
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.YounusS2
 

Último (20)

COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online CollaborationCOMPUTER 10: Lesson 7 - File Storage and Online Collaboration
COMPUTER 10: Lesson 7 - File Storage and Online Collaboration
 
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just MinutesAI Fame Rush Review – Virtual Influencer Creation In Just Minutes
AI Fame Rush Review – Virtual Influencer Creation In Just Minutes
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer ServicePicPay - GenAI Finance Assistant - ChatGPT for Customer Service
PicPay - GenAI Finance Assistant - ChatGPT for Customer Service
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1UiPath Platform: The Backend Engine Powering Your Automation - Session 1
UiPath Platform: The Backend Engine Powering Your Automation - Session 1
 
Spring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdfSpring24-Release Overview - Wellingtion User Group-1.pdf
Spring24-Release Overview - Wellingtion User Group-1.pdf
 
COMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a WebsiteCOMPUTER 10 Lesson 8 - Building a Website
COMPUTER 10 Lesson 8 - Building a Website
 
Machine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdfMachine Learning Model Validation (Aijun Zhang 2024).pdf
Machine Learning Model Validation (Aijun Zhang 2024).pdf
 
Introduction to Quantum Computing
Introduction to Quantum ComputingIntroduction to Quantum Computing
Introduction to Quantum Computing
 
Videogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdfVideogame localization & technology_ how to enhance the power of translation.pdf
Videogame localization & technology_ how to enhance the power of translation.pdf
 
Linked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond OntologiesLinked Data in Production: Moving Beyond Ontologies
Linked Data in Production: Moving Beyond Ontologies
 
Computer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and HazardsComputer 10: Lesson 10 - Online Crimes and Hazards
Computer 10: Lesson 10 - Online Crimes and Hazards
 
Introduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptxIntroduction to Matsuo Laboratory (ENG).pptx
Introduction to Matsuo Laboratory (ENG).pptx
 
Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™Meet the new FSP 3000 M-Flex800™
Meet the new FSP 3000 M-Flex800™
 
Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?Do we need a new standard for visualizing the invisible?
Do we need a new standard for visualizing the invisible?
 
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
Connector Corner: Extending LLM automation use cases with UiPath GenAI connec...
 
RAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AIRAG Patterns and Vector Search in Generative AI
RAG Patterns and Vector Search in Generative AI
 
Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.Basic Building Blocks of Internet of Things.
Basic Building Blocks of Internet of Things.
 

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