MongoDB+Struts2+JQuery.formValidator外掛的web應用示例

edagarli發表於2014-03-11

  1. /** 
  2.  * 此次應用涉及的幾個小知識點為: 
  3.  * 1.MongoDB的插入和更新操作 
  4.  * 2.Struts2的最基本使用 
  5.  * 3.單例設計模式的簡單使用 
  6.  * 4.JQuery form驗證表單外掛的使用 
  7.  */  
 

 

  1. /** 
  2.  * MongoDBWebTest 
  3.  * 註冊 
  4.  */  
  5. package com.labci.mongodb.web.action;  
  6. import java.util.Iterator;  
  7. import java.util.Map;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import net.sf.json.JSONArray;  
  10. import org.apache.struts2.interceptor.ServletRequestAware;  
  11. import com.labci.mongodb.web.util.GenderEnum;  
  12. import com.labci.mongodb.web.util.JSONToMapUtil;  
  13. import com.labci.mongodb.web.util.MongoDBUtil;  
  14. import com.labci.mongodb.web.util.NumbericUtil;  
  15. import com.mongodb.BasicDBObject;  
  16. import com.mongodb.DBCollection;  
  17. import com.mongodb.DBCursor;  
  18. import com.mongodb.DBObject;  
  19. import com.opensymphony.xwork2.ActionSupport;  
  20. /** 
  21.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  22.  * Jun 11, 2011[10:27:12 PM] 
  23.  * 
  24.  */  
  25. public class RegisterAction extends ActionSupport implements ServletRequestAware{  
  26.     /** 
  27.      *  
  28.      */  
  29.     private static final long serialVersionUID = -6732943120575582727L;  
  30.     private HttpServletRequest request;  
  31.     private static final String USER="user";  
  32.     @Override  
  33.     public String execute() throws Exception {  
  34.         String username=request.getParameter("username");  
  35.         String password=request.getParameter("password");  
  36.         String ageStr=request.getParameter("age");  
  37.         String birth=request.getParameter("birth");  
  38.         int age=getAge(ageStr);  
  39.         String gender=request.getParameter("gender");  
  40.         if(gender.equals("0")){  
  41.             gender=GenderEnum.MALE.getGenderValue();  
  42.         }else{  
  43.             gender=GenderEnum.FEMALE.getGenderValue();  
  44.         }  
  45.           
  46.         String idCardNo=request.getParameter("idCardNo");  
  47.         String email=request.getParameter("email");  
  48.         String telNo=request.getParameter("telephoneNo");  
  49.         String phoneNo=request.getParameter("phoneNo");  
  50.         String education=request.getParameter("education");  
  51.         String []interests=request.getParameterValues("interests");  
  52.         String desc=request.getParameter("desc");  
  53.           
  54.         //使用者表   
  55.         DBCollection userCollection=MongoDBUtil.getCollection(USER);  
  56.           
  57.         if(null!=username && !"".equals(username)){  
  58.             DBObject queryByName=new BasicDBObject();  
  59.             queryByName.put("username", username);  
  60.             DBCursor findByName=userCollection.find(queryByName);  
  61.             Iterator<DBObject> iter=findByName.iterator();  
  62.             if(!iter.hasNext()){  
  63.                 DBObject user=new BasicDBObject();  
  64.                 user.put("username", username);  
  65.                 user.put("password", password);  
  66.                 user.put("age", age);  
  67.                 user.put("birth", birth);  
  68.                 user.put("gender", gender);  
  69.                 user.put("idCardNo", idCardNo);  
  70.                 user.put("email", email);  
  71.                 user.put("telephoneNo", telNo);  
  72.                 user.put("phoneNo", phoneNo);  
  73.                 user.put("education", education);  
  74.                 int len=interests.length;  
  75.                 if(null!=interests && len>0){  
  76.                     Object []interestsArray=new Object[len];  
  77.                     for(int i=0;i<len;i++){  
  78.                         interestsArray[i]=interests[i];  
  79.                     }  
  80.                     user.put("interests", interestsArray);  
  81.                 }  
  82.                 user.put("desc", desc);  
  83.                 userCollection.save(user);  
  84.                 request.getSession().setAttribute("username", username);  
  85.                 DBObject findByUsername=userCollection.findOne(queryByName);  
  86.                 if(null!=findByUsername){  
  87.                     Map<String,Object> userMap=JSONToMapUtil.parseToMap(findByUsername.toString());  
  88.                     JSONArray interestsArray=JSONArray.fromObject(userMap.get("interests"));  
  89.                     request.setAttribute("interest", interestsArray.toArray());  
  90.                     request.setAttribute("userMap", userMap);  
  91.                 }  
  92.             }  
  93.         }  
  94.         return SUCCESS;  
  95.     }  
  96.     private int getAge(String ageStr){  
  97.         int age=18;//預設為18歲,成年人   
  98.         if(NumbericUtil.isInteger(ageStr)){  
  99.             age=Integer.parseInt(ageStr);  
  100.             age=age<1?1:age>100?100:age;  
  101.         }  
  102.         return age;  
  103.     }  
  104.     public void setServletRequest(HttpServletRequest arg0) {  
  105.         this.request=arg0;  
  106.     }  
  107.       
  108. }  
 

  1. /** 
  2.  * MongoDBWebTest 
  3.  * 去更新頁面 
  4.  */  
  5. package com.labci.mongodb.web.action;  
  6. import java.util.Map;  
  7. import javax.servlet.http.HttpServletRequest;  
  8. import net.sf.json.JSONArray;  
  9. import org.apache.struts2.interceptor.ServletRequestAware;  
  10. import com.labci.mongodb.web.util.JSONToMapUtil;  
  11. import com.labci.mongodb.web.util.MongoDBUtil;  
  12. import com.mongodb.BasicDBObject;  
  13. import com.mongodb.DBCollection;  
  14. import com.mongodb.DBObject;  
  15. import com.opensymphony.xwork2.ActionSupport;  
  16. /** 
  17.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  18.  * Jun 11, 2011[10:27:12 PM] 
  19.  * 
  20.  */  
  21. public class ToUpdateAction extends ActionSupport implements ServletRequestAware{  
  22.     /** 
  23.      *  
  24.      */  
  25.     private static final long serialVersionUID = -6732943120575582727L;  
  26.     private HttpServletRequest request;  
  27.     private static final String USER="user";  
  28.     @Override  
  29.     public String execute() throws Exception {  
  30.         String username=(String) request.getSession().getAttribute("username");  
  31.         if(null!=username && !"".equals(username)){  
  32.             DBCollection userCollection=MongoDBUtil.getCollectionNotByAuth(USER);  
  33.             DBObject queryByName=new BasicDBObject();  
  34.             queryByName.put("username", username);  
  35.             DBObject findByUsername=userCollection.findOne(queryByName);  
  36.             if(null!=findByUsername){  
  37.                 Map<String,Object> userMap=JSONToMapUtil.parseToMap(findByUsername.toString());  
  38.                 JSONArray interestsArray=JSONArray.fromObject(userMap.get("interests"));  
  39.                 request.setAttribute("interest", interestsArray.toArray());  
  40.                 request.setAttribute("userMap", userMap);  
  41.             }  
  42.         }  
  43.         return SUCCESS;  
  44.     }  
  45.     public void setServletRequest(HttpServletRequest arg0) {  
  46.         this.request=arg0;  
  47.     }  
  48.       
  49. }  
 

  1. /** 
  2.  * MongoDBWebTest 
  3.  * 更新操作 
  4.  */  
  5. package com.labci.mongodb.web.action;  
  6. import java.util.Map;  
  7. import javax.servlet.http.HttpServletRequest;  
  8. import net.sf.json.JSONArray;  
  9. import org.apache.struts2.interceptor.ServletRequestAware;  
  10. import com.labci.mongodb.web.util.GenderEnum;  
  11. import com.labci.mongodb.web.util.JSONToMapUtil;  
  12. import com.labci.mongodb.web.util.MongoDBUtil;  
  13. import com.labci.mongodb.web.util.NumbericUtil;  
  14. import com.mongodb.BasicDBObject;  
  15. import com.mongodb.DBCollection;  
  16. import com.mongodb.DBObject;  
  17. import com.opensymphony.xwork2.ActionSupport;  
  18. /** 
  19.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  20.  * Jun 11, 2011[10:27:12 PM] 
  21.  * 
  22.  */  
  23. public class UpdateAction extends ActionSupport implements ServletRequestAware{  
  24.     /** 
  25.      *  
  26.      */  
  27.     private static final long serialVersionUID = -6732943120575582727L;  
  28.     private HttpServletRequest request;  
  29.     private static final String USER="user";  
  30.     @Override  
  31.     public String execute() throws Exception {  
  32.         String username=(String) request.getSession().getAttribute("username");  
  33.         if(null!=username && !"".equals(username)){  
  34.             DBCollection userCollection=MongoDBUtil.getCollectionNotByAuth(USER);  
  35.             String ageStr=request.getParameter("age");  
  36.             String birth=request.getParameter("birth");  
  37.             int age=getAge(ageStr);  
  38.             String gender=request.getParameter("gender");  
  39.             if(gender.equals("0")){  
  40.                 gender=GenderEnum.MALE.getGenderValue();  
  41.             }else{  
  42.                 gender=GenderEnum.FEMALE.getGenderValue();  
  43.             }  
  44.               
  45.             String idCardNo=request.getParameter("idCardNo");  
  46.             String email=request.getParameter("email");  
  47.             String telNo=request.getParameter("telephoneNo");  
  48.             String phoneNo=request.getParameter("phoneNo");  
  49.             String education=request.getParameter("education");  
  50.             String []interests=request.getParameterValues("interests");  
  51.             String desc=request.getParameter("desc");  
  52.             DBObject condition=new BasicDBObject();  
  53.             condition.put("username", username);  
  54.               
  55.             DBObject update=new BasicDBObject();  
  56.               
  57.             update.put("age", age);  
  58.             update.put("birth", birth);  
  59.             update.put("gender", gender);  
  60.             update.put("idCardNo", idCardNo);  
  61.             update.put("telephoneNo", telNo);  
  62.             update.put("phoneNo", phoneNo);  
  63.             update.put("education", education);  
  64.             update.put("email", email);  
  65.             update.put("interests", interests);  
  66.             update.put("desc", desc);  
  67.             DBObject setValue=new BasicDBObject();  
  68.             setValue.put("$set", update);  
  69.             userCollection.update(condition, setValue);  
  70.             DBObject findByUsername=userCollection.findOne(condition);  
  71.             if(null!=findByUsername){  
  72.                 Map<String,Object> userMap=JSONToMapUtil.parseToMap(findByUsername.toString());  
  73.                 JSONArray interestsArray=JSONArray.fromObject(userMap.get("interests"));  
  74.                 request.setAttribute("interest", interestsArray.toArray());  
  75.                 request.setAttribute("userMap", userMap);  
  76.             }  
  77.         }  
  78.         return SUCCESS;  
  79.     }  
  80.     private int getAge(String ageStr){  
  81.         int age=18;//預設為18歲,成年人   
  82.         if(NumbericUtil.isInteger(ageStr)){  
  83.             age=Integer.parseInt(ageStr);  
  84.             age=age<1?1:age>100?100:age;  
  85.         }  
  86.         return age;  
  87.     }  
  88.     public void setServletRequest(HttpServletRequest arg0) {  
  89.         this.request=arg0;  
  90.     }  
  91.       
  92. }  

  1. /** 
  2.  * MongoDBWebTest 
  3.  * 性別列舉類 
  4.  */  
  5. package com.labci.mongodb.web.util;  
  6. /** 
  7.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  8.  * Jun 11, 2011[10:54:08 PM] 
  9.  * 
  10.  */  
  11. public enum GenderEnum {  
  12.     MALE{  
  13.         public String getGenderValue(){  
  14.             return "男";  
  15.         }  
  16.     },  
  17.     FEMALE{  
  18.         public String getGenderValue(){  
  19.             return "女";  
  20.         }  
  21.     };  
  22.     public abstract String getGenderValue();  
  23. }  
 

  1. /** 
  2.  * MongoDBWebTest 
  3.  * 
  4.  */  
  5. package com.labci.mongodb.web.util;  
  6. import java.util.HashMap;  
  7. import java.util.Iterator;  
  8. import java.util.Map;  
  9. import net.sf.json.JSONObject;  
  10. /** 
  11.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  12.  * Jun 12, 2011[2:51:54 PM] 
  13.  * 
  14.  */  
  15. public class JSONToMapUtil {  
  16.     private JSONToMapUtil(){  
  17.           
  18.     }  
  19.     @SuppressWarnings("unchecked")  
  20.     public static Map<String,Object> parseToMap(String s){  
  21.         Map<String,Object> map=new HashMap<String,Object>();  
  22.         JSONObject json=JSONObject.fromObject(s);  
  23.         Iterator keys=json.keys();  
  24.         while(keys.hasNext()){  
  25.             String key=(String) keys.next();  
  26.             String value=json.get(key).toString();  
  27.             if(value.startsWith("{")&&value.endsWith("}")){  
  28.                 map.put(key, parseToMap(value));  
  29.             }else{  
  30.                 map.put(key, value);  
  31.             }  
  32.         }  
  33.         return map;  
  34.     }  
  35. }  
 

  1. /** 
  2.  * MongoDBWebTest 
  3.  * 取得資料庫連線的工具類 
  4.  */  
  5. package com.labci.mongodb.web.util;  
  6. import java.net.UnknownHostException;  
  7. import java.util.Map;  
  8. import java.util.concurrent.ConcurrentHashMap;  
  9. import com.mongodb.DB;  
  10. import com.mongodb.DBCollection;  
  11. import com.mongodb.Mongo;  
  12. import com.mongodb.MongoException;  
  13. /** 
  14.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  15.  * Jun 11, 2011[10:05:00 PM] 
  16.  * 
  17.  */  
  18. public class MongoDBUtil {  
  19.     private static final String HOST="host";  
  20.     private static final String PORT="port";  
  21.     private static final String USER="user";  
  22.     private static final String PASSWORD="password";  
  23.     private static final String DBNAME="dbname";  
  24.       
  25.     private static Map<String,Mongo> dbConnsMap=new ConcurrentHashMap<String,Mongo>();  
  26.     private static final Map<String,String> dbInfoMap=ParseFileInfo.getIntance().getDbInfoMap();  
  27.       
  28.     private MongoDBUtil(){  
  29.           
  30.     }  
  31.       
  32.     public static Mongo getConnection(){  
  33.         Mongo conn=dbConnsMap.get("test");  
  34.         if(null==conn){  
  35.             synchronized(MongoDBUtil.class){  
  36.                 if(null==conn){  
  37.                     //這種方式在jdk1.5及以上版本上沒有問題   
  38.                     try {  
  39.                         conn=new Mongo(dbInfoMap.get(HOST),Integer.parseInt(dbInfoMap.get(PORT)));  
  40.                     } catch (NumberFormatException e) {  
  41.                         e.printStackTrace();  
  42.                     } catch (UnknownHostException e) {  
  43.                         e.printStackTrace();  
  44.                     } catch (MongoException e) {  
  45.                         e.printStackTrace();  
  46.                     }  
  47.                     dbConnsMap.put("test", conn);  
  48.                 }  
  49.             }  
  50.         }  
  51.         return conn;  
  52.     }  
  53.       
  54.     public static DBCollection getCollection(String collectionName){  
  55.         DBCollection collection=null;  
  56.         boolean isLogin=true;  
  57.         DB db=getConnection().getDB(dbInfoMap.get(DBNAME));  
  58.         if(null != db){  
  59.             isLogin=db.authenticate(dbInfoMap.get(USER), dbInfoMap.get(PASSWORD).toCharArray());  
  60.         }  
  61.         if(isLogin){  
  62.             collection=db.getCollection(collectionName);  
  63.             if(null==collection){  
  64.                 synchronized(MongoDBUtil.class){  
  65.                     if(null==collection){  
  66.                         collection=db.createCollection(collectionName, null);  
  67.                     }  
  68.                 }  
  69.             }  
  70.         }  
  71.         return collection;  
  72.     }  
  73.       
  74.     public static DBCollection getCollectionNotByAuth(String collectionName){  
  75.         DBCollection collection=null;  
  76.         DB db=getConnection().getDB(dbInfoMap.get(DBNAME));  
  77.         if(null != db){  
  78.             collection=db.getCollection(collectionName);  
  79.             if(null==collection){  
  80.                 synchronized(MongoDBUtil.class){  
  81.                     if(null==collection){  
  82.                         collection=db.createCollection(collectionName, null);  
  83.                     }  
  84.                 }  
  85.             }  
  86.         }  
  87.         return collection;  
  88.     }  
  89. }  
 

  1. /** 
  2.  * MongoDBWebTest 
  3.  * 判斷是否是數字的工具類 
  4.  */  
  5. package com.labci.mongodb.web.util;  
  6. import java.util.regex.Pattern;  
  7. /** 
  8.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  9.  * Jun 11, 2011[10:38:33 PM] 
  10.  * 
  11.  */  
  12. public class NumbericUtil {  
  13.     private NumbericUtil(){  
  14.           
  15.     }  
  16.       
  17.     public static boolean isDigits(String input){  
  18.         boolean flag=false;  
  19.         if(!isStringNull(input)){  
  20.             String regex="^[//d]+[//.]?[//d]+$";  
  21.             Pattern p=Pattern.compile(regex);  
  22.             flag=p.matcher(input).matches();  
  23.         }  
  24.         return flag;  
  25.     }  
  26.       
  27.     public static boolean isInteger(String input){  
  28.         boolean flag=false;  
  29.         if(!isStringNull(input)){  
  30.             String regex="^[-+]?[//d]+$";  
  31.             Pattern p=Pattern.compile(regex);  
  32.             flag=p.matcher(input).matches();  
  33.         }  
  34.         return flag;  
  35.     }  
  36.       
  37.     public static boolean isDouble(String input){  
  38.         boolean flag=false;  
  39.         if(!isStringNull(input)){  
  40.             String regex="^[//d]+[//.][//d]+$";  
  41.             Pattern p=Pattern.compile(regex);  
  42.             flag=p.matcher(input).matches();  
  43.         }  
  44.         return flag;  
  45.     }  
  46.       
  47.     private static boolean isStringNull(String input){  
  48.         boolean isNull=false;  
  49.         if(null==input ||"".equals(input.trim())||input.length()<=0){  
  50.             isNull=true;  
  51.         }  
  52.         return isNull;  
  53.     }  
  54. }  
 

  1. /** 
  2.  * MongoDBWebTest 
  3.  * 解析db屬性檔案的類 
  4.  */  
  5. package com.labci.mongodb.web.util;  
  6. import java.io.IOException;  
  7. import java.io.InputStream;  
  8. import java.util.Enumeration;  
  9. import java.util.HashMap;  
  10. import java.util.Map;  
  11. import java.util.Properties;  
  12. /** 
  13.  * @author Bill Tu(tujiyue/iwtxokhtd) 
  14.  * Jun 11, 2011[9:43:02 PM] 
  15.  * 
  16.  */  
  17. public class ParseFileInfo {  
  18.     private static Properties configFile=null;  
  19.     private static final String DB_CONFIG_FILE_NAME="db.properties";  
  20.     private ParseFileInfo(){  
  21.         configFile=new Properties();  
  22.     }  
  23.       
  24.     private static class ParseFileInfoHolder{  
  25.         private static ParseFileInfo instance=new ParseFileInfo();  
  26.     }  
  27.       
  28.     public static ParseFileInfo getIntance(){  
  29.         return ParseFileInfoHolder.instance;  
  30.     }  
  31.       
  32.     public Map<String,String> getDbInfoMap(){  
  33.         InputStream is=ParseFileInfo.class.getResourceAsStream("/"+DB_CONFIG_FILE_NAME);  
  34.         Map<String,String> dbInfoMap=new HashMap<String,String>();   
  35.         if(null != is){  
  36.             try {  
  37.                 configFile.load(is);  
  38.             } catch (IOException e) {  
  39.                 e.printStackTrace();  
  40.             }  
  41.             Enumeration<Object> fileKeys=configFile.keys();  
  42.             while(fileKeys.hasMoreElements()){  
  43.                 String keyName=(String) fileKeys.nextElement();  
  44.                 dbInfoMap.put(keyName, configFile.getProperty(keyName));  
  45.             }  
  46.         }  
  47.         return dbInfoMap;  
  48.     }  
  49. }  
 

db.properties

  1. host=192.168.1.86  
  2. port=27017  
  3. user=iwtxokhtd  
  4. password=123456  
  5. dbname=test  
 

struts.xml

  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE struts PUBLIC  
  3.     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"  
  4.     "http://struts.apache.org/dtds/struts-2.0.dtd">  
  5. <struts>  
  6.     <constant name="struts.devMode" value="false" />  
  7.     <!-- 改變struts2預設為2M的上傳檔案大小限制 -->  
  8.     <constant name="struts.multipart.maxSize" value="1024000000"/>  
  9.     <package name="mongoDB" extends="struts-default">  
  10.         <action name="register" class="com.labci.mongodb.web.action.RegisterAction">  
  11.             <result name="success">viewInfo.jsp</result>  
  12.             <result name="input">index.jsp</result>  
  13.         </action>  
  14.         <action name="toUpdate" class="com.labci.mongodb.web.action.ToUpdateAction">  
  15.             <result name="success">updateInfo.jsp</result>  
  16.         </action>  
  17.         <action name="update" class="com.labci.mongodb.web.action.UpdateAction">  
  18.             <result name="success">viewInfo.jsp</result>  
  19.             <result name="input">updateInfo.jsp</result>  
  20.         </action>  
  21.     </package>  
  22. </struts>  
 

validator.js

  1. $(document).ready(function(){  
  2.             $.formValidator.initConfig({formid:"register",onerror:function(msg){alert(msg);return false;},onsuccess:function(){alert('ddd');return true;}});  
  3.             $("#username").formValidator({tipid:"nameTip",onshow:"必填",onfocus:"使用者名稱至少6個字元,最多20個字元",oncorrect:"該使用者名稱可以註冊"}).inputValidator({min:6,max:20,onerror:"你輸入的使用者名稱不合法,請確認"}).regexValidator({regexp:"username",datatype:"enum",onerror:"使用者名稱格式不正確"});  
  4.             $("#password").formValidator({tipid:"passwordTip1",onshow:"必填",onfocus:"密碼不能為空,至少6位",oncorrect:"密碼輸入合法"}).inputValidator({min:6,empty:{leftempty:false,rightempty:false,emptyerror:"密碼兩邊不能有空格"},onerror:"密碼不能為空,請確認"});  
  5.             $("#password2").formValidator({tipid:"passwordTip2",onshow:"必填",onfocus:"兩次密碼輸入必須一致哦",oncorrect:"密碼確認正確"}).inputValidator({min:6,empty:{leftempty:false,rightempty:false,emptyerror:"重複密碼兩邊不能有空格"},onerror:"重複密碼不能為空,請確認"}).compareValidator({desid:"password",operateor:"=",onerror:"兩次密碼輸入不一致,請重新確認"});  
  6.             $(":radio[name='gender']").formValidator({tipid:"genderTip",onshow:"必填",onfocus:"預設為男性",oncorrect:"性別選擇正確",defaultvalue:["0"]}).inputValidator({min:1,max:1,onerror:"性別忘記選了,請確認"});  
  7.             $("#age").formValidator({onshow:"必填",onfocus:"請輸入年齡,範圍在18至100之間",oncorrect:"恭喜你,你輸對了"}).inputValidator({min:18,max:100,type:"value",onerrormin:"你輸入的值必須大於等於18",onerror:"年齡必須在18-100之間,請確認"});  
  8.             $("#birth").focus(function(){WdatePicker({skin:'whyGreen',oncleared:function(){$(this).blur();},onpicked:function(){$(this).blur();}})}).formValidator({onshow:"必填",onfocus:"請選擇出生日期",oncorrect:"出生日期輸入合法"}).inputValidator({min:"1900-01-01",max:"2099-01-01",type:"date",onerror:"日期必須在/"1900-01-01/"和/"2099-01-01/"之間"});  
  9.             $("#idCardNo").formValidator({onshow:"可選",onfocus:"請輸入15或18位身份證",oncorrect:"輸入正確"}).functionValidator({fun:isCardID});  
  10.             $("#email").formValidator({onshow:"必填",onfocus:"必須輸入合法的郵箱地址",oncorrect:"郵箱填寫正確",forcevalid:true}).inputValidator({min:6,max:100,onerror:"郵箱地址的長度限制在6至100字元以內"}).regexValidator({regexp:"^([//w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([//w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$",onerror:"你輸入的郵箱格式不正確"});  
  11.             $("#education").formValidator({onshow:"必填",onfocus:"請選擇真實的學歷",oncorrect:"學歷選擇正確"}).inputValidator({min:1,onerror: "學歷不能丟!"});  
  12.             $(":checkbox[name='interests']").formValidator({tipid:"interestsTip",onshow:"必須選擇一個",onfocus:"得選擇1個",oncorrect:"興趣愛好已選"}).inputValidator({min:1,onerror:"沒選擇好哦"});  
  13.             $("#telephoneNo").formValidator({empty:true,onshow:"可選",onfocus:"最好是留一下吧",oncorrect:"手機號碼填寫正確",onempty:"還真不留"}).inputValidator({min:11,max:11,onerror:"手機號碼必須是11位的,請確認"}).regexValidator({regexp:"mobile",datatype:"enum",onerror:"你輸入的手機號碼格式不正確"});;  
  14.             $("#phoneNo").formValidator({empty:true,onshow:"可選",onfocus:"格式例如:0755-66666666",oncorrect:"聯絡電話填寫正確",onempty:"哎,真得沒留"}).regexValidator({regexp:"^[[0-9]{3}-|/[0-9]{4}-]?([0-9]{8}|[0-9]{7})?$",onerror:"你輸入的聯絡電話格式不正確"});  
  15.             $("#desc").formValidator({onshow:"必填",onfocus:"描述至少要輸入10個漢字或20個字元",oncorrect:"輸入合法",defaultvalue:"得寫點東東..."}).inputValidator({min:20,onerror:"你輸入的描述長度不正確,請確認"});  
  16.         });  
