SlideShare uma empresa Scribd logo
1 de 18
Baixar para ler offline
Spring MVC

 Richard Paul
Kiwiplan NZ Ltd
 27 Mar 2009
What is Spring MVC

Spring MVC is the web component of Spring's framework.

Model - The data required for the request.
View - Displays the page using the model.
Controller - Handles the request, generates the model.
Front Controller Pattern
Controller Interface

public class MyController implements Controller {
  public ModelAndView handleRequest(
      HttpServletRequest request,
      HttpServletResponse response) {

        // Controller logic goes here
    }
}


This is the low level interface for controllers, most of the time you will not use
the Controller interface directly.

The ModelAndView, is an object that holds the model objects as well as the
view required to be rendered (simplified definition).
Controller Annotations

@Controller
public class ItemController {

    private ItemService itemService;
    @Autowired
    public ItemController(ItemService itemService) {
      this.itemService = itemService;
    }

    @RequestMapping(value=quot;viewItem.htmquot;, method=RequestMethod.GET)
    public Item viewItem(@RequestParam Long id) {
      return itemService.get(id);
    }

}

By convention a view with the name 'viewItem' (based on the request mapping URL) will be
used to render the item.
Session attributes

@Controller
@RequestMapping(quot;editItem.htmquot;)
@SessionAttribute(quot;itemquot;)
public class ItemEditorController {

    @RequestMapping(method=RequestMethod.GET)
    public String setupForm(@RequestParam Long itemId, ModelMap model) {
      Item item = ...; // Fetch item to edit
      model.addAttribute(quot;itemquot;, item);
      return quot;itemFormquot;;
    }

    @RequestMapping(method=RequestMethod.POST)
    public String processSubmit(@ModelAttribute(quot;itemquot;) Item item) {
      // Store item
      // ...
      return quot;redirect:/viewItem.htm?item=quot; + item.getId();
    }
}

A GET to 'editItem.htm' adds the item with the given ID to the user's session. When a POST is made, this
item is pulled from the session and provided as an argument to the processSubmit method.
Flexible Method Arguments

Methods mapped with @RequestMapping can have very
flexible method signatures.
Arguments
handle(@RequestParam Long id) // 'id' parameter from request
handle(@ModelAttribute Item item, BindingResult result)
handle(ModelMap modelMap) // The model to populate
handle(HttpSession session) // The user's session
handle(Locale locale) // The locale (from the locale resolver)

Return Type
String // View name
ModelAndView // Model objects and view name
Item // Or other object, assumed to be the model object
void // This method handles writing to the response itself

http://static.springframework.org/spring/docs/2.5.x/reference/mvc.html#mvc-ann-
requestmapping-arguments
Testability

We no longer need to pass in a HttpServletRequest when unit
testing controllers. Most use cases can simply pass objects
into the method. Examples show with Mockito.

public Item view(@RequestParam Long id) {
  return itemService.get(id);
}

@Test
public void viewWithValidId() {
  Item item = new Item(3l);
  when(itemService.get(3l)).thenReturn(item);
  assertEquals(item, controller.view(3l));
}
Testability - with model attributes

public String submitItem(@ModelAttribute Item item) {
  itemService.save(item);
}

@Test
public void submitItem() {
  Item item = new Item(3l);
  controller.submitItem(item);
  verify(itemService.save(item));
}

Previously the item would have been manually placed into a
mock session under the 'item' key before calling the test.
Binding

In order to bind request parameters to Java objects, Spring
uses PropertyEditors.

Default Property Editors
                           // For Strings
ByteArrayPropertyEditor
                           // For numbers, e.g. 4, 3.2
CustomNumberEditor
...

Spring Provided Editors
                           // For whitespace trimmed Strings
StringTrimmerEditor
                           // For file uploads
FileEditor
...

Custom property editors can be written.
e.g. CategoryPropertyEditor for binding a Category.
Example - CategoryPropertyEditor

public class CategoryPropertyEditor extends PropertyEditorSupport {
  @Override
  public String getAsText() {
    Object value = getValue();
    if (value == null) {
      return quot;quot;;
    }
    return ((Category) value).getId().toString();
  }
  @Override
  public void setAsText(String text) {
    this.setValue(null); // Always clear existing value
    if (!StringUtils.isBlank(text)) {
      long id = Long.parseLong(text);
      this.setValue(categoryService.get(id));
    }
  }
}

