org.springframework.security.web.util.TextEscapeUtils

经常看到一些开发团队在项目开发中,想重用一些代码,最低层次的代码重用其实就是写工具类,不过我这里想说的是,在web项目中常用的一些工具类不妨看一下springframework中的util包中的类,非常实用,最近在看springSecurity源码时就看到这样的一个类TextEscapeUtils,作用是用来进行URL编码的,并且做一些用户表单数据的非法输入字符的判断,具体代码如下:

public abstract class TextEscapeUtils {

    public final static String escapeEntities(String s) {
        if (s == null || s.length() == 0) {
            return s;
        }

        StringBuilder sb = new StringBuilder();

        for (int i=0; i < s.length(); i++) {
            char c = s.charAt(i);

            if (c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9') {
                sb.append(c);
            } else if(c == '<') {
                sb.append("<");
            } else if (c == '>') {
                sb.append(">");
            } else if (c == '&') {
                sb.append("&");
            } else if (Character.isWhitespace(c)) {
                sb.append("&#").append((int)c).append(";");
            } else if (Character.isISOControl(c)) {
                // ignore control chars
            } else if (Character.isHighSurrogate(c)) {
                if (i + 1 >= s.length()) {
                    // Unexpected end
                    throw new IllegalArgumentException("Missing low surrogate character at end of string");
                }
                char low = s.charAt(i + 1);

                if (!Character.isLowSurrogate(low)) {
                    throw new IllegalArgumentException("Expected low surrogate character but found value = " + (int)low);
                }

                int codePoint = Character.toCodePoint(c, low);
                if (Character.isDefined(codePoint)) {
                    sb.append("&#").append(codePoint).append(";");
                }
                i++; // skip the next character as we have already dealt with it
            } else if (Character.isLowSurrogate(c)) {
                throw new IllegalArgumentException("Unexpected low surrogate character, value = " + (int)c);
            } else if (Character.isDefined(c)) {
                sb.append("&#").append((int) c).append(";");
            }
            // Ignore anything else
        }

        return sb.toString();
    }
}

 

posted @ 2012-01-07 15:35  杭州胡欣  阅读(1283)  评论(0编辑  收藏  举报