Mindon.IDEA

Air off, Mind on ~ / Javascript+Golang, Sci, Health… /

Struts ActionForm字段校验(JAVA)

BlogMS original blog key: 1000141910, blog id: airoff History stat: 浏览/评论:392/0 , 日期:2005年1月7日 10:05

package com.mindon.util;

/**============================================================

  • 文件: com.mindon.util.FieldCheck

  • 功能: 校验函数库

  • 所含类:FieldCheck

  • 修改记录:

  • 日期 作者 内容


  • 2003-11-17 fengrj 校验函数

  • ============================================================*/

import org.apache.struts.action.*;

import javax.servlet.http.*;

import java.lang.StringBuffer;

import java.util.Date;

import org.jdom.*;

import org.jdom.input.*;

import org.jdom.output.*;

import java.io.File;

import java.io.IOException;

import java.util.HashMap;

public class FieldCheck {

private ActionErrors errors = null;

private HttpServletRequest request = null;

private String moduleName;

private static String errorURL = "org.apache.struts.action.ERROR";

private static String confName = "./definition.xml";

private static HashMap xMRootMap = new HashMap();

public static String L_CONFIRM = ".confirm";

public static String L_SELECT_NONE = ".selectNone";

public static String L_DUPLICATE = ".duplicate";

public static String L_EXISTENT = ".existent";

public static String L_INEXISTENT = ".inexistent";

public static String L_LOGIN = ".login";

public static String L_LOOP = ".loop";

public static String L_FAIL = ".fail";

public static String L_REQUIRED = ".required";

public static String L_NEEDONE = ".needone";

public static String L_FALSE_LENGTH = ".falseLength";

public static String L_CHOOSE_NONE = ".needed";

public static String L_OVERFLOW = ".overflow";

public static String L_DIFFERENT = ".different";

public static String L_FALSE_NUMBER = ".fasleNumber";

public static String L_INT_NEEDED = ".intNeeded";

public static String L_DOUBLE_NEEDED = ".doubleNeeded";

public static String L_FALSE_DATE = ".falseDate";

public static String L_BEFORE_DATE = ".beforeDate";

public static String L_AFTER_DATE = ".afterDate";

public static String L_FALSE_RATE = ".falseRate";

public static String L_FALSE_RANGE = ".falseRange";

public static String L_FALSE_IDCARD = ".falseIdCard";

private static java.text.SimpleDateFormat datefmt = new java.text.SimpleDateFormat("yyyy年M月dd日");

public FieldCheck(ActionErrors errors,

HttpServletRequest request,

String moduleName)

{

this.errors = errors;

this.request = request;

this.moduleName = moduleName;

}

public static boolean error(ActionErrors errors,

HttpServletRequest request,

String label,

StringBuffer message)

{

StringBuffer url = (new StringBuffer("error")).append(label);

errors.add(label.substring(1), new ActionError(url.toString(), message.toString()));

request.setAttribute(errorURL, errors);

return true;

}

public static boolean error(ActionErrors errors,

HttpServletRequest request,

String label,

String module)

{

return error(errors, request, label, module, null, null);

}

public static boolean error(ActionErrors errors,

HttpServletRequest request,

String label,

String module,

String name)

{

return error(errors, request, label, module, name, null);

}

public static boolean error(ActionErrors errors,

HttpServletRequest request,

String label,

String module,

String name,

String extdesc)

{

System.out.println("[-FAIL->>Error:" +module +(null!=name?"-"+name:""));

StringBuffer url = (new StringBuffer("error")).append(label);

errors.add(null!=name?name:module, new ActionError(url.toString(), description(module, name), extdesc));

request.setAttribute(errorURL, errors);

return true;

}

public boolean isEmpty(String name)

{

if(null==request.getParameter(name)

|| "".equals(request.getParameter(name))) {

return true;

}

return false;

}

// 带参校验函数 —>>> 开始

public boolean isEmpty(String field, Object value)

{

if(null == value || value.toString().length() < 1) {

return error(L_REQUIRED, field, description(field));

}

return false;

}

public boolean falseLength(String field, Object value, int maxLength)

{

if(!isEmpty(field) && value.toString().length() > maxLength) {

return error(L_FALSE_LENGTH, field, description(field), "(" +maxLength +")");

}

return false;

}

public boolean falseNumber(String field, Object value)

{

if(!isEmpty(field) && null == value) {

return error(L_FALSE_NUMBER, field, description(field));

}

return false;

}

public boolean intNeeded(String field, Object value)

{

if(!isEmpty(field) && null == value) {

return error(L_INT_NEEDED, field, description(field));

}

return false;

}

public boolean doubleNeeded(String field, Object value)

{

if(!isEmpty(field) && null == value) {

return error(L_DOUBLE_NEEDED, field, description(field));

}

return false;

}

public boolean overflow(String field, Double value, double limit, int precision)

{

if(isEmpty(field)) return false;

int dot = -1;

String param = request.getParameter(field);

if(null != value) dot = param.indexOf(".");

if(null != value && (value.doubleValue() > limit

|| (dot>=0 && precision < param.length() -dot -1))) {

String limitstr = Double.toString(limit);

String extdesc = "(" +(Integer.parseInt(limitstr.substring(limitstr.indexOf("E") +1)) +precision) +"," +precision +")";

return error(L_OVERFLOW, field, description(field), extdesc);

}

return false;

}

public boolean chooseNone(String field, Object value)

{

if(null == value || value.toString().length() < 1) {

return error(L_CHOOSE_NONE, field, description(field));

}

return false;

}

public boolean different(String field, Object value, Object origin)

{

if(isEmpty(field, origin)) return true;

if(!origin.equals(value)) {

return error(L_DIFFERENT, field, description(field), origin.toString());

}

return false;

}

public boolean different(String field, Object value, String olabel, Object origin)

{

if(isEmpty(field, origin)) return true;

if(!origin.equals(value)) {

return error(L_DIFFERENT, field, description(field), description(olabel));

}

return false;

}

public boolean falseDate(String field, Object value)

{

if(!isEmpty(field) && null == value) {

return error(L_FALSE_DATE, field, description(field));

}

return false;

}

public boolean beforeDate(String field, Date base, Date date)

{

if(!isEmpty(field) && null != base && null != date) {

base.setHours(0); base.setMinutes(0); base.setSeconds(0);

date.setHours(0); date.setMinutes(0); date.setSeconds(0);

if(base.compareTo(date)>0) return error(L_BEFORE_DATE, field, description(field), datefmt.format(base));

}

return false;

}

public boolean afterDate(String field, Date base, Date date)

{

if(!isEmpty(field) && null != base && null != date) {

base.setHours(0); base.setMinutes(0); base.setSeconds(0);

date.setHours(0); date.setMinutes(0); date.setSeconds(0);

if(base.compareTo(date)<0) return error(L_AFTER_DATE, field, description(field), datefmt.format(base));

}

return false;

}

public boolean beforeToday(String field, Date date)

{

return beforeDate(field, new Date(), date);

}

public boolean afterToday(String field, Date date)

{

return afterDate(field, new Date(), date);

}

//decimal(7,4)

public boolean falseRate(String field, Double value)

{

if(doubleNeeded(field, value)) return true;

if(overflow(field, value, 1000d, 4)) return true;

if(!isEmpty(field)) {

if(Double.compare(value.doubleValue(), 100d) > 0

|| Double.compare(value.doubleValue(), 0d) < 0) {

return error(L_FALSE_RATE, field, description(field), "[0, 100]");

}

}

return false;

}

public boolean falseRange(String field, Integer[] range, Integer value)

{

if(intNeeded(field, value)) return true;

if(!isEmpty(field)) {

boolean isIn = false;

String extdesc = "";

if(range.length <= 0) {

isIn = true; //没指定范围

} else if(range.length == 1) {

if(null == range[0]) {

isIn = true;

} else {

isIn = (range[0].compareTo(value) <= 0);

extdesc = "大于" +range[0];

}

} else if(range.length == 2) {

isIn = ((null==range[0] || range[0].compareTo(value) <= 0)

&& (null==range[1] || range[1].compareTo(value) >= 0));

if(null != range[0]) extdesc = "大于" +range[0];

if(null != range[1]) extdesc = ("".equals(extdesc)?"":", ") +"小于" +range[1];

}

if(!isIn) return error(L_FALSE_RANGE, field, description(field), extdesc);

}

return false;

}

//身份证号码校验

public boolean falseIdCard(String field, String value)

{

if(!isEmpty(field)) {

int idclen = value.length();

String fieldesc = "身份证号码"; // description(field);

String extdesc = "";

boolean idCardTrue = true;

int pos = value.indexOf(" ");

if(pos>=0) {

extdesc = "第" +(pos +1) +"个字符不能为空格";

idCardTrue = false;

} else if(idclen != 15 && idclen != 18) { //检查身份证号码长度

extdesc = "长度必须为15或者18";

idCardTrue = false;

} else {

boolean isOldCard = (idclen==15);

if(!dateValid(value.substring(6, (isOldCard?12:14)))) { //检查出生日期

extdesc = "出生日期无效";

idCardTrue = false;

} else {

long verify = 0, modBase = 11;

StringBuffer errExt = new StringBuffer();

try {

int kmax = idclen -(isOldCard?0:1);

for(int k=kmax; k>0; k–) {

errExt = new StringBuffer();

errExt.append(",第").append(k).append("位“").append(value.substring(k-1, k)).append("”有误");

verify += Long.parseLong(value.substring(k-1, k))*((long)(2<<(kmax-k))%modBase);

}

if(!isOldCard) {

verify = (verify%modBase);

String vcode = value.substring(idclen -1);

String rightc = "";

if(verify == 0 && !("1".equals(vcode))) {

rightc = "1";

idCardTrue = false;

} else if(verify == 1 && !("0".equals(vcode))) {

rightc = "0";

idCardTrue = false;

} else if(verify == 2 && !("X".equals(vcode))) {

rightc = "X";

idCardTrue = false;

} else if(verify > 2 && !((String.valueOf(modBase -verify +1)).equals(vcode))) {

rightc = (String.valueOf(modBase -verify +1));

idCardTrue = false;

}

if(!idCardTrue) extdesc = "校验位有误(应为" +rightc+")";

}

} catch(NumberFormatException e) {

extdesc = (isOldCard?"旧号码必须全由数字0~9组成":"新号码前17位必须由数字0~9组成") +errExt.toString();

idCardTrue = false;

}

}

}

if(!idCardTrue) return error(L_FALSE_IDCARD, field, fieldesc, extdesc);

}

return false;

}

public static void duplicate(ActionErrors errors, HttpServletRequest request, String module)

{

error(errors, request, L_DUPLICATE, module, null, null);

}

private boolean error(String label, String field, String paramA)

{

System.out.println("[-FAIL->>Name:" +field +"<,Value:" +request.getParameter(field) +"<");

StringBuffer url = (new StringBuffer("error")).append(label);

errors.add(field, new ActionError(url.toString(), paramA));

request.setAttribute(errorURL, errors);

return true;

}

private boolean error(String label, String field, String paramA, String paramB)

{

System.out.println("[-FAIL->>Name:" +field +"<,Value:" +request.getParameter(field) +"<");

StringBuffer url = (new StringBuffer("error")).append(label);

errors.add(field, new ActionError(url.toString(), paramA, paramB));

request.setAttribute(errorURL, errors);

return true;

}

private boolean error(String label, String field, String paramA, String paramB, String paramC)

{

System.out.println("[-FAIL->>Name:" +field +"<,Value:" +request.getParameter(field) +"<");

StringBuffer url = (new StringBuffer("error")).append(label);

errors.add(field, new ActionError(url.toString(), paramA, paramB, paramC));

request.setAttribute(errorURL, errors);

return true;

}

private boolean dateValid(String datestr)

{

String date = datestr;

if(date.indexOf("-") > 0) date = date.replaceAll("-", "");

if(date.indexOf("/") > 0) date = date.replaceAll("/", "");

if(null == date) return false;

int len = date.length();

if(len != 6 && len != 8) return false;

try {

int year = Integer.parseInt(date.substring(0, len-4));

int month = Integer.parseInt(date.substring(len-4, len-2));

int day = Integer.parseInt(date.substring(len-2));

Date dchk = new Date(year -(len==8?1900:0), month-1, day);

if((year == dchk.getYear() +(len==8?1900:0))

&& (month == dchk.getMonth()+1)

&& (day == dchk.getDate()))

return true;

} catch(NumberFormatException e) {

return false;

}

return false;

}

/**

  • 获取指定xml文件的根结点,并保存

  • @param module 模块名称

*/

private static void xbuild(String module)

{

Document doc = null;

try {

SAXBuilder sax = new SAXBuilder();

System.out.println("[–>>Reading XML configuration file &quot;" + confName +"&quot;…");

doc = sax.build(new File(confName));

} catch(IOException e) {

//e.printStackTrace();

System.out.println("[-FAIL->> " +e.getMessage());

} catch(JDOMException e) {

//e.printStackTrace();

System.out.println("[-FAIL->> " +e.getMessage());

} finally {

if(null != doc && null != doc.getRootElement()) {

Element root = doc.getRootElement();

if(null != root) root = root.getChild(module, root.getNamespace(""));

if(null != root) {

xMRootMap.put(module, root);

} else {

System.out.println("[-FAIL->> " +module +" NOT-FOUND in " +confName);

}

}

}

}

/**

  • 获取XML文件中指定节点参数描述

  • @param name 参数名称

  • @return 若参数存在,返回其描述,否则返回空串

*/

private String description(String name)

{

return description(moduleName, name);

}

public static String description(String module, String name)

{

if(!xMRootMap.containsKey(module)) xbuild(module);

String pmstr = "";

try {

Element root = (Element)xMRootMap.get(module);

if(null == name) return root.getAttributeValue("description");

if(null != root) {

Element elm = root.getChild(name, root.getNamespace(""));

if(null != elm) pmstr = elm.getText();

else xbuild(module);

}

} catch(NullPointerException e) {

//e.printStackTrace();

System.out.println("[-FAIL->> " +module +" NOT-FOUND in " +confName);

}

return pmstr;

}

}

Comments