下載地址:http://codeshop.googlecode.com/files/idchecker.zip
提供給外部調用的cn.idchecker.check.Checker類的相關方法如下表:
方法 | 方法作用 | 參數及返回值 |
Checker(String num) | 構造方法 | 參數num爲18位身份證號碼的字符串 |
boolean checkLength() | 驗證身份證長度是否正確 | 長度爲18,則返回true,否則返回false |
boolean checkBirth() | 驗證出生生日碼是否合法 | 合法則返回true,否則返回false |
boolean checkAddr() | 驗證地址碼是否存在 | 存在則返回true,否則返回false |
boolean checkCheckCode() | 計算校驗碼是否正確 | 正確則返回true,否則返回false |
boolean check() | 總的身份證驗證,驗證順序:長度 -> 生日 -> 最後一位校驗碼 -> 地址 | 若遇到有一項目不合法即返回false,所有驗證通過才返回true。驗證後,可通過調用getErrorMsg()方法獲取錯誤信息 |
boolean checkAll() | 總的身份證驗證,驗證項目包括長度、地址、生日、最後一位校驗碼 | 身份證合法則返回true,否則false。驗證後,可調用getErrorMsgs()方法獲取錯誤信息集合 |
String getBirth() | 獲取出生年月日 | 返回“2010年01月12日”格式的生日字符串通串 |
String getAddr() | 獲取公民籍貫 | 返回籍貫字符串("xx省xx市xx縣”) |
String getSex() | 獲取性別 | 返回“男”或“女” |
String getErrorMsg() | 獲取錯誤信息 | 返回錯誤信息字符串 |
public Set<String> getErrorMsgs() | 獲取錯誤信息集合 | 返回錯誤信息集合 |
用法舉例 1 :解壓縮“idchecker.zip”,將其目錄下的“idchecker.jar” 包引進Java Project中,以下是測試程序:
public static void main(String[] args) {
Checker checker = new Checker("44010619860710145X");
System.out.println("出生年月日 : " + checker.getBirth());
System.out.println("性別 :" + checker.getSex());
System.out.println("居民地址 : " + checker.getAddr());
System.out.println("身份證號碼是否合法 : " + checker.check() + " " + checker.getErrorMsg());
checker.checkAll();
for(String msg : checker.getErrorMsgs()) {
System.out.print(msg + " | ");
}
}
}
運行結果:
性別 :男
居民地址 : 廣東省廣州市天河區
身份證號碼是否合法 : true
用法舉例 2 :將“idchecker.jar” 包引進到Web Project的lib目錄下,以下是測試程序:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>測試idchecker組件</title>
</head>
<body>
<h1>身份證驗證</h1>
<%
String id = request.getParameter("ID");
if(id != null && !"".equals(id.trim())){
cn.idchecker.check.Checker checker = new cn.idchecker.check.Checker(id);
if(checker.check()) {
out.print(checker.getSex() + "<br/>");
out.print(checker.getBirth() + "<br/>");
out.print(checker.getAddr());
} else {
out.print("身份證不合法!" + "<br/>");
out.print(checker.getErrorMsg());
}
}
%>
<form action="input.jsp" method="post">
身份證號碼 :<input name="ID" type="text" value="<%=id %>"/>
<input type="submit" value="驗證"/>
</form>
</body>
</html>
運行結果: