1、导入jar包

  • validation-api-1.0.0.GA.jar这是比較关键的一个jar包,主要用于解析注解@Valid.
  • hibernate-validator-4.3.2.Final.jar能够下载最新的。这个包在注解方式编码中尤为重要。
  • 其它的就是一些日志包(不一定全不须要):jboss-logging-3.1.3.GA.jar、slf4j-log4j12-1.6.1.jar

2、web项目的结构图

3、项目配置

  • web.xml配置

    Spring mvc项目的最小配置
<?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>SpringMVC</display-name>
<welcome-file-list>
<welcome-file>jsp/hello.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
  • hello-servlet.xml配置

    通过自己主动载入
<?

xml version="1.0" encoding="UTF-8"?

>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd"> <context:component-scan
base-package="controller">
</context:component-scan>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" /> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/jsp/" p:suffix=".jsp">
<!-- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> -->
</bean> <!--数据验证 编码方式的配置-->
<mvc:annotation-driven validator="accountValidator"/>
<bean id="accountValidator" class="dao.AccountValidator"></bean>
</beans>

4、src下加入源代码

  • controller包

    RegisterController类主要有两个方法,一个用于get,还有一个用于post。当中数据验证是放在registerIF()方法中的。

    验证是通过前两个參数。第一个參数是一个javabean保存的是注冊用户的信息,第二个參数用于数据验证提交过来的javabean对象。

package controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.DataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import dao.Account;
import dao.AccountValidator; @Controller
@RequestMapping("/register")
public class RegisterController { @RequestMapping(method=RequestMethod.GET)
public String register(Model model){
if (!model.containsAttribute("account")) {
model.addAttribute("account",new Account());
}
return "register";
} @InitBinder
public void initBinder(DataBinder binder){
binder.setValidator(new AccountValidator());
} @RequestMapping(method=RequestMethod.POST)
public String registerIF(@Valid @ModelAttribute("account")Account account,BindingResult result,Model model){ System.out.println("用户名:"+account.getUsername());
if (result.hasErrors()) {
System.out.println("register faliure.");
model.addAttribute("message", "注冊失败");
}else {
model.addAttribute("message", "注冊成功");
} return "register";
}
}
  • dao包

    (1)、javabean类Account,用于保存注冊用户信息
package dao;

import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size; public class Account { private String username;
private String password; public Account() {
// TODO Auto-generated constructor stub
} public Account(String username, String password) {
super();
this.username = username;
this.password = password;
} public String getUsername() {
return username;
} public void setUsername(String username) {
this.username = username;
} public String getPassword() {
return password;
} public void setPassword(String password) {
this.password = password;
} }

(2)、 AccountValidator用于检验Account的输入用户信息

这个就是编码方式验证数据的主要类,通过hello-servlet.xml中的自己主动载入方式,将类载入进去,引入点就是在@Valid注解处。

package dao;

import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator; public class AccountValidator implements Validator { @Override
public boolean supports(Class<?> arg0) {
// TODO Auto-generated method stub
return Account.class.equals(arg0);
} @Override
//主要通过这种方法,验证数据
public void validate(Object obj, Errors erros) {
// TODO Auto-generated method stub
ValidationUtils.rejectIfEmpty(erros, "username", null,"用户名不能为空.");
ValidationUtils.rejectIfEmpty(erros, "password", null,"密码不能为空.");
Account account = (Account) obj;
if (account.getUsername().length()<3 || account.getUsername().length()>20) {
erros.rejectValue("username","length","用户名长度在3-20个字符串之间");
} if (account.getPassword().length()<6 || account.getPassword().length()>20) {
erros.rejectValue("password","size","密码长度在6-20个字符之间");
}
}
}

5、加入jsp

在WEB-INF中新建一个jsp文件夹,然后新建一个register.jsp文件,加入例如以下代码:

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>注冊界面</title>
</head>
<body>
<form:form method="post" modelAttribute="account">
<label for="username">用户名:</label>
<form:input type="text" path="username"/>
<form:errors path="username"/><br><br> <label for="pwd">密码:</label>&nbsp;
<form:input type="password" path="password"/>
<form:errors path="password"/>
<br><br>
<input type="submit" value="注冊" name="login"/>&nbsp;&nbsp;
</form:form>
<br><hr>
${message}
</body>
</html>

6、效果演示

执行程序,然后在浏览器中输入地址:http://localhost:8080/annotation_springmvc/register

