SpringMVC和FreeMarker整合Hibernate-validator在页面渲染校验错误信息

xiaoxiao2021-02-28  3

1、整合背景 项目中使用了SpringMVC整合FreeMarker作为页面渲染,在后台管理端页面存在大量的form输入项,每个输入项在提交到Controller层时都需要对数据的有效性进行校验,工作量非常大而且繁琐。

2、校验框架 为了解决数据校验的问题,调研了一下Hibernate-validator,发现该框架功能非常的全面,能很好的解决我遇到的数据校验问题,官方文档:https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#validator-gettingstarted-createproject Hibernate-validator 的优势: 支持校验规则分组 支持国际化错误消息 支持错误的fail-fast模式:https://docs.jboss.org/hibernate/stable/validator/reference/en-US/html_single/#section-fail-fast 支持自定义校验注解

3、校验依赖包

<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.3.5.Final</version> </dependency> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>1.1.0.Final</version> </dependency>

4、示例代码

UserDemoDO .java

import com.jd.jdpetrol.dao.enums.YNEnum; import org.apache.ibatis.type.Alias; import org.hibernate.validator.constraints.NotBlank; import javax.validation.constraints.NotNull; @Alias("UserDemoDO") public class UserDemoDO { @NotNull private Long id; @NotBlank private String name; private YNEnum yn; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public YNEnum getYn() { return yn; } public void setYn(YNEnum yn) { this.yn = yn; } @Override public String toString() { final StringBuffer sb = new StringBuffer("UserDemo{"); sb.append("id=").append(id); sb.append(", name='").append(name).append('\''); sb.append('}'); return sb.toString(); } public static void main(String[] args) { String str = "/abc"; if (str.startsWith("/")) { System.out.println(str.substring(1)); } } } import java.util.HashMap; import java.util.Map; /** * Created by XFrame on 2016/1/29. */ public enum YNEnum { VALID(1, "有效"), INVALID(0, "无效"); YNEnum(Integer code, String desc) { this.code = code; this.desc = desc; } private Integer code; private String desc; private static Map<Integer, YNEnum> map = new HashMap<Integer, YNEnum>(); static { for (YNEnum ele : values()) { map.put(ele.code, ele); } } public static YNEnum getByCode(Integer code) { return map.get(code); } public Integer getCode() { return code; } public String getDesc() { return desc; } }

UserDemoController .java

@Controller @RequestMapping("/demo") public class UserDemoController { @RequestMapping("/user2") public String index(ModelMap model) {//UserDemoDO userVo UserDemoDO userVo = new UserDemoDO(); model.addAttribute("userDemoDO", userVo); return "userdemo/user2"; } @RequestMapping(value = "/user", method = POST) //@ResponseBody public ModelAndView addUser(@Validated UserDemoDO user, BindingResult br) { ModelAndView modelView = new ModelAndView(); modelView.setViewName("userdemo/user2"); //基础校验 if (br.hasErrors()) { return modelView; } user.setYn(YNEnum.VALID); //userDemoService.save(user); return modelView; } }

5、FreeeMarker 页面

<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>user demo</title> <style> .outer { margin-top: 20px; } </style> </head> <body> <#import "/spring.ftl" as spring/> <div class="outer"> <form action="/demo/user/" name="user" method="post"> <@spring.bind "userDemoDO.id" /> 用户Id:<input type="text" id="id" name="id"/> <br/> <@spring.showErrors "<br>"/> 用户名:<input type="text" id="name" name="name"/> <br/> <input type="submit" value="提交"> <br> <#if userDemoDO??> <@spring.bind "userDemoDO.id" /> <#--<@spring.showErrors "<br>"/>--> <@spring.bind "userDemoDO.name" /> <#list spring.status.errorMessages as error> <b>${error}</b> <br> </#list> <br>****************11****************<br> <@spring.bind "userDemoDO.*" /> <@spring.showErrors "<br>"/> </#if> -------------------- <br> <br> =====================333======================== </form> </div> </body> </html>

6、校验效果

7、解析错误信息的核心源代码 org.springframework.web.servlet.support.BindStatus

8、参考文章: http://yunzhu.iteye.com/blog/2088548 http://hualong.iteye.com/blog/2038092 http://blog.csdn.net/fengyong7723131/article/details/54668905 PDF 文档下载:https://pan.baidu.com/s/1htA4BAG

有问题欢迎加qq:787141854 交流

转载请注明原文地址: https://www.6miu.com/read-1750047.html

最新回复(0)