SpringMvc后台校验实现

第一步:meven添加依赖包,也可自行下载,注意jboss.logging与hibernate-validator的版本要能对应上:

 <dependency>
            <groupId>org.hibernategroupId>
            <artifactId>hibernate-validatorartifactId>
            <version>4.3.1.Finalversion>           
        dependency>

        <dependency>
            <groupId>javax.validationgroupId>
            <artifactId>validation-apiartifactId>
            <version>1.0.0.GAversion>
        dependency>

        <dependency>
            <groupId>org.jboss.logginggroupId>
            <artifactId>jboss-loggingartifactId>
            <version>3.1.0.CR2version>
        dependency> 

第二步:在配置文件中添加校验的bean配置

<bean id="validator"  
        class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">  
        
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator" />  
   
        <property name="validationMessageSource" ref="messageSource" />  
    bean> 
    
    <bean id="messageSource"  
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">  
        
        <property name="basenames">     
            <list>      
            <value>classpath:CustomValidationMessagesvalue>  
            list>     
        property>  
        
        <property name="fileEncodings" value="UTF-8" />  
        <property name="defaultEncoding" value="UTF-8"/>
        
        <property name="cacheSeconds" value="120" />  
    bean>  

这里注意 这行代码,不然输出的错误信息可能乱码
第三步:新建错误信息配置文件,如我这里是CustomValidationMessages.properties,配置文件如下:

#校验错误信息的配置文件
marketing.jgdm.error=机构代码不能为空
marketing.yyrq.error=预约日期不能为空

第四步:在Pojo类中配置校验规则,如下所示,更多校验如@NotNull、@Null、@Max等可自行网上查阅

@Size(min=1,message="{marketing.jgdm.error}")
    private String jgdm;            //机构代码

第五步:Controller中使用该校验

@RequestMapping(value="/insertDepositMarketing.action",method={RequestMethod.POST,RequestMethod.GET})
    public String insertDepositMarketing(@Validated DepositMarketing depositMarketing,BindingResult bindingResult
            ,Model model) throws Exception{

        List allErrors = bindingResult.getAllErrors();
        if(bindingResult.hasErrors()){
            for(ObjectError error : allErrors){
                System.out.println(error.getDefaultMessage());
            }
            model.addAttribute("allErrors",allErrors);
            return "fail";
        }
        int yybh = depositMarketingService.insertDepositMarketing(depositMarketing);
        if(yybh > 0){
            //插入成功
            return "forward:queryDepositMarketing.action";
        }else{
            return "fail";
        }
    }

使用@Validated对Po类进行校验,并用BindingResult接收校验
第六步:页面输出错误信息

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>


<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'MyJsp.jsp' starting pagetitle>

    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    

  head>

  <body>
     <c:if test="${allErrors!= null}">
        <c:forEach items="${allErrors}" var="item">
            ${item.defaultMessage}
        c:forEach>
    c:if>
    <center> 操作居然失败了,真遗憾!center><br>
  body>
html>

分组校验

第一步:新建一个校验分组接口,如下:

public interface MarketingValidationGroup {

}

这个接口仅仅是标志校验分组
第二步:在Pojo类中给不同的校验规则划分分组,如下:

//将次校验划到校验分组:MarketingValidationGroup中去
    @Size(min=1,message="{marketing.jgdm.error}",groups=MarketingValidationGroup.class)

第散步步:在Controller中使用校验分组,如下:

public String insertDepositMarketing(@Validated(value={MarketingValidationGroup.class}) DepositMarketing depositMarketing,BindingResult bindingResult
            ,Model model) throws Exception{
            //代码省略
}

你可能感兴趣的:(Web开发)