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

java后端校验

时间:2016-02-22 19:19:26      阅读:293      评论:0      收藏:0      [点我收藏+]

标签:

  网站的后端校验是不可或缺的一部分,我们在后台验证表单时,可能需要把前端传过来的字段一个一个手工校验,或者使用框架的校验去做,今天我编写了一个校验框架,记录如下,

和大家一起分享。《转载请注明出处,谢谢》

1.代码总览

技术分享

将需要校验的表单信息设置在src目录下的formVerify.xml里;

Xmlparse4FormVerify.java负责读取解析formVerify.xml文件;

VerifyRegularUtil.java负责处理正则表达式相关工作;

 

2.下面是具体文件及代码

1.formVerify.xml

技术分享
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <forms>
 3     <form id="test">
 4         <name>
 5             <text>用户名</text>
 6             <rule>required,min_3,max_20,email</rule>
 7         </name>
 8         <pwd>
 9             <text>密码</text>
10             <rule>required,min_3,max_20</rule>
11         </pwd>
12         <phone>
13             <text>手机</text>
14             <rule>phone</rule>
15         </phone>
16         <tel>
17             <text>电话</text>
18             <rule>tel</rule>
19         </tel>
20         <yzbm>
21             <text>邮编</text>
22             <rule>yzbm</rule>
23         </yzbm>
24         <sfz>
25             <text>身份证</text>
26             <rule>sfz</rule>
27         </sfz>
28         <url>
29             <text>url</text>
30             <rule>url</rule>
31         </url>
32         <ip>
33             <text>ip</text>
34             <rule>ip</rule>
35         </ip>
36         <mac>
37             <text>mac</text>
38             <rule>mac</rule>
39         </mac>
40         
41         <decimal>
42             <text>小数点两位</text>
43             <rule>decimal</rule>
44         </decimal>
45         <num>
46             <text>数字</text>
47             <rule>num</rule>
48         </num>
49         
50         <n>
51             <text>正整数</text>
52             <rule>n</rule>
53         </n>
54     </form>
55     
56     <form id="test2">
57         <name>
58             <text>用户名</text>
59             <rule>required,min_3,max_20,email</rule>
60         </name>
61         <pwd>
62             <text>密码</text>
63             <rule>required,min_3,max_20</rule>
64         </pwd>
65         <phone>
66             <text>手机</text>
67             <rule>phone</rule>
68         </phone>
69     </form>
70 </forms>
formVerify.xml

2.VerifyRegularUtil.java

