32

もちろん、私はjava.net.URLEncoderandjava.net.URLDecoderクラスに精通しています。ただし、必要なのは HTML スタイルのエンコーディングだけです。' '( などに置き換えたくありません'+')。HTMLエンコーディングのみを行うクラスに組み込まれたJDKを認識していません。ありますか?私は他の選択肢を認識しています (たとえば、Jakarta Commons Lang 'StringEscapeUtils'ですが、これが必要なプロジェクトに別の外部依存関係を追加したくありません。

最近の JDK (別名 5 または 6) に何かが追加されて、私が知らないことを実行できることを願っています。それ以外の場合は、自分でロールバックする必要があります。

4

7 に答える 7

45

これを行うための JDK 組み込みクラスはありませんが、Jakarta commons-lang ライブラリの一部です。

String escaped = StringEscapeUtils.escapeHtml3(stringToEscape);
String escaped = StringEscapeUtils.escapeHtml4(stringToEscape);

JavaDocをチェックしてください

依存関係の追加は、通常、jar をどこかにドロップするのと同じくらい簡単です。また、commons-lang には非常に多くの便利なユーティリティがあるため、多くの場合、搭載する価値があります。

于 2009-03-17T21:52:33.397 に答える
14

簡単な方法は次のようです。

/**
 * HTML encode of UTF8 string i.e. symbols with code more than 127 aren't encoded
 * Use Apache Commons Text StringEscapeUtils if it is possible
 *
 * <pre>
 * escapeHtml("\tIt's timeto hack & fun\r<script>alert(\"PWNED\")</script>")
 *    .equals("&#9;It&#39;s time to hack &amp; fun&#13;&lt;script&gt;alert(&quot;PWNED&quot;)&lt;/script&gt;")
 * </pre>
 */
public static String escapeHtml(String rawHtml) {
    int rawHtmlLength = rawHtml.length();
    // add 30% for additional encodings
    int capacity = (int) (rawHtmlLength * 1.3);
    StringBuilder sb = new StringBuilder(capacity);
    for (int i = 0; i < rawHtmlLength; i++) {
        char ch = rawHtml.charAt(i);
        if (ch == '<') {
            sb.append("&lt;");
        } else if (ch == '>') {
            sb.append("&gt;");
        } else if (ch == '"') {
            sb.append("&quot;");
        } else if (ch == '&') {
            sb.append("&amp;");
        } else if (ch < ' ' || ch == '\'') {
            // non printable ascii symbols escaped as numeric entity
            // single quote ' in html doesn't have &apos; so show it as numeric entity &#39;
            sb.append("&#").append((int)ch).append(';');
        } else {
            // any non ASCII char i.e. upper than 127 is still UTF
            sb.append(ch);
        }
    }
    return sb.toString();
}

ただし、ASCII以外のすべての記号をエスケープする必要がある場合、つまり、エンコードされたテキストを7ビットエンコードで送信する場合は、最後の記号を次のように置き換えます。

        } else {
            // encode non ASCII characters if needed
            int c = (ch & 0xFFFF);
            if (c > 127) {
                sb.append("&#").append(c).append(';');
            } else {
                sb.append(ch);
            }
        }
于 2012-01-12T15:53:33.030 に答える
10

どうやら、答えは「いいえ」です。残念ながら、これは私が何かをしなければならず、そのための新しい外部依存関係を短期的に追加できなかったケースでした。Commons Lang を使用することが最善の長期的な解決策であるという点で、私はすべての人に同意します。プロジェクトに新しいライブラリを追加できるようになったら、これを使用します。

そのような一般的な用途が Java API にないのは残念です。

于 2009-09-09T16:27:54.367 に答える
5

私がレビューしたすべての既存のソリューション (ライブラリ) は、以下の問題の 1 つまたは複数に苦しんでいることがわかりました。

  • Javadoc では、何を置き換えるかについて正確に説明されていません。
  • エスケープが多すぎるため、HTML が読みにくくなっています。
  • 戻り値が安全に使用できる場合 (HTML エンティティに安全に使用できるか?、HTML 属性に安全に使用できるか? など)文書化されません。
  • それらは速度のために最適化されていません。
  • 二重エスケープを回避する機能はありません (すでにエスケープされているものをエスケープしないでください)。
  • &apos; 一重引用符を(間違った!)に置き換えます。

これに加えて、少なくともある程度のお役所仕事がなければ、外部ライブラリを持ち込めないという問題もありました。

だから、私は自分自身を巻きました。有罪。

以下はそれがどのように見えるかですが、最新バージョンは常にこの要点にあります。

/**
 * HTML string utilities
 */
public class SafeHtml {

