基于SpringMVC的数据效验
引入Jar
pom文件:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.xxzc</groupId>
<artifactId>Spring_MVC_YanZheng</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>Spring_MVC_YanZheng Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<!-- SpringMVC核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.8.RELEASE</version>
</dependency>
<!-- 导入log4j jar 包 此包是我自己手动添加到我的仓库,如需下载,请查询Maven坐标,选择更换 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
<!-- hibernate效验 -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<finalName>Spring_MVC_YanZheng</finalName>
</build>
</project>
Web
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1">
<display-name>Spring_MVC_YanZheng</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>login.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 配置SpringMVC前端控制器 -->
<servlet>
<servlet-name>SpringMVC</servlet-name><!-- spring-webmvc-5.1.8.RELEASE.jar 包下的servlet:DispatcherServlet:前端控制器 -->
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param> <!-- contextConfigLocation:加载SpringMVC的配置文件(处理器映射器,处理器适配器,视图解析器等等) -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<!-- 两种方式 1. *.action :访问以.action结尾的,全部交由DispatcherServlet解析
2. / :所有访问交由DispatcherServlet解析
千万不能使用/*。会报错 -->
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
springmvc.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置处理器映射器,处理器适配器 -->
<!-- validator="validator" 向适配器中注入validator -->
<mvc:annotation-driven validator="validator"></mvc:annotation-driven>
<!-- 配置处理器:开启扫描 -->
<context:component-scan
base-package="com.xxzc.controller"></context:component-scan>
<!-- 配置视图解析器 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"></bean>
<!-- 校验器 --> <!-- 初始化LocalValidatorFactoryBean -->
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<!-- 指定校验器提供方的 -->
<property name="providerClass"
value="org.hibernate.validator.HibernateValidator" />
<!-- 效验错误使用的资源文件,在文件中配置错误信息。不指定默认是classpath下的ValidationMessageSource.properties -->
<!-- 也就是发现错误返回到页面的错误信息, -->
<property name="validationMessageSource" ref="messageSource"></property>
</bean>
<!-- 效验错误信息配置 -->
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<!-- basenames是ReloadableResourceBundleMessageSource中的一个属性:要求指定资源位置,这里是指定错误资源位置 -->
<property name="basenames">
<list>
<value>classpath:errorMessage</value>
</list>
</property>
<!-- 资源文件编码格式 -->
<!-- 设置默认编码格式为UTF-8 -->
<property name="defaultEncoding" value="utf-8"></property>
</bean>
</beans>
Pojo类
package com.xxzc.pojo;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class User {
//最小长度为1,最大是5,message:错误信息(指的是错误资源位置的那个classpath位置:{K})
@Size(min=1,max=5,message= "{User.username.lenght.error}")
private String username;
//不能为空,且长度大于0
@NotBlank(message="{User.pwd.isNull}")
private String pwd;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
errorMessage.properties(错误信息的配置文件,xml里面那个basenames的位置,还有Pojo里message的K。.properties文件里面是K-V形式)
#添加错误的效验提示信息
User.username.lenght.error=用户名长度仅限于1-5位
User.pwd.isNull=密码不能为空
UserHandler类
package com.xxzc.controller;
import java.io.UnsupportedEncodingException;
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.xxzc.pojo.User;
@Controller
public class UserHandler {
@RequestMapping(value="requestMapping.action",method= {RequestMethod.POST} )
//在需要效验的Pojo前面+@Validated, 后面+BindingResult bindingResult用于接收效验出错信息, 这两个是配对出现
public ModelAndView login(Model model, @Validated User user,BindingResult bindingResult) throws UnsupportedEncodingException {
//获取效验信息
if(bindingResult.hasErrors()) {
//如果有错误,输出错误信息
//获取所有错误信息
List<ObjectError> allErrors = bindingResult.getAllErrors();
//遍历错误信息
for (ObjectError objectError : allErrors) {
System.out.println(objectError.getDefaultMessage());
}
//将错误信息添加到作用域,传到页面
model.addAttribute("allErrors", allErrors);
ModelAndView andView = new ModelAndView();
andView.setViewName("login.jsp");
return andView;
}
System.out.println(user.getUsername());
System.out.println(user.getPwd());
ModelAndView andView = new ModelAndView();
andView.setViewName("success.jsp");
return andView;
}
}
小白还在学习中,可能有好多地方解释的不到位,但是我的理解是那个样子,希望也能帮到你,碰到问题多查查,多看看,我写的只能保证能运行,但不是最完美的。如果那里写错了,或者解释错了,请多多包涵!