Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Forms with Spring MVC Handling Form.

Slides:



Advertisements
Similar presentations
Copyright © 2008 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 10 Servlets and Java Server Pages.
Advertisements

JTX Overview Overview of Job Tracking for ArcGIS (JTX)
Web Development with Karsten Schulz Terp-Nielsen Master Principal Sales Consultant Oracle Denmark.
Apache Struts Technology
 Copyright Wipro Technologies JSP Ver 1.0 Page 1 Talent Transformation Java Server Pages.
Edoclite and Managing Client Engagements What is Edoclite? How is it used at IU? Development Process?
Feature requests for Case Manager By Spar Nord Bank A/S IBM Insight 2014 Spar Nord Bank A/S1.
Copyright © 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 13 Introduction to SQL Programming Techniques.
Struts1 Apache Struts Dr Jim Briggs. Struts2 What is Struts? Struts is an open source framework for building Java web applications Supports MVC/Model.
Spring MVC form handling annotation example
Apache Struts Technology A MVC Framework for Java Web Applications.
Session-01. Layers Struts 2 Framework The struts 2 framework is used to develop MVC-based web application. Struts 1.0 was released in June The.
1 Guide to JSP common functions 1.Including the libraries as per a Java class, e.g. not having to refer to java.util.Date 2.Accessing & using external.
Struts 2.0 an Overview ( )
UNIT-V The MVC architecture and Struts Framework.
Form Handling, Validation and Functions. Form Handling Forms are a graphical user interfaces (GUIs) that enables the interaction between users and servers.
1 Chính phủ điện tử TS. Phạm Văn Tính Khoa CNTT, ĐH Nông Lâm TP.HCM
BEST PRACTICES - Java By Configuration Use global-forwards/results Helps to avoid duplicate jsp files and redundancy forward mapping.
Chapter 5 Java Script And Forms JavaScript, Third Edition.
Internationalization and the Java Stack Part 1 Matt Wheeler.
CSM-Java Programming-I Spring,2005 Objects and Classes Overview Lesson - 1.
CSCI 6962: Server-side Design and Programming Validation Tools in Java Server Faces.
Eric Westfall – Indiana University Jeremy Hanson – Iowa State University Building Applications with the KNS.
Copyright © 2012 Accenture All Rights Reserved.Copyright © 2012 Accenture All Rights Reserved. Accenture, its logo, and High Performance Delivered are.
Internationalization and the Java Stack Matt Wheeler.
JavaServer Faces Jeff Schmitt October 5, Introduction to JSF Presents a standard framework for building presentation tiers for web applications.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Understanding the Bean Lifecycle An.
JSF Introduction Copyright © Liferay, Inc. All Rights Reserved. No material may be reproduced electronically or in print without written permission.
Internationalization in the Java Stack Matt Wheeler.
By: Saurabh Dixit.  Groovy server pages  Taglibs  Validators in grails.
Struts J2EE web application framework “ Model 2 ” Model View Controller Controller Servlet Key features XML metadata Struts taglib Simplified form validation.
Lecturer: Prof. Piero Fraternali, Teaching Assistant: Alessandro Bozzon, Advanced Web Technologies: Struts–
Fall CIS 764 Database Systems Design L8. Web ….
(Business) Process Centric Exchanges
Java Web Development with NetBeans IDE -- Kai Qian Chapter 5 JavaServer Faces (JSF) Technology.
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Module Name Subtitle.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Spring Remoting Simplifying.
JSF Framework Java Server Faces Presented by Songkran Totiya (6/10/2014)
SiD Workshop October 2013, SLACDmitry Onoprienko SiD Workshop SLAC, October 2013 Dmitry Onoprienko SLAC, SCA FreeHEP based software status: Jas 3, WIRED,
Introduction to Spring Web Flow Andrew Petro Software Developer Unicon, Inc. Jasig 2011 Westminster, CO 23 May 2011 © Copyright Unicon, Inc., Some.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Views Rendering custom views.
Chính phủ điện tử TS. Phạm Văn Tính Khoa CNTT, ĐH Nông Lâm TP.HCM
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Spring MVC Essentials Getting started.
1 Introduction to Servlets. Topics Web Applications and the Java Server. HTTP protocol. Servlets 2.
JAVA BEANS JSP - Standard Tag Library (JSTL) JAVA Enterprise Edition.
© FPT SOFTWARE – TRAINING MATERIAL – Internal use 04e-BM/NS/HDCV/FSOFT v2/3 JSP Application Models.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Testing Spring Applications Unit Testing.
Preface IIntroduction Objectives I-2 Course Overview I-3 1Oracle Application Development Framework Objectives 1-2 J2EE Platform 1-3 Benefits of the J2EE.
1 Copyright © 2004, Oracle. All rights reserved. Oracle Application Development Framework.
13 Copyright © 2004, Oracle. All rights reserved. Adding Validation and Error Handling.
11 Copyright © 2004, Oracle. All rights reserved. Customizing Actions.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Data Access with Spring.
Struts Framework Day-2 Ashok Chakravarti. DataSource Usage Sample Struts-config.xml …
1 Java Server Pages A Java Server Page is a file consisting of HTML or XML markup into which special tags and code blocks are inserted When the page is.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Overview of the Spring Framework Introducing.
Data transfer and type conversion One of the common tasks of the web application domain was moving and converting data from string-based HTTP to the various.
© 2006 Pearson Addison-Wesley. All rights reserved 1-1 Chapter 1 Review of Java Fundamentals.
Copyright 2008 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Developing Rich Web Applications with.
Text INTRODUCTION TO ASP.NET. InterComm Campaign Guidelines CONFIDENTIAL Simply Server side language Simplified page development model Modular, well-factored,
10 Copyright © 2004, Oracle. All rights reserved. Building ADF View Components.
Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Introduction to Spring Web Flow An Overview.
12 Copyright © 2004, Oracle. All rights reserved. Using ADF Struts Components.
SDJ INFOSOFT PVT. LTD. 2 BROWSERBROWSER JSP JavaBean DB Req Res Application Layer Enterprise server/Data Sources.
Apache Struts Technology A MVC Framework for Java Web Applications.
CS 562 Advanced Java and Internet Application Computer Warehouse Web Application By Team Alpha :-  Puja Mehta (102163)  Mona Nagpure (102147)
CS520 Web Programming Spring – Web MVC Chengyu Sun California State University, Los Angeles.
CS520 Web Programming Spring – Web MVC Chengyu Sun California State University, Los Angeles.
Internationalization
J2EE Lecture 7: Spring – Spring MVC
JavaServer Faces: The Fundamentals
Presentation transcript:

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. Forms with Spring MVC Handling Form Input

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 2 Topics in this Session Form Workflow Primer Spring MVC Form Processing APIs –DataBinder –Validator –Form UI Tag Library SimpleFormController

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 3 Topics in this Session Form Workflow Primer Spring MVC Form Processing APIs –DataBinder –Validator –Form UI Tag Library SimpleFormController

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 4 Form Workflow Primer Forms often create or edit entities For example –Create a Reward –Edit a Reward

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 5 Common Form Workflows Simple Form –The user completes the form in a single POST request Wizard Form –The user completes the form over multiple POST requests –More complicated since state needs to be managed between requests

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 6 Simple Form Workflows Simple form flows typically execute two actions –A setup action To prepare the form for display –A submit action To process the form submission Both actions should be executed by the same Controller –They are two steps in a single cohesive workflow

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 7 Common Form Action Behaviors Form setup behaviors –Load the form model object –Load any supporting form “reference data” Form submit behaviors –Bind form input to the model –Perform model validation –Call an application layer service to persist edits

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 8 /reward/edit.jsp model={reward} Editing an Existing Reward - Setup Action RewardController handle GET /reward/edit.htm?id=1 1 RewardAdminService lookupReward(1) 2 reward

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 9 Editing an Existing Reward - Submit Action with a “Error” Result RewardController handle POST /reward/edit.htm {invalidInput} /reward/edit.jsp model={reward, errors} 1 Input Validation Failed

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 10 Editing an Existing Reward - Submit Action with a “Success” Result RewardController handle POST /reward/edit.htm {validInput} redirect:/reward/show.htm model={id} 1 RewardAdminService updateReward(reward) 2

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 11 Topics in this Session Form Workflow Primer Spring MVC Form Processing APIs –DataBinder –Validator –Form UI Tag Library SimpleFormController

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 12 Spring MVC Form Processing APIs Spring MVC provides several libraries to help implement common form action behaviors Libraries are included to –Automate the binding of request parameters to model objects –Implement form validation logic –Render form input controls such as text fields and select boxes

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 13 DataBinder Generic utility class for setting property values onto a target object –Useful for binding HTTP request parameters onto the form model object Key features –Type conversion –Error management

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 14 DataBinder Usage Example HttpServletRequest source = … RewardForm target = new RewardForm(); ServletRequestDataBinder binder = new ServletRequestDataBinder(target); binder.bind(source); BindingResult result = binder.getBindingResult(); if (result.hasErrors()) { // do error processing } else { // do success processing } HttpServletRequest source = … RewardForm target = new RewardForm(); ServletRequestDataBinder binder = new ServletRequestDataBinder(target); binder.bind(source); BindingResult result = binder.getBindingResult(); if (result.hasErrors()) { // do error processing } else { // do success processing } Copies source request parameters to target Returned BindingResult tracks bind errors

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 15 String creditCard String userName String reason Money amount Date date ChangeInfo changeInfo RewardForm rewardForm Data Binding Behavior creditCard=“ ” amount=“$50.00” date=“2006/12/29” changeInfo.userName=“colin” changeInfo.reason=“Correction” creditCard=“ ” amount=“$50.00” date=“2006/12/29” changeInfo.userName=“colin” changeInfo.reason=“Correction” Source Request Parameters Target RewardForm … $50.00 colin Correction 2006/12/29

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 16 Property Paths The name of the request parameter maps to a property path on the target Java Bean Map and indexed collection paths are also supported

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 17 Property Path Examples changeInfo.reason=“Correction” getChangeInfo().setReason(“Correction”); specialsMap[“spring”].discount=“.5”; getSpecialsMap().get(“spring”).setDiscount(“.5”); fileList[2].name=“readme.txt” getFileList().get(2).setName(“readme.txt”); customerMap[“bob”].addressList[0].city=“Oslo” getCustomerMap().get(“bob”).getAddressList().get(0). setCity(“Oslo”);

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 18 Useful Data Binder Configuration Options setRequiredFields(String[]) –Configures the properties that must be present for each binding attempt setAllowedFields(String[]) –Configures the only properties allowed for binding registerCustomEditor(Class, PropertyEditor) –Installs custom type converters setBindingErrorProcessor(BindingErrorProcessor) –Allows for control over how binding exceptions are handled

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 19 Bind Error Processing A Data Binder generates binding errors for –Missing required fields (“missingField”) –Type conversion failures (“typeMismatch”) Errors are resolvable to messages in a Spring MessageSource

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 20 Bind Error Processing Example RewardForm target = new RewardForm(); ServletRequestDataBinder binder = new ServletRequestDataBinder(target, “rewardForm”); binder.setRequiredFields(new String[] { “creditCardNumber”, “amount”, “date” }); binder.registerCustomEditor(MonetaryAmount.class, new MonetaryAmountEditor()); RewardForm target = new RewardForm(); ServletRequestDataBinder binder = new ServletRequestDataBinder(target, “rewardForm”); binder.setRequiredFields(new String[] { “creditCardNumber”, “amount”, “date” }); binder.registerCustomEditor(MonetaryAmount.class, new MonetaryAmountEditor()); class RewardForm { String creditCardNumber; MonetaryAmount amount; Date date; } class RewardForm { String creditCardNumber; MonetaryAmount amount; Date date; } All fields are required Will convert string values to MonetaryAmount objects

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 21 Missing Field Scenario ServletRequest DataBinder DefaultBinding ErrorProcessor DefaultBinding ErrorProcessor process MissingFieldError (“amount”, bindingResult) MessageCodes Resolver MessageCodes Resolver resolve MessageCodes( “missingField”, “rewardForm”, “amount”) errorMsgCodes FieldError new(”amount”, errorMsgCodes) addError(fieldError) bind(request) amount=null

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 22 Type Mismatch Scenario ServletRequest DataBinder DefaultBinding ErrorProcessor DefaultBinding ErrorProcessor process Property AccessException (exception, bindingResult) MessageCodes Resolver MessageCodes Resolver resolve MessageCodes( “typeMismatch”, “rewardForm”, “amount”) errorMsgCodes FieldError new(“amount”, errorMsgCodes, “bogus”) addError(fieldError) bind(request) amount=“bogus”

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 23 Error Message Codes Resolution DefaultMessage CodesResolver DefaultMessage CodesResolver resolveMessageCodes (“typeMismatch”, “rewardForm”, “amount”) new String[] { “typeMismatch.rewardForm.amount”, “typeMismatch.amount”, “typeMismatch” }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 24 Error Message Resolution MessageSource getMessage(typeMismatch) typeMismatch.rewardForm.amount=Reward amount is of the wrong type typeMismatch.amount=The amount is of the wrong type typeMismatch=The type is wrong missingField=The field is required typeMismatch.rewardForm.amount=Reward amount is of the wrong type typeMismatch.amount=The amount is of the wrong type typeMismatch=The type is wrong missingField=The field is required errorMessages.properties_en “Reward amount is of the wrong type”

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 25 Validator Spring provides an API to perform form model validation –To exercise custom validation rules –To add errors on validation failures public interface Validator { void validate(Object target, Errors errors); }

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 26 Example Validator public class RewardFormValidator implements Validator { public boolean supports(Class clazz) { return RewardForm.class.isAssignableFrom(clazz); } public void validate(Object target, Errors errors) { RewardForm form = (RewardForm) target; String creditCardNumber = form.getCreditCardNumber(); if (!isNumeric(creditCardNumber)) { errors.rejectValue(“creditCardNumber”, “numeric”); } if (creditCardNumber.length() != 16) { errors.rejectValue(“creditCardNumber”, “length”, new Object[] { “16” }, “invalid creditCardNumber”); } } } FieldError code Error argumentDefault message

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 27 Pre-Built Validators Spring Validator integration is available for several popular validation frameworks Spring Modules is a good source for such extensions – Available validation extensions include –Apache Commons Validator Support –Valang, a declarative validation language

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 28 Form Tag Library Spring MVC provides a tag library for form UI development Simplifies rendering of bound form controls –Text fields, select boxes, check boxes, etc Also capable of rendering form error messages –Resolves error messages using the configured MessageSource

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 29 Example JSP Form Tag Usage Credit Card Number: … Import form tag library The name of the backing “form object” Renders all errors associated with the target object Renders all errors associated with the “creditCardNumber” property Renders text field bound to the “creditCardNumber” property

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 30 Exposing the Form Model to your Form Views Form actions must expose a “form model” for the form tags to render bound form data –Contains the “form object” and any binding errors Spring’s SimpleFormController can handle this automatically Or you can use a DataBinder directly

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 31 Exposing the Form Model for the Initial Display of a Form View public class RewardController extends MultiActionController { public ModelAndView newForm(HttpServletRequest request, HttpServletResponse response) throws Exception { RewardForm form = new RewardForm(); ServletRequestDataBinder binder = new ServletRequestDataBinder(form, “rewardForm”); binder.bind(request); ModelAndView result = new ModelAndView(“newReward”); result.addAllObjects(binder.getBindingResult().getModel()); return result; } public class RewardController extends MultiActionController { public ModelAndView newForm(HttpServletRequest request, HttpServletResponse response) throws Exception { RewardForm form = new RewardForm(); ServletRequestDataBinder binder = new ServletRequestDataBinder(form, “rewardForm”); binder.bind(request); ModelAndView result = new ModelAndView(“newReward”); result.addAllObjects(binder.getBindingResult().getModel()); return result; } … Matches Exposes a form model

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 32 Exposing the Form Model after Binding and Validation public ModelAndView create(HttpServletRequest request, HttpServletResponse response) throws Exception { RewardForm form = new RewardForm(); ServletRequestDataBinder binder = new ServletRequestDataBinder(form, “rewardForm”); binder.bind(request); BindingResult bindingResult = binder.getBindingResult(); ValidationUtils.invokeValidator(validator, form, bindingResult); Map model = bindingResult.getModel(); if (bindingResult.hasErrors()) { return new ModelAndView(“newReward”, model); } // we have valid input createNewReward(form); return new ModelAndView(“rewardCreated”, model); } public ModelAndView create(HttpServletRequest request, HttpServletResponse response) throws Exception { RewardForm form = new RewardForm(); ServletRequestDataBinder binder = new ServletRequestDataBinder(form, “rewardForm”); binder.bind(request); BindingResult bindingResult = binder.getBindingResult(); ValidationUtils.invokeValidator(validator, form, bindingResult); Map model = bindingResult.getModel(); if (bindingResult.hasErrors()) { return new ModelAndView(“newReward”, model); } // we have valid input createNewReward(form); return new ModelAndView(“rewardCreated”, model); } Prepares a form model Binds request parameters Redisplays form if errors occurred Validates form object

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 33 Available Form Tags

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 34 Topics in this Session Form Workflow Primer Spring MVC Form Processing APIs –DataBinder –Validator –Form UI Tag Library SimpleFormController

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 35 Implementing a Form Workflow Spring MVC provides the SimpleFormController as a base class for common form workflow MultiActionController may be used when more explicit control is needed Integration with Spring Web Flow is also available –Particularly suited for implementing wizards These classes make use of the data binding and validation building blocks previously discussed

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 36 Using SimpleFormController Extend SimpleFormController –Set properties in your constructor to configure it –Override hook methods as necessary to customize its workflow

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 37 Important SimpleFormController Properties setFormView(String) –Sets the view to render the form setSuccessView(String) –Sets the view to render after a successful form submit setCommandName(String) –Configures the name of the form model object referenced by the form view setCommandClass(Class) –Configures the form object class, for creating default instances to hold form values setValidator(Validator) –Configures the Validator to perform form validation

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 38 Important SimpleFormController Hooks formBackingObject(HttpServletRequest) – Returns the form object instance referenceData(HttpServletRequest) –Provides supporting data needed on the form initBinder(HttpServletRequest, ServletRequestDataBinder) –Configures the data binder used on setup and submit onSubmit(Object object) –Callback to persist edits of the “form backing object”

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 39 SimpleFormController Workflow request process form YES setup form NO isFormSubmission? protected boolean isFormSubmission(HttpServletRequest request) { return “POST”.equals(request.getMethod()); } protected boolean isFormSubmission(HttpServletRequest request) { return “POST”.equals(request.getMethod()); } Default implementation:

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 40 SimpleFormController: Setup Form GET request formBackingObject initBinder referenceData showForm create ‘commandClass’ instanceno-opreturn null (add nothing to model)display ‘formView’ Default implementations:

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. 41 SimpleFormController: Process Form POST request formBackingObject initBinder create ‘commandClass’ instance Default implementations: onBind onBindAndValidate binds validates hasErrors? showForm YES onSubmit NO no-op display ‘successView’

Copyright 2007 SpringSource. Copying, publishing or distributing without express written permission is prohibited. LAB Forms with Spring MVC