技术分享
  1 /**
  2  * 
  3  */
  4 package com.linker.util;
  5 
  6 import java.util.regex.Pattern;
  7 
  8 /**
  9  * Title:VerifyRegularUtil 
 10  * description: 验证表单的工具包
 11  * company: linker
 12  * @author zhanjp
 13  * @date 2016年2月22日 上午11:00:52
 14  */
 15 public class VerifyRegularUtil {
 16     //邮箱
 17     private String email = "^([\\w-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([\\w-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$";
 18     //手机
 19     private String phone = "^[1]+[3,5]+\\d{9}$";
 20     //电话
 21     private String tel = "^(\\d{3,4}-)?\\d{6,8}$";
 22     //邮编
 23     private String yzbm = "^\\d{6}$";
 24     //身份证
 25     private String sfz = "(^\\d{18}$)|(^\\d{15}$)";
 26     
 27     //url
 28     private String url = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";
 29     //ip
 30     private String ip = "^((\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])\\.){3}(\\d|[1-9]\\d|1\\d\\d|2[0-4]\\d|25[0-5]|[*])$";
 31     //物理地址
 32     private String mac = "^[A-F0-9]{2}(-[A-F0-9]{2}){5}$";  
 33     
 34     //两位小数
 35     private String decimal = "^[0-9]+(.[0-9]{2})?$";
 36     //数字
 37     private String num = "^[0-9]*$";
 38     //正整数
 39     private String n = "^\\+?[1-9][0-9]*$";
 40     
 41     /**
 42      * 校验表单
 43      * @param data
 44      * @return
 45      */
 46     public String verify(String value,String preText,String rule)throws Exception{
 47         String[] rs = rule.split(",");
 48         String errorInfo = null;
 49         for(String s:rs){
 50             if(s.indexOf("|")<0&&s.indexOf("_")<0){
 51                 //包含“|”是指或者的关系,比如输入框可以输入邮箱或者手机号,包含“_”,比如min_6指最小6位
 52                 switch (s) {
 53                 //需要特殊说明文字的在此添加case
 54                 case "required":
 55                     if(value!=null&&value.trim().length()>0){
 56                         
 57                     }else{
 58                         errorInfo = preText + "不能为空";
 59                     }
 60                     break;
 61                 //通用说明走else
 62                 default:
 63                     errorInfo = verifyByRegular(value,preText,s);
 64                     break;
 65                 }
 66                 if(errorInfo!=null){
 67                     //如果已有错误信息,则不需要再次循环
 68                     break;
 69                 }
 70             }else{
 71                 if(s.indexOf("|")>=0){
 72                     //包含"或者关系",一般"|"和"_"不会共存,在此不做考虑
 73                     if(s.indexOf("_")>=0){
 74                         throw new Exception(preText + "规则配置错误");
 75                     }
 76                     String[] s1 = s.split("|");
 77                     for(String s2:s1){
 78                         errorInfo = verifyByRegular(preText, value, s2);
 79                         if(errorInfo==null){
 80                             break;
 81                         }
 82                     }
 83                 }else if(s.indexOf("_")>=0){
 84                     String[] s1 = s.split("_");
 85                     if(s1[0].equals("min")){
 86                         errorInfo = minLen(preText, value, Integer.parseInt(s1[1]));
 87                     }else if(s1[0].equals("max")){
 88                         errorInfo = maxLen(preText, value, Integer.parseInt(s1[1]));
 89                     }else{
 90                         throw new Exception("暂不支持这种校验格式:" + s1[0]);
 91                     }
 92                 }
 93                 if(errorInfo!=null){
 94                     //如果已有错误信息,则不需要再次循环
 95                     break;
 96                 }
 97                 
 98             }
 99         }
100         return errorInfo;
101     }
102     
103     /**
104      * 根据正则表达式判断是否成立
105      * @param preText 必传,字段名称
106      * @param value 必传,字段值
107      * @param r 必传,校验类型
108      * @return
109      */
110     private String verifyByRegular(String value,String preText,String r)throws Exception{
111         String errorInfo = null;
112         String regex = "";
113         switch (r) {
114         case "email":
115             regex = email;
116             break;
117         case "phone":
118             regex = phone;
119             break;
120         case "tel":
121             regex = tel;
122             break;
123         case "yzbm":
124             regex = yzbm;
125             break;
126         case "sfz":
127             regex = sfz;
128             break;
129         case "n":
130             regex = n;
131             break;
132         case "url":
133             regex = url;
134             break;
135         case "ip":
136             regex = ip;
137             break;
138         case "mac":
139             regex = mac;
140             break;
141         case "decimal":
142             regex = decimal;
143             break;
144         case "num":
145             regex = num;
146         default:
147             break;
148         }
149         if(regex.equals("")){
150             throw new Exception("暂不支持这种校验格式:" + r);
151         }else{
152             boolean flg = Pattern.matches(regex, value);
153             if(flg){
154 
155             }else{
156                 errorInfo = preText + "格式不正确,请重新检查!";
157             }
158         }
159         return errorInfo;
160     }
161     
162     
163     /**
164      * 校验最少长度
165      * @param preText
166      * @param value
167      * @param min
168      * @return
169      */
170     private String minLen(String preText,String value,int min){
171         String errorInfo = null;
172         if(value!=null&&value.trim().length()>=min){
173             
174         }else{
175             errorInfo = preText + "最少长度为" + min +"位。";
176         }
177         return errorInfo;
178     }
179     
180     private String maxLen(String preText,String value,int max){
181         String errorInfo = null;
182         if(value!=null&&value.trim().length()<=max){
183             
184         }else{
185             errorInfo = preText + "最大长度为" + max +"位。";
186         }
187         return errorInfo;
188     }
189     
190 }
VerifyRegularUtil.java

3.Xmlparse4FormVerify.java

