SSM整合
1. web工程搭建初始化
1.1创建webapp工程
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-QguhZdIr-1595636771137)(.\img\image-20200722174349545.png)]
1.2 编写工程信息
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-MwtVCIO0-1595636771151)(.\img\image-20200722174544315.png)]
1.3POM文件
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.3</version>
</dependency>
<!--mysql环境-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--spring整合jdbc-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--spring整合mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>2.0.3</version>
</dependency>
<!--druid连接池-->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.16</version>
</dependency>
<!--分页插件坐标-->
<dependency>
<groupId>com.github.pagehelper</groupId>
<artifactId>pagehelper</artifactId>
<version>5.1.2</version>
</dependency>
<!--springmvc环境-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
<!--jackson相关坐标3个-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<!--<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>-->
<!--servlet环境-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--junit单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<!--spring整合junit-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.1.9.RELEASE</version>
</dependency>
</dependencies>
<build>
<!--设置插件-->
<plugins>
<!--具体的插件配置-->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.1</version>
<configuration>
<port>80</port>
<path>/</path>
</configuration>
</plugin>
</plugins>
</build>
2. 工程基础代码编写
2.1基本工程结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KA9qvs0E-1595636771154)(.\img\image-20200722181108328.png)]
2.2 基本pojo
1)Student对象
public class Student {
private Integer id;
private String name;
private Integer age;
}
2) 通用返回对象
public class GeneralResult<T> {
private T data;
private Boolean flag;
private String msg;
private Integer code;
}
3. 初始化SpringMVC + Spring
3.1 web.xml编写
- 过滤器
- 中央控制器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
3.2 resources下添加spring-mvc.xml配置文件
- 包扫描
- 静态资源放行
- 注解驱动
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.itheima"/>
<mvc:default-servlet-handler/>
</beans>s
3.3 HelloController编写
- 在Controller包下添加HelloController,目的测试springMVC是否配置成功
@Controller
public class HelloController {
@RequestMapping("/hello")
@ResponseBody
public String hello() {
return "hello world";
}
}
3.4 此处启动Tomcat访问是否能够成功获得响应
3.5目前工程目录结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-tySvw4Xg-1595636771156)(.\img\image-20200722181545174.png)]
4. 整合mybatis
实现查询所有学生功能
4.1 完整工程结构
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yES1uRbG-1595636771158)(.\img\image-20200722183434385.png)]
4.2 编写StudentDao接口
public interface StudentDao {
List<Student> findAll();
}
4.3 StudentDao.xml映射文件
- 注意此文件必须在对应的接口权限定报名下
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.itheima.dao.StudentDao">
<select id="findAll" resultType="com.itheima.domain.Student">
select * from student
</select>
</mapper>
4.4 jdbc.properties文件
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://192.168.200.129:3307/db1
jdbc.username=root
jdbc.password=123456
4.5 spring配置文件中添加mybatis相关的三个bean
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven/>
<context:component-scan base-package="com.itheima"/>
<mvc:default-servlet-handler/>
<!--加载perperties配置文件的信息-->
<context:property-placeholder location="classpath:*.properties"/>
<!--加载druid资源-->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--spring整合mybatis后控制的创建连接用的对象-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.itheima.domain"/>
</bean>
<!--加载mybatis映射配置的扫描,将其作为spring的bean进行管理-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.dao"/>
</bean>
</beans>
4.6 SSM整合完成修改Controller测试
@Controller
public class HelloController {
@Autowired
private StudentDao studentDao;
@RequestMapping("/hello")
@ResponseBody
public List<Student> hello() {
return studentDao.findAll();
}
}
5,完整代码演示
-
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m4dGRqhy-1595636771160)(E:\每日讲课笔记\Spring\springMVCmd笔记\img3\1595505007755.png)]
-
控制层
-
package com.itheima.controller; import com.github.pagehelper.PageInfo; import com.itheima.dao.StudentDao; import com.itheima.domain.GeneralResult; import com.itheima.domain.Student; import com.itheima.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import java.util.List; @Controller public class StudentController { @Autowired private StudentService studentService; @RequestMapping("/hello") @ResponseBody public String hello() { return "hello world"; } @RequestMapping("/findAll") @ResponseBody public List<Student> findAll(){ //throw new RuntimeException("斗罗大陆");配合NomalException中的异常处理,返回给前端特定消息 return studentService.findAll(); } @RequestMapping("/save") @ResponseBody public GeneralResult save( Student student){ //只有想从请求体里面拿数据才用requestBody(也就是请求的请求体中封装的json数据), // 如果你想获取请求地址栏上写的参数(也就是地址栏手动输入携带的参数),就去掉requestBody。postman软件中可以很好体会 studentService.saveStudent(student); GeneralResult result=new GeneralResult(); result.setFlag(true); result.setMsg("林铭"); result.setCode(2000); return result; } @RequestMapping("/update") @ResponseBody public GeneralResult update(Student student){ studentService.updateStudent(student); GeneralResult result =new GeneralResult(); result.setFlag(true); result.setMsg("修改成功"); result.setCode(2200); return result; } @RequestMapping("/delete") @ResponseBody public GeneralResult delete(Integer id){ studentService.deleteStudent(id); GeneralResult result =new GeneralResult(); result.setFlag(true); result.setMsg("删除成功"); result.setCode(3200); return result; } @RequestMapping("/findpage") @ResponseBody//用内置转换器把结果转换成json字符串,所以别忘了加这个@ResponseBody public GeneralResult findpage(){ PageInfo finpage = studentService.finpage(); GeneralResult result =new GeneralResult(); result.setFlag(true); result.setMsg("删除成功"); result.setCode(3200); result.setData(finpage); return result; } }
-
dao层
-
package com.itheima.dao; import com.itheima.domain.Student; import java.util.List public interface StudentDao { List<Student> findAll(); int saveStudent(Student student); int updateStudent(Student student); int deleteStudent(Integer id); }
-
domain层
-
package com.itheima.domain; //定义统一的返回格式,返回给前端 public class GeneralResult<T> { private T data; private Boolean flag; private String msg; private Integer code; @Override public String toString() { return "GeneralResult{" + "data=" + data + ", flag=" + flag + ", msg='" + msg + '\'' + ", code=" + code + '}'; } public T getData() { return data; } public void setData(T data) { this.data = data; } public Boolean getFlag() { return flag; } public void setFlag(Boolean flag) { this.flag = flag; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } public Integer getCode() { return code; } public void setCode(Integer code) { this.code = code; } }
-
package com.itheima.domain; public class Student { private Integer id; private String name; private Integer age; @Override public String toString() { return "Student{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + '}'; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } }
-
exception
-
package com.itheima.exception; import com.itheima.domain.GeneralResult; import org.springframework.stereotype.Component; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; import org.springframework.web.bind.annotation.ResponseBody; @Component @ControllerAdvice//这个注解标记该类是异常处理类,只要一抛异常,就会在这处理 public class NomalException { @ExceptionHandler(Exception.class) @ResponseBody//让返回的数据解析成json格式返回,而不是页面 public GeneralResult handleException(Exception e){ GeneralResult result=new GeneralResult(); result.setFlag(false); result.setMsg(e.getMessage()); result.setCode(400001); return result; } }
-
service接口
-
package com.itheima.service; import com.github.pagehelper.PageInfo; import com.itheima.domain.Student; import org.springframework.transaction.annotation.Transactional; import java.util.List; public interface StudentService { List<Student> findAll(); @Transactional(readOnly = false) int saveStudent(Student student); @Transactional(readOnly = false) int updateStudent(Student student); @Transactional(readOnly = false) int deleteStudent(Integer id); PageInfo finpage(); }
-
service接口实现类
-
package com.itheima.service.impl; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.itheima.dao.StudentDao; import com.itheima.domain.Student; import com.itheima.service.StudentService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class StudentServiceImpl implements StudentService { @Autowired private StudentDao studentDao; @Override public List<Student> findAll() { return studentDao.findAll(); } @Override public int saveStudent(Student student) { return studentDao.saveStudent(student); } @Override public int updateStudent(Student student) { return studentDao.updateStudent(student); } @Override public int deleteStudent(Integer id) { return studentDao.deleteStudent(id); } @Override//分页查询,注意先查询再分页 public PageInfo finpage() { PageHelper.startPage(1,3); List<Student> all = studentDao.findAll(); PageInfo pageInfo=new PageInfo(all); return pageInfo; } }
-
applicationContext.xml
-
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd"> <!--配合下面开启事务使用,记得接口方法上也要开启注解事务--> <tx:annotation-driven transaction-manager="txManager"/> <!--开启bean注解扫描,这样就可以和spring-mvc扫描的地方区分开--> <context:component-scan base-package="com.itheima"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!--加载properties文件--> <context:property-placeholder location="classpath*:jdbc.properties"/> <!--数据源--> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"> <property name="driverClassName" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </bean> <!--整合mybatis到spring中--> <bean class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <property name="typeAliasesPackage" value="com.itheima.domain"/> <!--分页插件--> <property name="plugins"> <array> <bean class="com.github.pagehelper.PageInterceptor"> <property name="properties"> <props> <prop key="helperDialect">mysql</prop> <prop key="reasonable">true</prop> </props> </property> </bean> </array> </property> </bean> <!--映射扫描,加载上资源中的UserDao.xml--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.itheima.dao"/> </bean> <!--开启事务--> <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> </beans>
-
spring-mvc.xml
-
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan base-package="com.itheima.controller"/> <mvc:default-servlet-handler/> <mvc:annotation-driven/> </beans>
-
web.xml
-
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <!--启动服务器时,通过监听器加载spring运行环境,然后controller就可以使用bean了--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:applicationContext.xml</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <filter> <filter-name>CharacterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <servlet> <servlet-name>DispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath*:spring-mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>DispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
SSM额外功能
1. 分离mybatis整合相关的配置
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-CfCWiJfl-1595636771161)(.\img\image-20200723144514342.png)]
- 首先新建applicationContext.xml
<!--加载perperties配置文件的信息-->
<context:property-placeholder location="classpath:*.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--spring整合mybatis后控制的创建连接用的对象-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.itheima.domain"/>
</bean>
<!--加载mybatis映射配置的扫描,将其作为spring的bean进行管理-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.itheima.dao"/>
</bean>
- 修改web.xml,添加了一个listener,去加载spring整合mybatis的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:ApplicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:spring-mvc.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
- web.xml的内容
- listener, 加载mybatis相关的配置
- filter, 字符乱码问题
- dispatcherServlet, 中央控制器, 加载spring-mvc.xml配置文件
2. 事务没有配置
- 事务管理器
- 开启注解驱动
- 一下内容添加载ApplicationContext.xml文件中
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<tx:annotation-driven transaction-manager="txManager"/>
- 直接在需要的方法上添加@Transactional注解及可
@Override
@Transactional
public int saveStudent(Student student) {
return studentDao.saveStudent(student);
}
3. mybatis分页怎么配置
<!--spring整合mybatis后控制的创建连接用的对象-->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.itheima.domain"/>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor">
<property name="properties">
<props>
<prop key="helperDialect">mysql</prop>
<prop key="reasonable">true</prop>
</props>
</property>
</bean>
</array>
</property>
</bean>
3.统一异常处理
- ControllerAdvice
- ExceptionHandler
@Component
@ControllerAdvice
public class NormalException {
@ExceptionHandler(Exception.class)
@ResponseBody
public GeneralResult handleException(Exception ex) {
GeneralResult result = new GeneralResult();
result.setFlag(false);
result.setMsg(ex.getMessage());
return result;
}
}
4. springMVC配置文件中只扫描Controller
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-lAjoicL6-1595636771162)(.\img\image-20200723160427642.png)]
参数校验框架
使用步骤
-
导包
<!--导入校验的jsr303规范--> <dependency> <groupId>javax.validation</groupId> <artifactId>validation-api</artifactId> <version>2.0.1.Final</version> </dependency> <!--导入校验框架实现技术--> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>6.1.0.Final</version> </dependency>
-
@Valid标注在Controller放参数前面
@RequestMapping(value = "/addemployee")
public String addEmployee(@Valid Employee employee, Errors errors, Model m){
if(errors.hasErrors()){
List<FieldError> fieldErrors = errors.getFieldErrors();
System.out.println(fieldErrors.size());
for(FieldError error : fieldErrors){
System.out.println(error.getField());
System.out.println(error.getDefaultMessage());
m.addAttribute(error.getField(),error.getDefaultMessage());
}
return "addemployee.jsp";
}
return "success.jsp";
}
- 具体校验逻辑
public class Employee{
//设定校验器,设置校验不通过对应的消息,设定所参与的校验组
@NotBlank(message = "姓名不能为空")
private String name;//员工姓名
//一个属性可以添加多个校验器
@NotNull(message = "请输入您的年龄")
@Max(value = 60,message = "年龄最大值不允许超过60岁")
@Min(value = 18,message = "年龄最小值不允许低于18岁")
private Integer age;//员工年龄
-
如果校验出错会给Controller传入一个Errors参数
-
分组校验
-
Controller
@RequestMapping(value = "/login")
//使用@Valid开启校验,使用@Validated也可以开启校验
//Errors对象用于封装校验结果,如果不满足校验规则,对应的校验结果封装到该对象中,包含校验的属性名和校验不通过返回的消息
public String login(@Validated({GroupLogin.class}) Employee employee, Errors errors, Model m){
return "success.jsp";
}
@RequestMapping(value = "/update")
//使用@Valid开启校验,使用@Validated也可以开启校验
//Errors对象用于封装校验结果,如果不满足校验规则,对应的校验结果封装到该对象中,包含校验的属性名和校验不通过返回的消息
public String update(@Validated({GroupA.class}) Employee employee, Errors errors, Model m){
return "success.jsp";
}
- 实体对象
public class Employee{
//设定校验器,设置校验不通过对应的消息,设定所参与的校验组
@NotBlank(message = "姓名不能为空", groups = {GroupLogin.class, GroupA.class})
private String name;//员工姓名
//一个属性可以添加多个校验器
@NotNull(message = "请输入您的年龄", groups = {GroupLogin.class})
@Max(value = 60,message = "年龄最大值不允许超过60岁", groups = {GroupLogin.class})
@Min(value = 18,message = "年龄最小值不允许低于18岁", groups = {GroupLogin.class})
private Integer age;//员工年龄
}
-
如果校验出错会给Controller传入一个Errors参数
-
分组校验
-
Controller
@RequestMapping(value = "/login")
//使用@Valid开启校验,使用@Validated也可以开启校验
//Errors对象用于封装校验结果,如果不满足校验规则,对应的校验结果封装到该对象中,包含校验的属性名和校验不通过返回的消息
public String login(@Validated({GroupLogin.class}) Employee employee, Errors errors, Model m){
return "success.jsp";
}
@RequestMapping(value = "/update")
//使用@Valid开启校验,使用@Validated也可以开启校验
//Errors对象用于封装校验结果,如果不满足校验规则,对应的校验结果封装到该对象中,包含校验的属性名和校验不通过返回的消息
public String update(@Validated({GroupA.class}) Employee employee, Errors errors, Model m){
return "success.jsp";
}
- 实体对象
public class Employee{
//设定校验器,设置校验不通过对应的消息,设定所参与的校验组
@NotBlank(message = "姓名不能为空", groups = {GroupLogin.class, GroupA.class})
private String name;//员工姓名
//一个属性可以添加多个校验器
@NotNull(message = "请输入您的年龄", groups = {GroupLogin.class})
@Max(value = 60,message = "年龄最大值不允许超过60岁", groups = {GroupLogin.class})
@Min(value = 18,message = "年龄最小值不允许低于18岁", groups = {GroupLogin.class})
private Integer age;//员工年龄
}