实训小笔记之—第5 章 数据绑定和表单标签库

第5 章数据绑定和表单标签库

  ProductController 类的saveProduct 方法的部分代码:

@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) {

}

       有了数据绑定,就可以用下面的代码取代上面的saveProduct 方法部分。

       有了数据绑定,就不再需要ProductForm 类,也不需要解析Product 对象的price 属性了。

数据绑定的另一个好处是:当输入验证失败时,它会重新生成一个HTML 表单。手工编

写HTML 代码时,必须记着用户之前输入的值,重新填充输入字段。有了Spring 的数据绑定

和表单标签库后,它们就会替你完成这些工作。

标签:














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

}











猜你喜欢

转载自blog.csdn.net/H_yuxiang2018/article/details/80016970