<textarea style="DISPLAY: none" class="javascript" rows="15" cols="50" name="code">$(document).ready(function(){ $.formValidator.initConfig({formid:&quot;register&quot;,onerror:function(msg){alert(msg);return false;},onsuccess:function(){alert('ddd');return true;}}); $(&quot;#username&quot;).formValidator({tipid:&quot;nameTip&quot;,onshow:&quot;必填&quot;,onfocus:&quot;使用者名稱至少6個字元,最多20個字元&quot;,oncorrect:&quot;該使用者名稱可以註冊&quot;}).inputValidator({min:6,max:20,onerror:&quot;你輸入的使用者名稱不合法,請確認&quot;}).regexValidator({regexp:&quot;username&quot;,datatype:&quot;enum&quot;,onerror:&quot;使用者名稱格式不正確&quot;}); $(&quot;#password&quot;).formValidator({tipid:&quot;passwordTip1&quot;,onshow:&quot;必填&quot;,onfocus:&quot;密碼不能為空,至少6位&quot;,oncorrect:&quot;密碼輸入合法&quot;}).inputValidator({min:6,empty:{leftempty:false,rightempty:false,emptyerror:&quot;密碼兩邊不能有空格&quot;},onerror:&quot;密碼不能為空,請確認&quot;}); $(&quot;#password2&quot;).formValidator({tipid:&quot;passwordTip2&quot;,onshow:&quot;必填&quot;,onfocus:&quot;兩次密碼輸入必須一致哦&quot;,oncorrect:&quot;密碼確認正確&quot;}).inputValidator({min:6,empty:{leftempty:false,rightempty:false,emptyerror:&quot;重複密碼兩邊不能有空格&quot;},onerror:&quot;重複密碼不能為空,請確認&quot;}).compareValidator({desid:&quot;password&quot;,operateor:&quot;=&quot;,onerror:&quot;兩次密碼輸入不一致,請重新確認&quot;}); $(&quot;:radio[name='gender']&quot;).formValidator({tipid:&quot;genderTip&quot;,onshow:&quot;必填&quot;,onfocus:&quot;預設為男性&quot;,oncorrect:&quot;性別選擇正確&quot;,defaultvalue:[&quot;0&quot;]}).inputValidator({min:1,max:1,onerror:&quot;性別忘記選了,請確認&quot;}); $(&quot;#age&quot;).formValidator({onshow:&quot;必填&quot;,onfocus:&quot;請輸入年齡,範圍在18至100之間&quot;,oncorrect:&quot;恭喜你,你輸對了&quot;}).inputValidator({min:18,max:100,type:&quot;value&quot;,onerrormin:&quot;你輸入的值必須大於等於18&quot;,onerror:&quot;年齡必須在18-100之間,請確認&quot;}); $(&quot;#birth&quot;).focus(function(){WdatePicker({skin:'whyGreen',oncleared:function(){$(this).blur();},onpicked:function(){$(this).blur();}})}).formValidator({onshow:&quot;必填&quot;,onfocus:&quot;請選擇出生日期&quot;,oncorrect:&quot;出生日期輸入合法&quot;}).inputValidator({min:&quot;1900-01-01&quot;,max:&quot;2099-01-01&quot;,type:&quot;date&quot;,onerror:&quot;日期必須在/&quot;1900-01-01/&quot;和/&quot;2099-01-01/&quot;之間&quot;}); $(&quot;#idCardNo&quot;).formValidator({onshow:&quot;可選&quot;,onfocus:&quot;請輸入15或18位身份證&quot;,oncorrect:&quot;輸入正確&quot;}).functionValidator({fun:isCardID}); $(&quot;#email&quot;).formValidator({onshow:&quot;必填&quot;,onfocus:&quot;必須輸入合法的郵箱地址&quot;,oncorrect:&quot;郵箱填寫正確&quot;,forcevalid:true}).inputValidator({min:6,max:100,onerror:&quot;郵箱地址的長度限制在6至100字元以內&quot;}).regexValidator({regexp:&quot;^([//w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([//w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$&quot;,onerror:&quot;你輸入的郵箱格式不正確&quot;}); $(&quot;#education&quot;).formValidator({onshow:&quot;必填&quot;,onfocus:&quot;請選擇真實的學歷&quot;,oncorrect:&quot;學歷選擇正確&quot;}).inputValidator({min:1,onerror: &quot;學歷不能丟!&quot;}); $(&quot;:checkbox[name='interests']&quot;).formValidator({tipid:&quot;interestsTip&quot;,onshow:&quot;必須選擇一個&quot;,onfocus:&quot;得選擇1個&quot;,oncorrect:&quot;興趣愛好已選&quot;}).inputValidator({min:1,onerror:&quot;沒選擇好哦&quot;}); $(&quot;#telephoneNo&quot;).formValidator({empty:true,onshow:&quot;可選&quot;,onfocus:&quot;最好是留一下吧&quot;,oncorrect:&quot;手機號碼填寫正確&quot;,onempty:&quot;還真不留&quot;}).inputValidator({min:11,max:11,onerror:&quot;手機號碼必須是11位的,請確認&quot;}).regexValidator({regexp:&quot;mobile&quot;,datatype:&quot;enum&quot;,onerror:&quot;你輸入的手機號碼格式不正確&quot;});; $(&quot;#phoneNo&quot;).formValidator({empty:true,onshow:&quot;可選&quot;,onfocus:&quot;格式例如:0755-66666666&quot;,oncorrect:&quot;聯絡電話填寫正確&quot;,onempty:&quot;哎,真得沒留&quot;}).regexValidator({regexp:&quot;^[[0-9]{3}-|/[0-9]{4}-]?([0-9]{8}|[0-9]{7})?$&quot;,onerror:&quot;你輸入的聯絡電話格式不正確&quot;}); $(&quot;#desc&quot;).formValidator({onshow:&quot;必填&quot;,onfocus:&quot;描述至少要輸入10個漢字或20個字元&quot;,oncorrect:&quot;輸入合法&quot;,defaultvalue:&quot;得寫點東東...&quot;}).inputValidator({min:20,onerror:&quot;你輸入的描述長度不正確,請確認&quot;}); });</textarea> 

validator.css

  1. .onCorrect  
  2. {  
  3.     background:url(../images/reg4.gif) no-repeat;  
  4.     padding-left:25px;  
  5.     font-size12px;  
  6.     line-height:22px;   
  7.     vertical-align:middle;  
  8. }  
  9. .onShow  
  10. {  
  11.     background:url(../images/reg1.gif) no-repeat;   
  12.     padding-left:25px;   
  13.     font-size12px;  
  14.     line-height:22px;   
  15.     vertical-align:middle;  
  16. }  
  17. .onFocus  
  18. {  
  19.     background:#E9F0FF url(../images/reg2.gif) no-repeat;   
  20.     padding-left:25px;   
  21.     font-size12px;  
  22.     line-height:22px;   
  23.     vertical-align:middle;  
  24. }  
  25. .onError  
  26. {  
  27.     background:#FFF2E9 url(../images/reg3.gif) no-repeat;  
  28.     padding-left:25px;  
  29.     font-size12px;  
  30.     line-height:22px;   
  31.     vertical-align:middle;  
  32. }  
  33. .onLoad  
  34. {  
  35.    background:#E9FFEB url(../images/loading.gif) no-repeat 3px 3px;  
  36.    padding-left:25px;  
  37.    font-size12px;  
  38.    line-height:22px;   
  39.    vertical-align:middle;  
  40. }  
<textarea style="DISPLAY: none" class="css" rows="15" cols="50" name="code">.onCorrect { background:url(../images/reg4.gif) no-repeat; padding-left:25px; font-size: 12px; line-height:22px; vertical-align:middle; } .onShow { background:url(../images/reg1.gif) no-repeat; padding-left:25px; font-size: 12px; line-height:22px; vertical-align:middle; } .onFocus { background:#E9F0FF url(../images/reg2.gif) no-repeat; padding-left:25px; font-size: 12px; line-height:22px; vertical-align:middle; } .onError { background:#FFF2E9 url(../images/reg3.gif) no-repeat; padding-left:25px; font-size: 12px; line-height:22px; vertical-align:middle; } .onLoad { background:#E9FFEB url(../images/loading.gif) no-repeat 3px 3px; padding-left:25px; font-size: 12px; line-height:22px; vertical-align:middle; }</textarea> 

web.xml

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee   
  5.     http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  
  6.     <filter>  
  7.         <filter-name>struts2</filter-name>  
  8.         <filter-class>  
  9.             org.apache.struts2.dispatcher.FilterDispatcher  
  10.         </filter-class>  
  11.     </filter>  
  12.     <filter-mapping>  
  13.         <filter-name>struts2</filter-name>  
  14.         <url-pattern>*.action</url-pattern>  
  15.     </filter-mapping>  
  16.     <welcome-file-list>  
  17.         <welcome-file>index.jsp</welcome-file>  
  18.     </welcome-file-list>  
  19. </web-app>  
 

 


 

 

 

 

 

 

相關文章