SpringMVC拦截器实现数据验证 v0.1版(欣茂Java学院)

1、SpringMVC文件配置:


       
       
           
           
       
   

   
       
           
               Validators
           
       
   

2、定义资源文件

AdminLoginAction.login=aid:string|password:string

3、定义拦截器

package cn.xmkeshe.util.validation;
import org.springframework.context.MessageSource;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;
public class ValidatorInterceptor implements HandlerInterceptor {
    @Resource
    private MessageSource messageSource;
    @Override
    public boolean preHandle(HttpServletRequest request,HttpServletResponse response, Object handler) throws Exception {
        // 1、取得对象
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        // 2、取得对象方法
        System.out.println(handlerMethod.getMethod().getName());
        // 3、取得对象名称
        System.out.println(handlerMethod.getBean().getClass().getSimpleName());
        // 4、拼凑key
        String key = handlerMethod.getBean().getClass().getSimpleName() + "." + handlerMethod.getMethod().getName();
        // 5、通过key取得value
        System.out.println("key=" + key);
        System.out.println("key=" + this.messageSource.getMessage(key, null, Locale.getDefault()));
        // 6、判断规则是否存在
        String validatorValue = this.messageSource.getMessage(key, null, Locale.getDefault());
        if (validatorValue != null) {
            System.out.println(new Validator().validation(request, validatorValue)+"****");
            if(new Validator().validation(request, validatorValue)) {
                return true;
            }else{
                return false;
            }
        } else {
            return false;
        }
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    }
}

4、数据验证类

package cn.xmkeshe.util.validation;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
public class Validator {
    public boolean validation(HttpServletRequest request, String rule) throws ServletException, IOException {
        boolean flag = true;
        String result[] = rule.split("\\|");
        for (int x = 0; x < result.length; x++) {
            String temp[] = result[x].split(":");
            // 取得内容
            String value = request.getParameter(temp[0]);
            if(value != null){
                if("string".equals(temp[1])){
                    flag = this.isEmpty(value);
                    if(flag == false){
                       return false;
                    }
                }else if("date".equals(temp[1])){
                    flag = this.isDate(value);
                    if(flag == false){
                        return false;
                    }
                }else if("number".equals(temp[1])){
                    flag = this.isNumber(value);
                    if(flag == false){
                        return false;
                    }
                }
            }
        }
        return flag;
    }
    /**
     * 
  • 验证字符串是否为空1
  • * * @param str 要执行验证的字符串 * @return 验证成功返回true,验证失败返回false */ public boolean isEmpty(String str) { if (str == null || "".equals(str)) { return false; } return true; } /** *
  • 数字验证
  • * * @param str * @return */ public boolean isNumber(String str) { if (this.isEmpty(str)) { return str.matches("\\d+(\\.\\d+?)"); } return false; } /** *
  • 日期验证
  • * * @param str * @return */ public boolean isDate(String str) { if (this.isEmpty(str)) { if (str.matches("\\d{4}-\\d{2}-\\d{2}")) { return true; } else { return str.matches("\\d{4}-\\d{2}-\\d{2} \\d{2}:\\d{2}:\\d{2}"); } } return false; } }

    5、js提示信息定义

    layui.use(['layer', 'form', 'jquery'], function () {
        var layer = layui.layer,
            form = layui.form,
            $ = layui.jquery;
        form.on('submit(formDemo)', function (obj) {
            $.ajax({
                url: '/hospital/pages/AdminLoginAction/login.html',
                type: 'POST',
                data: $('.layui-form').serialize(),
                success: function (data) {
                    if (data == "success") {
                        layer.msg('登录成功!', {
                            time: 2000, icon: 1, end: function () {
                                window.location.href='/hospital/back/admin/index.jsp';
                            }
                        })
                    } else if(data == "failure"){
                        layer.msg('登录失败!',{time:2000,icon:2})
                    }else{
                        layer.msg("数据不能为空!",{time:2000,icon:2})
                    }
                }
            })
        })
    })
    

    6、控制层代码定义

    @Controller
    @RequestMapping("/pages/AdminLoginAction/*")
    public class AdminLoginAction extends DefaultAction {
        @Resource
        private IAdminService adminService;
    
        @RequestMapping("login")
        public void login(Admin admin, HttpServletResponse response, HttpServletRequest request) {
            try {
                Admin vo = this.adminService.login(admin.getAid(),admin.getPassword());
               if(vo != null){
                   super.print(response, "success");
               }else{
                   super.print(response, "failure");
               }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
    
    

    欣茂Java学院更多课程:点击学习
    SpringMVC拦截器实现数据验证 v0.1版(欣茂Java学院)_第1张图片

    你可能感兴趣的:(SpringMVC拦截器实现数据验证 v0.1版(欣茂Java学院))