码迷,mamicode.com
首页 > 编程语言 > 详细

Spring MVC 数据验证——validate编码方式

时间:2017-07-11 19:29:08      阅读:273      评论:0      收藏:0      [点我收藏+]

标签:pos   编码方式   logging   net   cto   download   dcl   执行   app   

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编码方式

标签:pos   编码方式   logging   net   cto   download   dcl   执行   app   

原文地址:http://www.cnblogs.com/yutingliuyl/p/7151806.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!