If an IllegalArgumentException is thown a binding error is stored and can be
shown against the field in the form.
Registering Property Editors

Those property editors that aren't automatically wired up need
to be initialised against the DataBinder.

@InitBinder
public void initBinder(DataBinder binder) {
  // Register a new editor each time as they are not thread safe
  binder.registerCustomEditor(
    Category.class, new CategoryPropertyEditor());
}
Validation

Spring provides a validation framework that is usually invoked
in the controller layer.

Also possible to register different editors based on the field.

An alternative, which is still in draft form is JSR-303. It provides
validation at a model level and can be used in the presentation,
business & persistence layers.
Example - ItemValidator

Spring validator example.

public class ItemValidator implements Validator {

    public boolean supports(Class clazz) {
      return Item.class.isAssignableFrom(clazz);
    }

    public void validate(Object target, Errors errors) {
      Item item = (Item) target;
      ValidationUtils.rejectIfEmpty(e, quot;namequot;, quot;name.emptyquot;);
      if (item.getCategory() == null) {
        e.rejectValue(quot;categoryquot;, quot;item.category.requiredquot;);
      }
    }
}

Errors are stored in the Errors object, if any errors are present, the form can be
redisplayed with error messages instead of following the normal form submission.
Views

Spring supports a number of view technologies, the below
example shows JSP with JSTL, specifically Spring's Form tags.
<form:form method=quot;postquot; commandName=quot;itemquot;>
  <form:label path=quot;namequot;>Name</form:label>
  <form:input path=quot;namequot;/>
  <!-- Binding & Validation errors displayed here -->
  <form:error path=quot;namequot; cssClass=quot;errorquot;/>

  <!-- Show a select list of categories. Categories already set
       on the item are automatically selected -->
  <form:select path=quot;categoriesquot; items=quot;${allCategories}quot;
    itemValue=quot;idquot; itemLabel=quot;namequot;/>

</form:form>

Form tags are include for all HTML input types, e.g. form:radio, form:textarea
Resolving Messages

Spring resolves all messages using MessageSource interface.

This message source is uses dot notation to access message
coes. e.g. item.name.required

Using springs default MessageSource, properties files using a
specific locale are used.
ApplicationResources.properties      // Fall back
ApplicationResources_en.properties   // English
ApplicationResources_es.properties   // Spanish


Custom implementations of MessageSource can be
written. Useful if messages are pulled from a different backend
e.g. XML
AJAX Support

AJAX support is limited in Spring 2.5

Generally use a separate library to generate JSON data for the
controller to return.

Hopefully better support will be coming with Spring 3.0 with
new view types for XML, JSON, etc.
Questions?




Spring Reference
http://static.springframework.org/spring/docs/2.5.x/reference/

Mais conteúdo relacionado

Mais procurados

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 MVC
Spring MVCSpring MVC
Spring MVCyuvalb
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet MVCJohn Lewis
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVCDzmitry Naskou
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892Tuna Tore
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCJohn Lewis
 
ASP.NET Routing & MVC
ASP.NET Routing & MVCASP.NET Routing & MVC
ASP.NET Routing & MVCEmad Alashi
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedBG Java EE Course
 
Spray - Build RESTfull services in scala
Spray - Build RESTfull services in scalaSpray - Build RESTfull services in scala
Spray - Build RESTfull services in scalaSandeep Purohit
 

Mais procurados (19)

SpringMVC
SpringMVCSpringMVC
SpringMVC
 
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 4 Web App
Spring 4 Web AppSpring 4 Web App
Spring 4 Web App
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Spring Portlet MVC
Spring Portlet MVCSpring Portlet MVC
Spring Portlet 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)
 
Spring annotation
Spring annotationSpring annotation
Spring annotation
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Spring Framework - MVC
Spring Framework - MVCSpring Framework - MVC
Spring Framework - MVC
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
Struts,Jsp,Servlet
Struts,Jsp,ServletStruts,Jsp,Servlet
Struts,Jsp,Servlet
 
Annotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVCAnnotation-Based Spring Portlet MVC
Annotation-Based Spring Portlet MVC
 
ASP.NET Routing & MVC
ASP.NET Routing & MVCASP.NET Routing & MVC
ASP.NET Routing & MVC
 
Java Server Faces (JSF) - advanced
Java Server Faces (JSF) - advancedJava Server Faces (JSF) - advanced
Java Server Faces (JSF) - advanced
 
Backbone js
Backbone jsBackbone js
Backbone js
 
Spring mvc
Spring mvcSpring mvc
Spring mvc
 
Jinal desai .net
Jinal desai .netJinal desai .net
Jinal desai .net
 
Spray - Build RESTfull services in scala
Spray - Build RESTfull services in scalaSpray - Build RESTfull services in scala
Spray - Build RESTfull services in scala
 

Destaque

Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework Serhat Can
 
Spring MVC - The Basics
Spring MVC -  The BasicsSpring MVC -  The Basics
Spring MVC - The BasicsIlio Catallo
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - CoreDzmitry Naskou
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCFunnelll
 
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 3 Annotated Development
Spring 3 Annotated DevelopmentSpring 3 Annotated Development
Spring 3 Annotated Developmentkensipe
 
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 @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
 
Spring rest-doc-2015-11
Spring rest-doc-2015-11Spring rest-doc-2015-11
Spring rest-doc-2015-11Eric Ahn
 
Spring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerSpring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerZeroTurnaround
 

Destaque (15)

Introduction to Spring Framework
Introduction to Spring FrameworkIntroduction to Spring Framework
Introduction to Spring Framework
 
Spring MVC - The Basics
Spring MVC -  The BasicsSpring MVC -  The Basics
Spring MVC - The Basics
 
Spring Framework - Core
Spring Framework - CoreSpring Framework - Core
Spring Framework - Core
 
Spring ppt
Spring pptSpring ppt
Spring ppt
 
Introduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoCIntroduction to Spring Framework and Spring IoC
Introduction to Spring Framework and Spring IoC
 
Modeling and analysis
Modeling and analysisModeling and analysis
Modeling and analysis
 
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 3 Annotated Development
Spring 3 Annotated DevelopmentSpring 3 Annotated Development
Spring 3 Annotated Development
 
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 @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
 
Spring rest-doc-2015-11
Spring rest-doc-2015-11Spring rest-doc-2015-11
Spring rest-doc-2015-11
 
Spring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen HoellerSpring 4 on Java 8 by Juergen Hoeller
Spring 4 on Java 8 by Juergen Hoeller
 

Semelhante a Introduction to Spring MVC

Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc trainingicubesystem
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's NewTed Pennings
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2wiradikusuma
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_HourDilip Patel
 
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
 
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
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Matt Raible
 
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
 
Murach: How to transfer data from controllers
Murach: How to transfer data from controllersMurach: How to transfer data from controllers
Murach: How to transfer data from controllersMahmoudOHassouna
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4soelinn
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0Korhan Bircan
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web FrameworkLuther Baker
 

Semelhante a Introduction to Spring MVC (20)

Asp.NET MVC
Asp.NET MVCAsp.NET MVC
Asp.NET MVC
 
Asp.net mvc training
Asp.net mvc trainingAsp.net mvc training
Asp.net mvc training
 
Spring 3: What's New
Spring 3: What's NewSpring 3: What's New
Spring 3: What's New
 
Introducing Struts 2
Introducing Struts 2Introducing Struts 2
Introducing Struts 2
 
MVC & SQL_In_1_Hour
MVC & SQL_In_1_HourMVC & SQL_In_1_Hour
MVC & SQL_In_1_Hour
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
70562 (1)
70562 (1)70562 (1)
70562 (1)
 
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
 
Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6Integrating Wicket with Java EE 6
Integrating Wicket with Java EE 6
 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
 
Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2Migrating from Struts 1 to Struts 2
Migrating from Struts 1 to Struts 2
 
Backbone Basics with Examples
Backbone Basics with ExamplesBackbone Basics with Examples
Backbone Basics with Examples
 
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
 
