J2EE数据验证的一些开发建议(二)

2014-11-24 02:29:20 · 作者: · 浏览: 7
user selection against a list of options public class validator { ... public static boolean validateoption(object[] options, object value) { boolean isvalidvalue = false; try { list list = arrays.aslist(options); if (list != null) { isvalidvalue = list.contains(value); } } catch (exception e) { } return isvalidvalue; } ... } ... // allowed options string[] options = {"option1", "option2", "option3"); // verify that the user selection is one of the allowed options string userselection = request.getparameter("userselection"); if (validator.validateoption(options, userselection)) { // valid user selection, continue processing request ... }

[6] 字段模式
始终检查用户输入与由功能需求定义的模式是否匹配。例如,如果 username 字段应仅允许字母数字字符,且不区分大小写,那么请使用以下正则表达式:^[a-za-z0-9]*$。
执行正则表达式验证的示例:
Java代码
// example to validate that a given value matches a specif ied pattern // using the java 1.4 regular expression package import java.util.regex.pattern; import java.util.regexe.matcher; public class validator { ... public static boolean matchpattern(string value, string expression) { boolean match = false; if (validaterequired(expression)) { match = pattern.matches(expression, value); } return match; } ... } ... // verify that the username request parameter is alphanumeric string username = request.getparameter("username"); if (validator.matchpattern(username, "^[a-za-z0-9]*$")) { / / username is valid, continue processing request ... }

[7]cookie值使用javax.servlet.http.cookie对象来验证cookie值。适用于cookie值的相同的验证规则(如上所述)取决于应用程序需求(如验证必需值、验证长度等)。
验证必需 cookie 值的示例:

Java代码
// example to validate a required cookie value // first retrieve all available cookies submitted in the http request cookie[] cookies = request.getcookies(); if (cookies != null) { // f ind the "user" cookie for (int i=0; i

[8] http 响应
[8-1] 过滤用户输入要保护应用程序免遭跨站点脚本编制的攻击,请通过将敏感字符转换为其对应的字符实体来清理 html。这些是 html 敏感字符:< > " ' % ; ) ( & +。
以下示例通过将敏感字符转换为其对应的字符实体,来过滤指定字符串:
Java代码
// example to f ilter sensitive data to prevent cross-site scripting public class validator { ... public static string f ilter(string value) { if (value == null) { return null; } stringbuf fer result = new stringbuf fer(value.length()); for (int i=0; i': result.append("&gt;"); break; case '"': result.append("&quot;"); break; case '\'': result.append("&#39;"); break; case '%': result.append("&#37;"); break; case ';': result.append("&#59;"); break; case '(': result.append("&#40;"); break; case ')': result.append("&#41;"); break; case '&': result.append("&amp;"); break; case '+': result.append("&#43;"); break; default: