栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

当表单中仅使用少量属性时,将完整的模型对象发布到控制器

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

当表单中仅使用少量属性时,将完整的模型对象发布到控制器

您可能不希望将实体用作可能存在安全隐患的表单后备对象。例如,可以伪造一个恶意请求来设置一些不需要的属性。

因此,通常最好为每个要处理的表单创建一个显式的表单支持对象。这将需要您编写更多的代码,但同时也消除了一些常见的问题(例如您遇到的问题)。

使用表单支持对象时,处理程序看起来像:

请注意,我将

BPost
参数更改为
BPostForm

@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)public String editProcessPost(Model model, @PathVariable Integer id, @ModelAttribute BPostForm editPost) {    // fetch the original post    BPost post = bPostService.findById(editPost.getId());    // set the properties    post.setTitle(editPost.getTitle());    post.setDescription(editPost.getDescription());    post.setText(editPost.getText());    // update    bPostService.updatePost(post);    model.addAttribute("posts", bPostService.getPosts());    return "redirect:/";}

PS使用

bPostService.getPosts()
添加帖子到模型,并立即返回重定向似乎很没有意义;)

[编辑]验证

您可以使用Hibernate批注通过声明性验证或在中设置自定义验证器来验证表单支持对象

WebdataBinder

hibernate注释

使用Hibernate批注时,可以将任何批注放在字段或getter上。为了使这些验证生效,您需要做两件事。

  1. 注册一个验证器bean
    org.springframework.validation.beanvalidation.LocalValidatorFactoryBean
  2. 使用注释处理程序中表单支持对象的参数
    @valid

例:

public String editProcessPost(Model model, @PathVariable Integer id,@ModelAttribute @Valid BPostForm editPost, BindingResult result)

请注意,使用验证需要

BindingResult
在参数列表中出现,并且必须直接在支持对象之后。这
BindingResult
将是所有验证错误的容器。

定制验证器

自定义验证器还需要更多工作。您将需要先编写自己的内容。

MyPostValidator extends org.springframework.validation.Validator

编写验证器后,您可以将其添加到中

WebDataBinder

@InitBinderpublic void initBinder(WebDataBinder binder) {    binder.setValidator(new MyPostValidator());}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/443448.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号