Murach: How to transfer data from controllers
Murach: How to transfer data from controllersMurach: How to transfer data from controllers
Murach: How to transfer data from controllers
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
java ee 6 Petcatalog
java ee 6 Petcatalogjava ee 6 Petcatalog
java ee 6 Petcatalog
 
Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4Retrofit Web Forms with MVC & T4
Retrofit Web Forms with MVC & T4
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
 
Apache Wicket Web Framework
Apache Wicket Web FrameworkApache Wicket Web Framework
Apache Wicket Web Framework
 

Mais de Richard Paul

Cucumber on the JVM with Groovy
Cucumber on the JVM with GroovyCucumber on the JVM with Groovy
Cucumber on the JVM with GroovyRichard Paul
 
Acceptance testing with Geb
Acceptance testing with GebAcceptance testing with Geb
Acceptance testing with GebRichard Paul
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionRichard Paul
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing FundamentalsRichard Paul
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax BasicsRichard Paul
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with MockitoRichard Paul
 

Mais de Richard Paul (9)

Cucumber on the JVM with Groovy
Cucumber on the JVM with GroovyCucumber on the JVM with Groovy
Cucumber on the JVM with Groovy
 
Acceptance testing with Geb
Acceptance testing with GebAcceptance testing with Geb
Acceptance testing with Geb
 
Acceptance tests
Acceptance testsAcceptance tests
Acceptance tests
 
jQuery Behaviours
jQuery BehavioursjQuery Behaviours
jQuery Behaviours
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Unit Testing Fundamentals
Unit Testing FundamentalsUnit Testing Fundamentals
Unit Testing Fundamentals
 
Using Dojo
Using DojoUsing Dojo
Using Dojo
 
Javascript & Ajax Basics
Javascript & Ajax BasicsJavascript & Ajax Basics
Javascript & Ajax Basics
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 

Último

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
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
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
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
 
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
 
#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
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
🐬 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
 
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
 
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
 
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 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
 

