Training Notes - Chapter 5 Data Binding and Form Tag Library

Chapter 5. Data Binding and the Form Tag Library

  Part of the code for the saveProduct method of the ProductController class:

@RequestMapping(value="save-product")
public String saveProduct(ProductForm productForm, Model model) {
logger.info("saveProduct called");
// no need to create and instantiate a ProductForm
// create Product
Product product = new Product();
product.setName(productForm.getName());
product.setDescription(productForm.getDescription());
try {
product.setPrice(new BigDecimal(productForm.getPrice()));

} catch (NumberFormatException e) {

}

       With data binding in place, you can replace the saveProduct method section above with the following code.

       With data binding, there is no need for the ProductForm class nor for parsing the price property of the Product object.

Another benefit of data binding is that it regenerates an HTML form when input validation fails. handmade

When writing HTML code, it is necessary to repopulate the input fields with the values ​​that the user entered before. With Spring data binding

and form tag library, they will do the work for you.

Label:














Book 类:
package domain;
import java.math.BigDecimal;
import java.io.Serializable;
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
private long id;
private String isbn;
private String title;
private Category category;
private String author;
public Book() {
}
public Book(long id, String isbn, String title,
Category category, String author, BigDecimal price) {
this.id = id;
this.isbn = isbn;
this.title = title;
this.category = category;
this.author = author;
this.price = price;
}
// get and set methods not shown
}

Category 类
package domain;
import java.io.Serializable;
public class Category implements Serializable {
private static final long serialVersionUID = 1L;
private int id;
private String name;
public Category() {
}
public Category(int id, String name) {
this.id = id;
this.name = name;
}
// get and set methods not shown

}











Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324665221&siteId=291194637