Spring MVC 数据验证——validate编码方式的更多相关文章

  1. Spring MVC 数据验证——validate注解方式

    1.说明 学习注解方式之前,应该先学习一下编码方式的spring注入.这样便于理解验证框架的工作原理.在出错的时候,也能更好的解决这个问题.所以本次博客教程也是基于编码方式.仅仅是在原来的基础加上注解 ...

  2. Hibernate Validation,Spring mvc 数据验证框架注解

    1.@NotNull:不能为 Null,但是可以为Empty:用在基本数据类型上. @NotNull(message="{state.notnull.valid}", groups ...

  3. spring mvc数据验证

    今天来说一下.前段验证,与后端数据验证.大家都知道.在我们.注册与登陆的时候,往往需要对数据进行效验.那么前段我们都知道,可以使用,js去做处理. 今天主要讲解.后端的数据效验.这里我们采用Hiber ...

  4. Spring mvc 数据验证框架注解

    @AssertFalse 被注解的元素必须为false@AssertTrue 被注解的元素必须为false@DecimalMax(value) 被注解的元素必须为一个数字,其值必须小于等于指定的最小值 ...

  5. Spring mvc 数据验证

    加入jar包 bean-validator.jar 在实体类中加入验证Annotation和消息提示 package com.stone.model; import javax.validation. ...

  6. MVC 数据验证

    MVC 数据验证 前一篇说了MVC数据验证的例子,这次来详细说说各种各样的验证注解.System.ComponentModel.DataAnnotations 一.基础特性 一.Required 必填 ...

  7. MVC 数据验证[转]

    前一篇说了MVC数据验证的例子,这次来详细说说各种各样的验证注解. 一.基础特性 一.Required 必填选项,当提交的表单缺少该值就引发验证错误. 二.StringLength 指定允许的长度 指 ...

  8. spring mvc返回json字符串的方式

    spring mvc返回json字符串的方式 方案一:使用@ResponseBody 注解返回响应体 直接将返回值序列化json            优点:不需要自己再处理 步骤一:在spring- ...

  9. mvc 数据验证金钱格式decimal格式验证

    mvc 数据验证金钱格式decimal格式验证 首先看下代码 /// <summary> /// 产品单价 /// </summary> [Display(Name = &qu ...

随机推荐

  1. 由于未清除缓存引发的bug

    在写页面的时候,首先引入了本地react.js和react-dom.js 16版本(cjs)的文件,出现如下错误 发现bug后,将本地的react.js和react-dom.js文件改成16.2(um ...

  2. 表单文件上传编码方式(enctype 属性)

    enctype 属性规定在发送到服务器之前应该如何对表单数据进行编码. 如下: <form action="upload.php" method="post&quo ...

  3. SolidWorks的文件类型

    零件模板 *.prtdot装配体模板 *.asmdot工程图模板 *.drwdot颜色文件 *.sldclr曲线文件 *.sldcrv复制设定向导文件 *.sldreg零件文件:prt sldprtF ...

  4. 09Windows编程

    Windows编程 2.1      窗口 Windows应用程序一般都有一个窗口,窗口是运行程序与外界交换信息的界面.一个典型的窗口包括标题栏.最小化按钮.最大/还原按钮.关闭按钮.系统菜单图标.菜 ...

  5. javaScript中计算字符串MD5

    进行HTTP网络通信的时候,调用API向服务器请求数据,有时为了防止API调用过程中被黑客恶意篡改,所请求参数需要进行MD5算法计算,得到摘要签名.服务端会根据请求参数,对签名进行验证,签名不合法的请 ...

  6. Maven 的相关配置

    第一步: 官方下载路径: http://maven.apache.org/download.cgi maven官方网站:http://www.mvnrepository.com/ 第二步: 请下载这个 ...

  7. 使用ajax解析后台json数据时:Unexpected token o in JSON at position 1

    json数据解析异常 今天在做json数据的时候,出现了如下错误,说是解析异常. VM1584:1 Uncaught SyntaxError: Unexpected token o in JSON a ...

  8. 又是latch: cache buffers chains惹得祸

    前言 一大早,客户给我打电话说: xx,应用很慢,查询数据总是超时,让我看看... 根据多年DBA经验,首当其冲的肯定是去查询数据库在这段时间都在干嘛. 分析 导出awr报告分析 1). 数据库在此时 ...

  9. mysql解决 ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: YES)的报错

    一般这个错误是由密码错误引起,解决的办法自然就是重置密码. 假设我们使用的是root账户. 1.重置密码的第一步就是跳过MySQL的密码认证过程,方法如下: #vim /etc/my.cnf(注:wi ...

  10. 76-Bears/Bulls Power,熊力/牛力震荡指标.(2015.7.1)

    Bears/Bulls Power 熊力/牛力震荡指标 Power,熊力/牛力震荡指标.(2015.7.1)" title="76-Bears/Bulls Power,熊力/牛力震 ...