在web开发中,字符串的处理是时常遇见的,而且有些方面的处理是每次都必需的,例如:为空、过滤敏感字符等等,故将这些常用的处理方法封装在一个字符串工具类里是必要的,而且封装为静态方法是比较好的方法。(为了有选择的选用,将每个功能划分为独立的模块)
StringUtil.java
public class StringUtil {
/判断字符串是否为null----- args.equalsIgnoreCase("null")当向数据库中插入字符串时判断 public static boolean StringNull(String args){ if(args == null || args.trim().length() == 0 || args.equalsIgnoreCase("null")){ return true; }else{ return false; } } |
//若源字符串为null或长度为0,将target的值赋给源字符串,即给源字符串默认值 public static String changeNull(String source,String target){ if(source == null || source.trim().length() == 0){ return target; }else{ return source; } } |
//过滤敏感字符 public static String filterHtml(String input){ input = input.replaceAll(";", ""); input = input.replaceAll("&", "&"); input = input.replaceAll("<", "<"); input = input.replaceAll(">", ">"); input = input.replaceAll(" ", " "); input = input.replaceAll("'", "'"); input = input.replaceAll("/"", """); input = input.replaceAll("/n", "<br>"); return input; } | } |