发表于: 2018-10-13 23:00:01

1 675


今天完成的事情:

一、完成接口的校验

  Springmvc本身没有校验功能,它使用hibernate的校验框架

添加 jar包

<!--接口校验-->
<!-- https://mvnrepository.com/artifact/javax.validation/validation-api -->
<dependency>
 <groupId>javax.validation</groupId>
 <artifactId>validation-api</artifactId>
 <version>1.1.0.Final</version>
</dependency>

<!-- https://mvnrepository.com/artifact/org.hibernate/hibernate-validator -->
<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-validator</artifactId>
 <version>4.3.0.Final</version>
</dependency>

在springmvc.xml中配置validator校验器

<!--配置validator校验器-->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
   <!-- 校验器,使用hibernate校验器 -->
   <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/>
   <!-- 指定校验使用的资源文件,在文件中配置校验错误信息,如果不指定则默认使用classpath下面的ValidationMessages.properties文件 -->
   <property name="validationMessageSource" ref="MessageSource"/>
</bean>


<bean id="MessageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
   <!-- 指定校验信息的资源文件的基本文件名称,不包括后缀,后缀默认是properties -->
   <property name="basename" value="Messages"/>

   <!-- 指定文件的编码 -->
   <property name="fileEncodings" value="utf8"></property>
   <!-- 对资源文件内容缓存的时间,单位秒 -->
   <property name="cacheSeconds" value="120"></property>
</bean>


将validator注册到适配器中

<mvc:annotation-driven  conversion-service="conversionService" validator="validator"/>

在classpath 路径 创建message.properties文件

该配置文件的作用就是存储校验失败时的提示文字信息的,也就是相当于将其提取出来放到配置文件中

student.name.notnull=请输入学生姓名
student.id.notnull=请输入学生的ID
student.school.notnull=请输入学生的毕业院校


在pojo中指定校验规则

public class Student {
   /**
   @NotEmpty 用在集合类上面
   @NotBlank 用在String上面
   @NotNull 用在基本类型上
    */
   @NotBlank(message = "学生姓名不能为空")
   private String name;
   private int qq;
   private String learn_type;
   private long entrance_time;
   private String school;
   @NotNull(message = "请填写id")
   private long id;
   private String daily_link;
   private String wish;
   private String senior;
   private String way;
   private long create_time;
   private long update_time;

controller中对其校验绑定进行使用

/**
* 根据姓名查询学生
*/
@RequestMapping(value="/findStudent",method = RequestMethod.GET)
public String findStudent(Model model, String name, @Validated Student student, BindingResult result){
   if (name==null && result.hasErrors()){
       List<ObjectError>allErrors=result.getAllErrors();
       for (ObjectError objectError:allErrors) {
           System.out.println(objectError.getDefaultMessage());
       }
       model.addAttribute("errors",allErrors);
       return "error";
   }
   List<Student> studentList=studentService.findStudentByName(name);
   System.out.println(studentList);
   model.addAttribute(studentList);
   return "select";
}

  1、@Validated作用就是将pojo内的注解数据校验规则(@NotNull等)生效,如果没有该注解的声明,pojo内有注解数据校验规则也不会生效

        2、BindingResult对象用来获取校验失败的信息(@NotNull中的message),与@Validated注解必须配对使用,一前一后

        3、代码中的逻辑应该很容易看懂,就是将result中所有的错误信息取出来,然后到原先的页面将错误信息进行显示,注意,要使用model对象,则需要在形参中声明Model model,然后菜能使用

jsp页面

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<% String path=request.getContextPath();
   String basePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%>
<html>
<head>
 <title>错误页面</title>
</head>
 <body>
 <h1 style="text-align: center">错误信息界面</h1>
  <c:if test="${errors!=null&& errors.size()>0}" >
<c:forEach items="${errors}" var="error">
${error.defaultMessage}<br/>
 </c:forEach>
</c:if>
<a href="<%=basePath%>/findAllStudent">返回用户界面</a>
 </body>
</html>


postman测试


明天完成的任务 

1、配置域名 

2、提交任务,深度思考



遇到的问题

1、无法读取都message.propertie文件  





返回列表 返回列表
评论

    分享到