Escape and unescape string : HTML Output « Servlets « Java

Home
Java
1.2D Graphics GUI
2.3D
3.Advanced Graphics
4.Ant
5.Apache Common
6.Chart
7.Class
8.Collections Data Structure
9.Data Type
10.Database SQL JDBC
11.Design Pattern
12.Development Class
13.EJB3
14.Email
15.Event
16.File Input Output
17.Game
18.Generics
19.GWT
20.Hibernate
21.I18N
22.J2EE
23.J2ME
24.JavaFX
25.JDK 6
26.JDK 7
27.JNDI LDAP
28.JPA
29.JSP
30.JSTL
31.Language Basics
32.Network Protocol
33.PDF RTF
34.Reflection
35.Regular Expressions
36.Scripting
37.Security
38.Servlets
39.Spring
40.Swing Components
41.Swing JFC
42.SWT JFace Eclipse
43.Threads
44.Tiny Application
45.Velocity
46.Web Services SOA
47.XML
Java » Servlets » HTML Output 




Escape and unescape string
     
import java.awt.FontMetrics;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;

/**
 * Globally available utility classes, mostly for string manipulation.
 
 @author Jim Menard, <a href="mailto:[email protected]">[email protected]</a>
 */
public class StringUtils {
  /**
   * Returns a string with HTML special characters replaced by their entity
   * equivalents.
   
   @param str
   *          the string to escape
   @return a new string without HTML special characters
   */
  public static String escapeHTML(String str) {
    if (str == null || str.length() == 0)
      return "";

    StringBuffer buf = new StringBuffer();
    int len = str.length();
    for (int i = 0; i < len; ++i) {
      char c = str.charAt(i);
      switch (c) {
      case '&':
        buf.append("&amp;");
        break;
      case '<':
        buf.append("&lt;");
        break;
      case '>':
        buf.append("&gt;");
        break;
      case '"':
        buf.append("&quot;");
        break;
      case '\'':
        buf.append("&apos;");
        break;
      default:
        buf.append(c);
        break;
      }
    }
    return buf.toString();
  }

  /**
   * Returns a new string where all newlines (&quot;\n&quot;, &quot;\r&quot;, or
   * &quot;\r\n&quot;) have been replaced by &quot;\n&quot; plus XHTML break
   * tags (&quot;\n&lt;br /&gt;&quot;).
   * <p>
   * We don't call <code>splitIntoLines</code> because that method does not
   * tell us if the string ended with a newline or not.
   
   @param str
   *          any string
   @return a new string with all newlines replaced by &quot;\n&lt;br
   *         /&gt;&quot;
   */
  public static String newlinesToXHTMLBreaks(String str) {
    if (str == null || str.length() == 0)
      return "";

    StringBuffer buf = new StringBuffer();
    int len = str.length();
    for (int i = 0; i < len; ++i) {
      char c = str.charAt(i);
      switch (c) {
      case '\n':
        buf.append("\n<br />");
        break;
      case '\r':
        if (i + < len && str.charAt(i + 1== '\n'// Look for '\n'
          ++i;
        buf.append("\n<br />");
        break;
      default:
        buf.append(c);
        break;
      }
    }
    return buf.toString();
  }

  /**
   * Returns a string with XML special characters replaced by their entity
   * equivalents.
   
   @param str
   *          the string to escape
   @return a new string without XML special characters
   */
  public static String escapeXML(String str) {
    return escapeHTML(str);
  }

  /**
   * Returns a string with XML entities replaced by their normal characters.
   
   @param str
   *          the string to un-escape
   @return a new normal string
   */
  public static String unescapeXML(String str) {
    if (str == null || str.length() == 0)
      return "";

    StringBuffer buf = new StringBuffer();
    int len = str.length();
    for (int i = 0; i < len; ++i) {
      char c = str.charAt(i);
      if (c == '&') {
        int pos = str.indexOf(";", i);
        if (pos == -1) { // Really evil
          buf.append('&');
        else if (str.charAt(i + 1== '#') {
          int val = Integer.parseInt(str.substring(i + 2, pos)16);
          buf.append((charval);
          i = pos;
        else {
          String substr = str.substring(i, pos + 1);
          if (substr.equals("&amp;"))
            buf.append('&');
          else if (substr.equals("&lt;"))
            buf.append('<');
          else if (substr.equals("&gt;"))
            buf.append('>');
          else if (substr.equals("&quot;"))
            buf.append('"');
          else if (substr.equals("&apos;"))
            buf.append('\'');
          else
            // ????
            buf.append(substr);
          i = pos;
        }
      else {
        buf.append(c);
      }
    }
    return buf.toString();
  }

  /**
   * Returns <var>str</var> with leading and trailing spaces trimmed or, if
   * <var>str</var> is <code>null</code>, returns <code>null</code>.
   
   @return str trimmed or <code>null</code>
   */
  public static String nullOrTrimmed(String str) {
    return str == null ? str : str.trim();
  }

}

   
    
    
    
    
  














Related examples in the same category
1.Servlet Output HTML Demo
2.Servlet Display Static HTML
3.Prints a conversion table of miles per gallon to kilometers per liter
4.Servlet: Print Table
5.Html utilities
6.Html Parse Servlet
7.Escapes newlines, tabs, backslashes, and quotes in the specified string
8.Web Calendar
9.HTML Helper
10.Escape HTML
11.Convert HTML to text
12.Text To HTML
13.Unescape HTML
14.Java object representations of the HTML table structure
15.Entity Decoder
16.Format a color to HTML RGB color format (e.g. #FF0000 for Color.red)
17.Definitions of HTML character entities and conversions between unicode characters and HTML character entities
18.Encode special characters and do formatting for HTML output
19.HTML color names
20.Utility methods for dealing with HTML
21.Filter the specified message string for characters that are sensitive in HTML
22.A collection of all character entites defined in the HTML4 standard.
23.Decode an HTML color string like '#F567BA;' into a Color
24.Normalize Post Data
25.Get HTML Color String from Java Color object
26.HTML Decoder
27.HTML Parser
28.HTML color and Java Color
29.HTML form Utilites
30.Html Dimensions
31.break Lines with HTML
32.insert HTML block dynamically
33.Convert an integer to an HTML RGB value
34.Convert to HTML string
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.