技术分享
  1 /**
  2  * 
  3  */
  4 package com.linker.util;
  5 
  6 import java.io.File;
  7 import java.io.IOException;
  8 import java.util.ArrayList;
  9 import java.util.Iterator;
 10 import java.util.List;
 11 import java.util.Map;
 12 import java.util.Set;
 13 
 14 import javax.xml.parsers.DocumentBuilder;
 15 import javax.xml.parsers.DocumentBuilderFactory;
 16 import javax.xml.parsers.ParserConfigurationException;
 17 
 18 import org.w3c.dom.Document;
 19 import org.w3c.dom.Element;
 20 import org.w3c.dom.Node;
 21 import org.w3c.dom.NodeList;
 22 import org.xml.sax.SAXException;
 23 
 24 /**
 25  * Title:Xmlparse4FormVerify 
 26  * description: 读取xml中配置的表单验证信息
 27  * company: linker
 28  * @author zhanjp
 29  * @date 2016年2月22日 上午9:33:59
 30  */
 31 public class Xmlparse4FormVerify {
 32 
 33     private static DocumentBuilder db = null;
 34     
 35     private static DocumentBuilderFactory dbf = null;
 36     
 37     private static Document dt = null;
 38     
 39     public static Xmlparse4FormVerify xp;
 40     
 41     
 42     /**
 43      * 初始化DocumentBuilder等信息
 44      * @return
 45      */
 46     public Xmlparse4FormVerify getInstance(){
 47         if(xp==null){
 48             xp = new Xmlparse4FormVerify();
 49         }
 50         return xp;
 51     }
 52     
 53     static{
 54         try {
 55             //返回documentBuilderFactory
 56             dbf = DocumentBuilderFactory.newInstance();
 57             
 58             db = dbf.newDocumentBuilder();
 59             String basePath = new Xmlparse4FormVerify().getClass().getClassLoader().getResource("/").getPath();
 60             File f = new File(basePath + "formVerify.xml");
 61             //获取xml文件的dom对象
 62             dt = db.parse(f);
 63         } catch (ParserConfigurationException  e) {
 64             e.printStackTrace();
 65             System.out.println("class:Xmlparse4FormVerify>>documentBuilder对象初始化失败。");
 66         } catch (SAXException | IOException e) {
 67             // TODO Auto-generated catch block
 68             e.printStackTrace();
 69             System.out.println("class:Xmlparse4FormVerify>>解析formVerify.xml文档失败");
 70         }
 71     }
 72     
 73     /**
 74      * 根据表单ID和表单参数进行校验
 75      * @param formId 表单ID
 76      * @param pMap 表单参数
 77      * @return flag-0:成功,1:失败; msg-消息
 78      * @throws Exception
 79      */
 80     public static String verifyForm(String formId,Map<String, String> pMap)throws Exception{
 81         if(dt==null){
 82             throw new Exception("未能正确初始化。");
 83         }
 84         String errorInfo = null;
 85         //开始解析xml文档
 86         //获取xml文件跟节点
 87         Element element = dt.getDocumentElement();
 88         //获取根节点下的子节点列表
 89         NodeList cList = element.getChildNodes();
 90         List<Node> forms = new ArrayList<>();
 91         for (int i = 0; i < cList.getLength(); i++) {
 92             Node tNode = cList.item(i);
 93             if(tNode.getNodeName().equals("form")){
 94                 forms.add(tNode);
 95             }
 96         }
 97         for (int i = 0; i < forms.size(); i++) {
 98             Node node1 = forms.get(i);
 99             String nodeId = node1.getAttributes().getNamedItem("id").getNodeValue();
100 //            System.out.println("节点id:" + nodeId+","+"节点name"+node1.getNodeName());
101             if(nodeId.equals(formId)){
102                 NodeList cList2 = node1.getChildNodes();
103                 //开始校验
104                 Set<String> keys = pMap.keySet();
105                 Iterator<String> iter = keys.iterator();
106                 while (iter.hasNext()) {
107                     String key = iter.next();
108                     for (int j = 0; j < cList2.getLength(); j++) {
109                         Node node = cList2.item(j);
110 //                        System.out.println("clist2,node:"+node.getNodeName());
111                         if(node.getNodeName().equals(key)){
112                             String value = pMap.get(key);
113                             String preText = "";
114                             String rule = "";
115                             NodeList cList3 = node.getChildNodes();
116                             
117                             for(int m = 0;m < cList3.getLength(); m++){
118                                 if(cList3.item(m).getNodeName()=="text"){
119                                     preText = cList3.item(m).getTextContent();
120                                 }else if(cList3.item(m).getNodeName()=="rule"){
121                                     rule = cList3.item(m).getTextContent();
122                                 }
123                             }
124                             //TODO 校验
125                             errorInfo = new VerifyRegularUtil().verify(value, preText,  rule);
126                             if(errorInfo!=null){
127                                 return errorInfo;
128                             }
129                         }
130                     }
131                     
132                 }
133                 break;
134             }
135         }
136         return errorInfo;
137     }
138 }
Xmlparse4FormVerify.java

4.测试代码:(本项目控制层SpringMvc,可根据自己情况适当更改)

技术分享
 1 @RequestMapping(value="/test2017")
 2     public void test2(){
 3         HashMap<String, String> pMap = new HashMap<>();
 4         pMap.put("name", "944593237@qq.com");
 5         pMap.put("pwd", "123456");
 6         pMap.put("phone", "15138456324");
 7         pMap.put("tel", "123456");
 8         pMap.put("yzbm", "3100562");
 9         pMap.put("sfz", "413025199802243366");
10         pMap.put("url", "http://www.baidu.com");
11         pMap.put("ip", "172.1.4.113");
12         pMap.put("mac", "EC-B1-D7-49-20-33");
13         pMap.put("decimal", "123456.22");
14         pMap.put("num", "123");
15         pMap.put("n", "2");
16         try {
17             String errorInfo = Xmlparse4FormVerify.verifyForm("test2", pMap);
18             if(errorInfo!=null){
19                 System.out.println(errorInfo);
20             }else{
21                 System.out.println("表单验证通过!");
22             }
23         } catch (Exception e) {
24             // TODO Auto-generated catch block
25             e.printStackTrace();
26         }
27     }
测试

 

java后端校验

标签:

原文地址:http://www.cnblogs.com/bolg666/p/5207881.html

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