SSM-CRUD

1、项目介绍

前端技术:query+Bootstrap+ajax+json前端

后端技术:SSM(spring、springMVC、mybatis)、JSR303校验mysql

数据库:mysqlgit

服务器:tomcat9.0github

项目内容:对员工和部门进行增删改查操做、用pageHelper插件实现分页功能、全选/全不选等。ajax

2、遇到的问题和解决方法

一、用pageHelper插件实现分页,pageSize=集合长度(pagehelper插件失效)spring

pageInfo源码中:sql

  1 if (list instanceof Collection) {
  2     this.pageNum = 1;
  3     this.pageSize = list.size();
  4     this.pages = this.pageSize > 0 ? 1 : 0;
  5     this.size = list.size();
  6     this.startRow = 0;
  7     this.endRow = list.size() > 0 ? list.size() - 1 : 0;
  8 }

错误缘由:pagehelper除了添加依赖,还须要在mybatis-config.xml中配置中添加拦截器PageInterceptor数据库

  1 <!-- https://mvnrepository.com/artifact/com.github.pagehelper/pagehelper -->
  2     <dependency>
  3       <groupId>com.github.pagehelper</groupId>
  4       <artifactId>pagehelper</artifactId>
  5       <version>5.1.10</version>
  6     </dependency>
  1 <!-- 配置mybatis分页插件PageHelper -->
  2 <plugins>
  3     <plugin interceptor="com.github.pagehelper.PageInterceptor">
  4         <!--分页参数合理化-->
  5         <property name="reasonable" value="true"/>
  6     </plugin>
  7 </plugins>

二、校验数据不仅仅只是前端校验,后端和数据库都须要校验json

对于一些重要数据,后端也须要校验,用的是spring支持的JSR303校验后端

  • 导入Hibernate-Valdator

  • 在pojo对象的字段上添加注解,例如:@Pattern是自定义的约束

      1 @Pattern(regexp = "(^[a-zA-Z0-9_-]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,5})",        message = "用户名必须是6-16位英文和数字或者2-5位中文的组合")
      2 private String empName;private String gender;
      3 //@Email
      4 @Pattern(regexp = "^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+(\\.[a-zA-Z0-9-]+)*\\.[a-zA-Z0-9]{2,6}$", message = "邮箱格式不正确!")
      5 private String email;
  • 获取字段和信息

  1 @ResponseBodypublic ResultData add(@Valid Employee employee, BindingResult result){
  2     //用map来封装校验信息
  3     Map<String,Object> map = new HashMap<>();
  4     List<FieldError> errors = result.getFieldErrors();
  5     for(FieldError e:errors){
  6         System.out.println("错误的字段名:"+e.getField());           	
            System.out.println("错误的信息:"+e.getDefaultMessage());                                                             map.put(e.getField(),e.getDefaultMessage());
  7     }
  8     return ResultData.fail().add("errorFields",map);
  9 }

3、总结

1566641558267[13]

[RiterWu](https://github.com/RiterWu/ssmcrud)

相关文章
相关标签/搜索