【Spring学习笔记-MVC-10】Spring MVC之数据校验
1.准备


<?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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
<!-- 扫描web包,应用Spring的注解 -->
<context:component-scan base-package="com.ll.web"/>
<!-- 配置视图解析器,将ModelAndView及字符串解析为具体的页面,默认优先级最低 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:viewClass="org.springframework.web.servlet.view.JstlView"
p:prefix="/jsp/"
p:suffix=".jsp" />
<!-- 设置数据校验、数据转换、数据格式化 -->
<mvc:annotation-driven validator="validator" conversion-service="conversionService"/>
<!-- 数据转换/数据格式化工厂bean -->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean" />
<!-- 设置校验工厂bean-采用hibernate实现的校验jar进行校验-并设置国际化资源显示错误信息 -->
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<!--不设置则默认为classpath下的 ValidationMessages.properties -->
<property name="validationMessageSource" ref="validatemessageSource" />
</bean>
<!-- 设置国际化资源显示错误信息 -->
<bean id="validatemessageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basename">
<list>
<value>classpath:valideMessages</value>
</list>
</property>
<property name="fileEncodings" value="utf-8" />
<property name="cacheSeconds" value="120" />
</bean>
</beans>

package com.ll.model;
import java.util.Date;
import javax.validation.constraints.DecimalMax;
import javax.validation.constraints.DecimalMin;
import javax.validation.constraints.Past;
import javax.validation.constraints.Pattern;
import org.hibernate.validator.constraints.Length;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.format.annotation.NumberFormat;
public class Person {
@Pattern(regexp="W{4,30}",message="{Pattern.person.username}")
private String username;
@Pattern(regexp="S{6,30}",message="{Pattern.person.passwd}")
private String passwd;
@Length(min=2,max=100,message="{Pattern.person.passwd}")
private String realName;
@Past(message="{Past.person.birthday}")
@DateTimeFormat(pattern="yyyy-MM-dd")
private Date birthday;
@DecimalMin(value="1000.00",message="{DecimalMin.person.salary}")
@DecimalMax(value="2500.00",message="{DecimalMax.person.salary}")
@NumberFormat(pattern="#,###.##")
private long salary;
public Person() {
super();
}
public Person(String username, String passwd, String realName) {
super();
this.username = username;
this.passwd = passwd;
this.realName = realName;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPasswd() {
return passwd;
}
public void setPasswd(String passwd) {
this.passwd = passwd;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public Date getBirthday() {
// DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
// return df.format(birthday);
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public long getSalary() {
return salary;
}
public void setSalary(long salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Person [username=" + username + ", passwd=" + passwd + "]";
}
}
4. 国际化资源文件
5. 控制层

package com.ll.web;
import java.security.NoSuchAlgorithmException;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.ll.model.Person;
/**
* @author Administrator
*
*/
@Controller
@RequestMapping(value = "/test")
public class TestController {
@ModelAttribute("person")
public Person initModelAttr() {
Person person = new Person();
return person;
}
/**
* 返回主页
* @return
*/
@RequestMapping(value = "/index.action")
public String index() {
return "regedit";
}
/**
* 1. 在入参对象前添加@Valid注解,同时在其后声明一个BindingResult的入参(必须紧随其后),
* 入参可以包含多个BindingResult参数;
* 2. 入参对象前添加@Valid注解:请求数据-->入参数据 ===>执行校验;
* 3. 这里@Valid在Person对象前声明,只会校验Person p入参,不会校验其他入参;
* 4. 概括起来:@Valid与BindingResult必须成对出现,且他们之间不允许声明其他入参;
* @param bindingResult :可判断是否存在错误
*/
@RequestMapping(value = "/FormattingTest")
public String conversionTest(@Valid @ModelAttribute("person") Person p,
BindingResult bindingResult) throws NoSuchAlgorithmException {
// 输出信息
System.out.println(p.getUsername() + " " + p.getPasswd() + " "
+ p.getRealName() + " " + " " + p.getBirthday() + " "
+ p.getSalary());
// 判断校验结果
if(bindingResult.hasErrors()){
System.out.println("数据校验有误");
return "regedit";
}else {
System.out.println("数据校验都正确");
return "success";
}
}
}
6. 前台
引入Spring的form标签:

在前台显示错误:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>数据校验</title>
<style>
.errorClass{color:red}
</style>
</head>
<body>
<form:form modelAttribute="person" action='FormattingTest.action' >
<form:errors path="*" cssClass="errorClass" element="div"/>
<table>
<tr>
<td>用户名:</td>
<td>
<form:errors path="username" cssClass="errorClass" element="div"/>
<form:input path="username" />
</td>
</tr>
<tr>
<td>密码:</td>
<td>
<form:errors path="passwd" cssClass="errorClass" element="div"/>
<form:password path="passwd" />
</td>
</tr>
<tr>
<td>真实名:</td>
<td>
<form:errors path="realName" cssClass="errorClass" element="div"/>
<form:input path="realName" />
</td>
</tr>
<tr>
<td>生日:</td>
<td>
<form:errors path="birthday" cssClass="errorClass" element="div"/>
<form:input path="birthday" />
</td>
</tr>
<tr>
<td>工资:</td>
<td>
<form:errors path="salary" cssClass="errorClass" element="div"/>
<form:input path="salary" />
</td>
</tr>
<tr>
<td colspan="2"><input type="submit" name="提交"/></td>
</tr>
</table>
</form:form>
</body>
</html>
7. 测试



附件列表
【Spring学习笔记-MVC-10】Spring MVC之数据校验的更多相关文章
- 【Spring学习笔记-MVC-4】SpringMVC返回Json数据-方式2
<Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...
- 【Spring学习笔记-MVC-3】SpringMVC返回Json数据-方式1
<Spring学习笔记-MVC>系列文章,讲解返回json数据的文章共有3篇,分别为: [Spring学习笔记-MVC-3]SpringMVC返回Json数据-方式1:http://www ...
- 【Spring学习笔记-MVC-7】Spring MVC模型对象-模型属性讲解
作者:ssslinppp 来自为知笔记(Wiz) 附件列表 处理模型数据.png
- 【Spring学习笔记-MVC-14】Spring MVC对静态资源的访问
作者:ssslinppp 参考链接: http://www.cnblogs.com/luxh/archive/2013/03/14/2959207.html http://www.cnb ...
- 【Spring学习笔记-MVC-16】Spring MVC之重定向-解决中文乱码
概述 spring MVC框架controller间跳转,需重定向,主要有如下三种: 不带参数跳转:形如:http://localhost:8080/SpringMVCTest/test/myRedi ...
- 【Spring学习笔记-MVC-15】Spring MVC之异常处理
作者:ssslinppp 1. 描述 在J2EE项目的开发中,不管是对底层的数据库操作过程,还是业务层的处理过程,还是控制层的处理过程,都不可避免会遇到各种可预知的.不可预知的异常需要处理 ...
- 【Spring学习笔记-MVC-13】Spring MVC之文件上传
作者:ssslinppp 1. 摘要 Spring MVC为文件上传提供了最直接的支持,这种支持是通过即插即用的MultipartResolve实现的.Spring使用Jakarta Co ...
- 【Spring学习笔记-MVC-12】Spring MVC视图解析器之ResourceBundleViewResolver
场景 当我们设计程序界面的时候,中国人希望界面是中文,而美国人希望界面是英文. 我们当然希望后台代码不需改变,系统能够通过配置文件配置,来自己觉得是显示中文界面还是英文界面. 这是,Spring mv ...
- Spring学习笔记 7.1 Spring MVC起步
7.1.1 跟踪Spring MVC的请求请求首先到达DispatcherServlet(DispatcherServlet是Spring MVC中的前端控制器):DispatcherServlet的 ...
随机推荐
- HDU 4791 Alice's Print Service 思路,dp 难度:2
A - Alice's Print Service Time Limit:1000MS Memory Limit:32768KB 64bit IO Format:%I64d & ...
- zabbix的搭建与入门
一,Zabbix架构 zabbix 是一个基于 WEB 界面的提供分布式系统监视以及网络监视功能的企业级的开源解决方案.zabbix 能监视各种网络参数,保证服务器系统的安全运营:并提供灵活的通知机制 ...
- window上创建python3虚拟环境
虚拟环境,就是为某个需要单独运行的软件创建一个隔绝的环境,虚拟程序中运行的程序不会影响电脑上其他软件的运行.例如同时使用python2和python3,可以在两个不同的虚拟环境中分别运行. 安装虚拟环 ...
- CentOS 7 目录布局变化
/bin转移到/usr/bin;/sbin转移到/usr/sbin;/lib转移到/usr/lib;/lib64转移到/usr/lib64. /var/run符号连接到/run;/var/lock符号 ...
- php 从2维数组组合为四维数组分析
- Linux/Mac OS 个人常用Terminal技巧整理
刚开始接触linux有些不适应,走了不少弯路,一直没有系统的学过linux应用,基本都是零零散散Google出来的知识,在这里做个整理: Vi/Vim 基本操作: 刚开始接触linux时,不懂vi吃了 ...
- HDU 1589 Stars Couple(计算几何求二维平面的最近点对和最远点对)
Time Limit: 1000/2000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission( ...
- C#读写基恩士PLC 使用TCP/IP 协议 MC协议
本文将使用一个Github开源的组件库技术来读写基恩士PLC数据,使用的是基于以太网的TCP/IP实现,不需要额外的组件,读取操作只要放到后台线程就不会卡死线程,本组件支持超级方便的高性能读写操作 g ...
- Linux删除Screen
screen screen命令是用来解决远程运行服务器中程序时无法退出的尴尬问题. 介绍 有详细的一篇文章 linux screen 命令详解 问题 文章较老,难免有问题. 比如某用户评论: Ctrl ...
- 【转】Python判断字符串是否为字母或者数字
str_1 = " str_2 = "Abc" str_3 = "123Abc" #用isdigit函数判断是否数字 print(str_1.isdi ...