Java的接受前端传递的参数的格式验证

Java后台在接受前端传递的参数时候会判断参数的格式是否正确

如果参数格式不正确,直接返回给前端页面一些错误的提示。这样就减少了

垃圾数据进入数据库中的操作。

        前端校验一般都用正则,后台接受数据如何校验呢?

下面我将自己写的一些后台的简单的校验数据参数的格式的方法说一下:

 引入包:

      

import java.util.regex.Matcher;
import java.util.regex.Pattern;

  定义数据的格式:

    

        private static final String EMAIL = "[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*@[_A-Za-z0-9-]+(\\.[_A-Za-z0-9-]+)*(\\.[A-Za-z]{2,})";//邮箱
	private static final String MOBILE_PHONE = "^((13[0-9])|(14[0-9])|(15[0-9])|17[0-9]|(18[0-9]))\\d{8}$"; // 手机号码
	private static Pattern emailPattern = Pattern.compile(EMAIL);
	private static Pattern mobilePhonePattern = Pattern.compile(MOBILE_PHONE);

	private static final String PASSWORD = "^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,16}$";
	private static final String NAME = "^[A-Z]+$";
private static Pattern passwordPattern = Pattern.compile(PASSWORD); private static Pattern namePattern = Pattern.compile(NAME);

  下面利用 Java给的验证方法进行处理

 Matcher matcher

  //     public static boolean isPasswordPattern(String str) {

         Matcher matcher = passwordPattern.matcher(str);
         return matcher.matches();
    }
     
     //姓名拼音缩写
     public static boolean isNamePattern(String str) {
         Matcher matcher = namePattern.matcher(str);
         if (matcher.matches()) {
             if (str.length() == 4) {
                 return true;
             } else {
                 return false;
             }
         }
         matcher = namePattern.matcher(str);
         return matcher.matches();
    }

      //   邮箱的校验
    public static boolean isEmailLegal(String str) {
        Matcher matcher = emailPattern.matcher(str);
        return matcher.matches();
    }


/** * 电话号码验证 * * @param str * @return 验证通过返回true */ public static boolean isTelephone(String str) { Pattern p1 = null, p2 = null; Matcher m = null; boolean b = false; p1 = Pattern.compile("^[0][1-9]{2,3}-[0-9]{5,10}$"); // 验证带区号的 p2 = Pattern.compile("^[1-9]{1}[0-9]{5,8}$"); // 验证没有区号的 if (str.length() > 9) { m = p1.matcher(str); b = m.matches(); } else { m = p2.matcher(str); b = m.matches(); } return b; }public static boolean check(String str, String regex) { boolean flag = false; try { Pattern pattern = Pattern.compile(regex); Matcher matcher = pattern.matcher(str); flag = matcher.matches(); } catch (Exception e) { flag = false; } return flag; }

 

posted @ 2017-07-19 09:12  坠落凡尘的魔鬼  阅读(4168)  评论(0编辑  收藏  举报