Episode 2: Caregiver
In the previous episode the DHTMLX Spring Adatper was introduced, now it is time to take care of the object through validation.
Forms
Since version 2.0 the Spring framework includes a JSP tag library, to make writing HTML forms much easier. A typical HTML form written using Spring JSP form tags looks like the code below:
Spring FormForms
Since version 2.0 the Spring framework includes a JSP tag library, to make writing HTML forms much easier. A typical HTML form written using Spring JSP form tags looks like the code below:
- <%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
- <form:form id="book" method="post">
- <form:label path="author">Author:</form:label>
- <form:input path="author"/> <br/>
- <form:label path="title">Title:</form:label>
- <form:input path="title"/> <br/>
- <form:label path="price">Price:</form:label>
- <form:input path="price"/> <br/>
- <form:label path="sales">Sales:</form:label>
- <form:input path="sales"/> <br/>
- <input type="submit" value="Save">
- </form:form>
DHTMLX version 2.6 introduced the dhtmlxForm component in 2010, providing a flexible Javascript API to create rich form, process events and validate data. The version 3.0 released in July 2011 includes a new version of dhtmlxForm, supporting integration with dhtmlxCalendar and dhtmlxCombo, and new ways to position form controls to build sophisticated web forms. Below the Javascript code to create a DHTMLX form:
DHTMLX Form- <div id="form" style="width:280px;height:250px;"/>
- var form_struct = [
- { type: 'input', name: 'author' , value: '', label:'Author:'},
- { type: 'input', name: 'title' , value: '', label:'Title:'},
- { type: 'input', name: 'price' , value: '', label:'Price:'},
- { type: 'input', name: 'sales' , value: '', label:'Sales:'},
- { type: 'button', name: 'button_save', value:'Save' },
- ];
- var formObject = new dhtmlXForm("form",form_struct);
The DHTMLX Tag Library, a JSP Tag library created on top of the DHTMLX component framework, allows to create DHTMLX forms with a very similar syntax to Spring JSP form tags.
DHTMLX Tags Form- <%@ taglib prefix="dhtmlx" uri="http://www.mylaensys.com/dhtmlx" %>
- <dhtmlx:form name='book'>
- <dhtmlx:formInput name='author' label='Author:'/>
- <dhtmlx:formInput name='title' label='Title:'/>
- <dhtmlx:formInput name='price' label='Price:'/>
- <dhtmlx:formInput name='sales' label='Sales:'/>
- <dhtmlx:formButton name='button_save' value='Save'/>
- </dhtmlx:form>
The code example in this series uses the DHTMLX Tag Library version 1.6, a recent release which include some of the new features of DHTMLX 3.0. Of course it also works without the tags using the Javascript DHTMLX API.
Client Side Validation
The dhtmlxForm let you specify client validation rules at field level using the validate property. The DHTMLX Tag Library supports the validate property as attribute of the tag. Below the source code of the of the example form:
The dhtmlxForm let you specify client validation rules at field level using the validate property. The DHTMLX Tag Library supports the validate property as attribute of the tag. Below the source code of the of the example form:
- <%@ taglib prefix="dhtmlx" uri="http://www.mylaensys.com/dhtmlx" %>
- <dhtmlx:form name='form'>
- <dhtmlx:formHidden name='id'/>
- <dhtmlx:formLabel name="message" label="" labelWidth="470"/>
- <dhtmlx:formInput name='author' validate="NotEmpty"/>
- <dhtmlx:formLabel name="authorError" label=""/>
- <dhtmlx:formInput name='title' validate="NotEmpty"/>
- <dhtmlx:formLabel name="titleError" label=""/>
- <dhtmlx:formInput name='price' validate="ValidInteger"/>
- <dhtmlx:formInput name='sales' validate="ValidInteger"/>
- <dhtmlx:formLabel name="message" label="">
- <dhtmlx:formLabel name="dummy" label="" labelWidth="120"/>
- <dhtmlx:formNewColumn/>
- <dhtmlx:formButton name='button_upd' value='Update'/>
- <dhtmlx:formNewColumn/>
- <dhtmlx:formButton name='button_close' value='Close'/>
- </dhtmlx:formLabel>
- </dhtmlx:form>
In order to minimize the client to server data exchange, it is a 'user friendly' practice to perform client side validation before sending data to the server. I used the expression 'user friendly' because the client side validation can be easily bypassed.
Server Side Validation
Staring from release 3, Spring has introduced several enhancements to the validation framework, including Bean Validation API (JSR-303). It is possible to declare validation constraints using annotations. This example has been written to run on the Google App Engine (using JDO). In the Book class below, in addition to the validation, you will find the persistence annotations.
Book.java
Server Side Validation
Staring from release 3, Spring has introduced several enhancements to the validation framework, including Bean Validation API (JSR-303). It is possible to declare validation constraints using annotations. This example has been written to run on the Google App Engine (using JDO). In the Book class below, in addition to the validation, you will find the persistence annotations.
Book.java
- public class Book {
- @PrimaryKey
- @Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
- private Long id;
- @Persistent
- @NotEmpty
- @Size(min = 5, max = 20)
- private String author;
- @Persistent
- @NotEmpty
- @Size(min = 5, max = 20)
- @BookConstraint( message = "title already exists")
- private String title;
- @Persistent
- private Integer sales;
- @Persistent
- private Integer price;
- }
A custom constraint annotation BookConstraint has been added to the title attribute, in order to evaluate if the book already exists in the datastore. You can find additional information about writing custom constraint in Spring documentation.
BookConstraint.java
- @Documented
- @Retention(RetentionPolicy.RUNTIME)
- @Target({ElementType.METHOD,ElementType.FIELD,ElementType.ANNOTATION_TYPE })
- @Constraint(validatedBy = BookValidator.class)
- public @interface BookConstraint {
- String message() default "{some.error.code}";
- Class<?>[] groups() default {};
- Class<? extends Payload>[] payload() default {};
- }
- public class BookValidator implements ConstraintValidator<BookConstraint,String> {
- @Autowired
- private BookDao bookDao;
- @Override
- public void initialize(BookConstraint bookConstraint) {
- }
- @Override
- public boolean isValid(String title, ConstraintValidatorContext context) {
- return bookDao.findByTitle( title ).size() < 2;
- }
- }
After validation the BookController receives an instance of the Book class initialized with the form data and a BindingResult object containing the errors detected.
BookController.java
BookController.java
- @Controller
- public class BookController {
- @Autowired
- private BookService bookService;
- @RequestMapping(value = "/book", method = RequestMethod.POST)
- public @ResponseBody DefaultFormAdapter
- storeBook(@Valid @ModelAttribute Book book, BindingResult binding) {
- DefaultFormAdapter adapter = new DefaultFormAdapter(book,binding);
- if( adapter.hasValidData() ) {
- bookService.store(book);
- }
- return adapter;
- }
- }
The dhtmlxForm posts the data performing an Ajax request. To return the errors triggered by the validation, the DHTMLX Spring Adapter creates an XML message. Below a XML response example including one error message:
- <data>
- <action
- sid="42"
- type="invalid"
- field="title"
- message="error !">
- </action>
- </data>
On client side, the Javascript function getErrors parses the response message and sets the text on the error labels.
- function getErrors(form,response) {
- var errorList = new Array();
- $('action', response).each(function(i) {
- field = $(this).attr("field");
- if( field != undefined ) {
- message = $(this).attr("message");
- form.setValidateCss(field, false);
- form.setItemLabel(field + "Error" , message );
- errorList.push( field );
- }
- });
- return errorList;
- }
- form.attachEvent("onButtonClick", function(id) {
- if (id == "button_upd") {
- clearMessages();
- form.send('/app/book', function(loader, response) {
- errorList = getErrors( form , response );
- });
- }
- });
In the next episode, the design of the DHTMLX Spring adapter will be presented in detail. For those who can't wait the application, running on the Google App Engine, is available here.
Stay Tuned!
I got lot of ideas after reading this. Share more as similar to this. Thank you for shared this.
ReplyDeletecore java training in chennai
core java training
core java Training in Porur
C++ Training in Chennai
javascript training in chennai
Appium Training in Chennai
JMeter Training in Chennai
core java training in chennai
Thanks for sharing the content in a short and clear way.
ReplyDeleteIELTS Coaching in Mulund
IELTS Training in Mulund West
IELTS Courses in Mulund
IELTS Coaching Centres in Mulund
Spoken English Class in Chennai
Spoken English in Chennai
IELTS Coaching in Chennai
A IEEE project is an interrelated arrangement of exercises, having a positive beginning and end point and bringing about an interesting result in Engineering Colleges for a particular asset assignment working under a triple limitation - time, cost and execution. share some more info.
ReplyDeleteAi & Artificial Intelligence Course in Chennai
PHP Training in Chennai
Ethical Hacking Course in Chennai Blue Prism Training in Chennai
UiPath Training in Chennai
Mua vé tại Aivivu, tham khảo
ReplyDeleteVe may bay di My
vé máy bay huế hà nội hôm nay
vé máy bay huế đi sài gòn giá rẻ
vé máy bay giá rẻ hà nội nha trang
lich bay tu my ve vietnam
taxi sân bay giá rẻ
combo bamboo airway đi quy nhơn
jeetwin : best online casinos with the best bonuses!
ReplyDeletePlay 바카라사이트 for Free! JeetWin Casino | best online vua nhà cái casinos with the best jeetwin bonuses! ⭐ All sites that accept Paypal deposits in South Africa are legal!