Último (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
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
 
#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
 
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
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
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
 
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
 
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 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
 

Introduction to Spring MVC

  • 1. Spring MVC Richard Paul Kiwiplan NZ Ltd 27 Mar 2009
  • 2. What is Spring MVC Spring MVC is the web component of Spring's framework. Model - The data required for the request. View - Displays the page using the model. Controller - Handles the request, generates the model.
  • 4. Controller Interface public class MyController implements Controller { public ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response) { // Controller logic goes here } } This is the low level interface for controllers, most of the time you will not use the Controller interface directly. The ModelAndView, is an object that holds the model objects as well as the view required to be rendered (simplified definition).
  • 5. Controller Annotations @Controller public class ItemController { private ItemService itemService; @Autowired public ItemController(ItemService itemService) { this.itemService = itemService; } @RequestMapping(value=quot;viewItem.htmquot;, method=RequestMethod.GET) public Item viewItem(@RequestParam Long id) { return itemService.get(id); } } By convention a view with the name 'viewItem' (based on the request mapping URL) will be used to render the item.
  • 6. Session attributes @Controller @RequestMapping(quot;editItem.htmquot;) @SessionAttribute(quot;itemquot;) public class ItemEditorController { @RequestMapping(method=RequestMethod.GET) public String setupForm(@RequestParam Long itemId, ModelMap model) { Item item = ...; // Fetch item to edit model.addAttribute(quot;itemquot;, item); return quot;itemFormquot;; } @RequestMapping(method=RequestMethod.POST) public String processSubmit(@ModelAttribute(quot;itemquot;) Item item) { // Store item // ... return quot;redirect:/viewItem.htm?item=quot; + item.getId(); } } A GET to 'editItem.htm' adds the item with the given ID to the user's session. When a POST is made, this item is pulled from the session and provided as an argument to the processSubmit method.
  • 7. Flexible Method Arguments Methods mapped with @RequestMapping can have very flexible method signatures. Arguments handle(@RequestParam Long id) // 'id' parameter from request handle(@ModelAttribute Item item, BindingResult result) handle(ModelMap modelMap) // The model to populate handle(HttpSession session) // The user's session handle(Locale locale) // The locale (from the locale resolver) Return Type String // View name ModelAndView // Model objects and view name Item // Or other object, assumed to be the model object void // This method handles writing to the response itself http://static.springframework.org/spring/docs/2.5.x/reference/mvc.html#mvc-ann- requestmapping-arguments
  • 8. Testability We no longer need to pass in a HttpServletRequest when unit testing controllers. Most use cases can simply pass objects into the method. Examples show with Mockito. public Item view(@RequestParam Long id) { return itemService.get(id); } @Test public void viewWithValidId() { Item item = new Item(3l); when(itemService.get(3l)).thenReturn(item); assertEquals(item, controller.view(3l)); }
  • 9. Testability - with model attributes public String submitItem(@ModelAttribute Item item) { itemService.save(item); } @Test public void submitItem() { Item item = new Item(3l); controller.submitItem(item); verify(itemService.save(item)); } Previously the item would have been manually placed into a mock session under the 'item' key before calling the test.
  • 10. Binding In order to bind request parameters to Java objects, Spring uses PropertyEditors. Default Property Editors // For Strings ByteArrayPropertyEditor // For numbers, e.g. 4, 3.2 CustomNumberEditor ... Spring Provided Editors // For whitespace trimmed Strings StringTrimmerEditor // For file uploads FileEditor ... Custom property editors can be written. e.g. CategoryPropertyEditor for binding a Category.
  • 11. Example - CategoryPropertyEditor public class CategoryPropertyEditor extends PropertyEditorSupport { @Override public String getAsText() { Object value = getValue(); if (value == null) { return quot;quot;; } return ((Category) value).getId().toString(); } @Override public void setAsText(String text) { this.setValue(null); // Always clear existing value if (!StringUtils.isBlank(text)) { long id = Long.parseLong(text); this.setValue(categoryService.get(id)); } } } If an IllegalArgumentException is thown a binding error is stored and can be shown against the field in the form.
  • 12. Registering Property Editors Those property editors that aren't automatically wired up need to be initialised against the DataBinder. @InitBinder public void initBinder(DataBinder binder) { // Register a new editor each time as they are not thread safe binder.registerCustomEditor( Category.class, new CategoryPropertyEditor()); }
  • 13. Validation Spring provides a validation framework that is usually invoked in the controller layer. Also possible to register different editors based on the field. An alternative, which is still in draft form is JSR-303. It provides validation at a model level and can be used in the presentation, business & persistence layers.
  • 14. Example - ItemValidator Spring validator example. public class ItemValidator implements Validator { public boolean supports(Class clazz) { return Item.class.isAssignableFrom(clazz); } public void validate(Object target, Errors errors) { Item item = (Item) target; ValidationUtils.rejectIfEmpty(e, quot;namequot;, quot;name.emptyquot;); if (item.getCategory() == null) { e.rejectValue(quot;categoryquot;, quot;item.category.requiredquot;); } } } Errors are stored in the Errors object, if any errors are present, the form can be redisplayed with error messages instead of following the normal form submission.
  • 15. Views Spring supports a number of view technologies, the below example shows JSP with JSTL, specifically Spring's Form tags. <form:form method=quot;postquot; commandName=quot;itemquot;> <form:label path=quot;namequot;>Name</form:label> <form:input path=quot;namequot;/> <!-- Binding & Validation errors displayed here --> <form:error path=quot;namequot; cssClass=quot;errorquot;/> <!-- Show a select list of categories. Categories already set on the item are automatically selected --> <form:select path=quot;categoriesquot; items=quot;${allCategories}quot; itemValue=quot;idquot; itemLabel=quot;namequot;/> </form:form> Form tags are include for all HTML input types, e.g. form:radio, form:textarea
  • 16. Resolving Messages Spring resolves all messages using MessageSource interface. This message source is uses dot notation to access message coes. e.g. item.name.required Using springs default MessageSource, properties files using a specific locale are used. ApplicationResources.properties // Fall back ApplicationResources_en.properties // English ApplicationResources_es.properties // Spanish Custom implementations of MessageSource can be written. Useful if messages are pulled from a different backend e.g. XML
  • 17. AJAX Support AJAX support is limited in Spring 2.5 Generally use a separate library to generate JSON data for the controller to return. Hopefully better support will be coming with Spring 3.0 with new view types for XML, JSON, etc.