    /**
     * Escapes a string for use in an HTML entity or HTML attribute.
     * 
     * <p>
     * The returned value is always suitable for an HTML <i>entity</i> but only
     * suitable for an HTML <i>attribute</i> if the attribute value is inside
     * double quotes. In other words the method is not safe for use with HTML
     * attributes unless you put the value in double quotes like this:
     * <pre>
     *    &lt;div title="value-from-this-method" &gt; ....
     * </pre>
     * Putting attribute values in double quotes is always a good idea anyway.
     * 
     * <p>The following characters will be escaped:
     * <ul>
     *   <li>{@code &} (ampersand) -- replaced with {@code &amp;}</li>
     *   <li>{@code <} (less than) -- replaced with {@code &lt;}</li>
     *   <li>{@code >} (greater than) -- replaced with {@code &gt;}</li>
     *   <li>{@code "} (double quote) -- replaced with {@code &quot;}</li>
     *   <li>{@code '} (single quote) -- replaced with {@code &#39;}</li>
     *   <li>{@code /} (forward slash) -- replaced with {@code &#47;}</li>
     * </ul>
     * It is not necessary to escape more than this as long as the HTML page
     * <a href="https://en.wikipedia.org/wiki/Character_encodings_in_HTML">uses
     * a Unicode encoding</a>. (Most web pages uses UTF-8 which is also the HTML5
     * recommendation.). Escaping more than this makes the HTML much less readable.
     * 
     * @param s the string to make HTML safe
     * @param avoidDoubleEscape avoid double escaping, which means for example not 
     *     escaping {@code &lt;} one more time. Any sequence {@code &....;}, as explained in
     *     {@link #isHtmlCharEntityRef(java.lang.String, int) isHtmlCharEntityRef()}, will not be escaped.
     * 
     * @return a HTML safe string 
     */
    public static String htmlEscape(String s, boolean avoidDoubleEscape) {
        if (s == null || s.length() == 0) {
            return s;
        }
        StringBuilder sb = new StringBuilder(s.length()+16);
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '&':
                    // Avoid double escaping if already escaped
                    if (avoidDoubleEscape && (isHtmlCharEntityRef(s, i))) {
                        sb.append('&');
                    } else {
                        sb.append("&amp;");
                    }
                    break;
                case '<':
                    sb.append("&lt;");
                    break;
                case '>':
                    sb.append("&gt;");
                    break;
                case '"':
                    sb.append("&quot;"); 
                    break;
                case '\'':
                    sb.append("&#39;"); 
                    break;
                case '/':
                    sb.append("&#47;"); 
                    break;
                default:
                    sb.append(c);
            }
        }
        return sb.toString();
  }

  /**
   * Checks if the value at {@code index} is a HTML entity reference. This
   * means any of :
   * <ul>
   *   <li>{@code &amp;} or {@code &lt;} or {@code &gt;} or {@code &quot;} </li>
   *   <li>A value of the form {@code &#dddd;} where {@code dddd} is a decimal value</li>
   *   <li>A value of the form {@code &#xhhhh;} where {@code hhhh} is a hexadecimal value</li>
   * </ul>
   * @param str the string to test for HTML entity reference.
   * @param index position of the {@code '&'} in {@code str}
   * @return 
   */
  public static boolean isHtmlCharEntityRef(String str, int index)  {
      if (str.charAt(index) != '&') {
          return false;
      }
      int indexOfSemicolon = str.indexOf(';', index + 1);
      if (indexOfSemicolon == -1) { // is there a semicolon sometime later ?
          return false;
      }
      if (!(indexOfSemicolon > (index + 2))) {   // is the string actually long enough
          return false;
      }
      if (followingCharsAre(str, index, "amp;")
              || followingCharsAre(str, index, "lt;")
              || followingCharsAre(str, index, "gt;")
              || followingCharsAre(str, index, "quot;")) {
          return true;
      }
      if (str.charAt(index+1) == '#') {
          if (str.charAt(index+2) == 'x' || str.charAt(index+2) == 'X') {
              // It's presumably a hex value
              if (str.charAt(index+3) == ';') {
                  return false;
              }
              for (int i = index+3; i < indexOfSemicolon; i++) {
                  char c = str.charAt(i);
                  if (c >= 48 && c <=57) {  // 0 -- 9
                      continue;
                  }
                  if (c >= 65 && c <=70) {   // A -- F
                      continue;
                  }
                  if (c >= 97 && c <=102) {   // a -- f
                      continue;
                  }
                  return false;  
              }
              return true;   // yes, the value is a hex string
          } else {
              // It's presumably a decimal value
              for (int i = index+2; i < indexOfSemicolon; i++) {
                  char c = str.charAt(i);
                  if (c >= 48 && c <=57) {  // 0 -- 9
                      continue;
                  }
                  return false;
              }
              return true; // yes, the value is decimal
          }
      }
      return false;
  } 


  /**
   * Tests if the chars following position <code>startIndex</code> in string
   * <code>str</code> are that of <code>nextChars</code>.
   * 
   * <p>Optimized for speed. Otherwise this method would be exactly equal to
   * {@code (str.indexOf(nextChars, startIndex+1) == (startIndex+1))}.
   *
   * @param str
   * @param startIndex
   * @param nextChars
   * @return 
   */  
  private static boolean followingCharsAre(String str, int startIndex, String nextChars)  {
      if ((startIndex + nextChars.length()) < str.length()) {
          for(int i = 0; i < nextChars.length(); i++) {
              if ( nextChars.charAt(i) != str.charAt(startIndex+i+1)) {
                  return false;
              }
          }
          return true;
      } else {
          return false;
      }
  }
}

TODO: 連続する空白を保持します。

于 2016-05-22T20:08:14.510 に答える