返回介绍

5.1 数据绑定概览

发布于 2025-04-22 20:09:59 字数 1054 浏览 0 评论 0 收藏

基于 HTTP 的特性,所有 HTTP 请求参数的类型均为字符串。在前面的章节中,为了获取正确的产品价格,不得不将字符串解析成 BigDecimal 类型。为了便于复习,这里把第 4 章中 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) { }

之所以需要解析 ProductForm 中的 price 属性,是因为它是一个 String,却需要用 BigDecimal 来填充 Product 的 price 属性。有了数据绑定,就可以用下面的代码取代上面的 saveProduct 方法部分。

@RequestMapping(value="save-product")
public String saveProduct(Product product, Model model)

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

数据绑定的另一个好处是:当输入验证失败时,它会重新生成一个 HTML 表单。手工编写 HTML 代码时,必须记着用户之前输入的值,重新填充输入字段。有了 Spring 的数据绑定和表单标签库后,它们就会替你完成这些工作。

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。