Java HTML Encode htmlEncode(String html)

Here you can find the source of htmlEncode(String html)

Description

Convert certain characters (&, <, >, and ') to their HTML character equivalents for literal display in web pages.

License

Open Source License

Parameter

Parameter Description
html a parameter

Declaration

public static String htmlEncode(String html) 

Method Source Code

//package com.java2s;
/* GWTUtil.java//from   ww  w . j a v  a2 s.  com
    
   Copyright (c) 2009 Juergen Schlierf, All Rights Reserved
       
   This file is part of Cubusmail (http://code.google.com/p/cubusmail/).
       
   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 3 of the License, or (at your option) any later version.
       
   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.
       
   You should have received a copy of the GNU Lesser General Public
   License along with Cubusmail. If not, see <http://www.gnu.org/licenses/>.
       
 */

public class Main {
    public static final String HTML_AMPERSAND = "&amp;";
    public static final String HTML_LESS_THAN = "&lt;";
    public static final String HTML_GREATER_THAN = "&gt;";
    public static final String HTML_DASH_POINT = "&acute;";

    /**
     * Convert certain characters (&, <, >, and ') to their HTML character
     * equivalents for literal display in web pages.
     * 
     * @param html
     * @return
     */
    public static String htmlEncode(String html) {

        if (hasText(html)) {
            String result = html.replace("&", HTML_AMPERSAND);
            result = result.replace("<", HTML_GREATER_THAN);
            result = result.replace(">", HTML_LESS_THAN);
            result = result.replace("'", HTML_DASH_POINT);
            return result;
        }

        return null;
    }

    /**
     * @param text
     * @return
     */
    public static boolean hasText(String text) {

        if (text != null) {
            if (text.trim().length() > 0) {
                return true;
            }
        }

        return false;
    }
}

Related

  1. html_encode(String input_string)
  2. HTMLBREncode(String str)
  3. htmlEncode(final String source, StringBuffer target)
  4. htmlEncode(Object input)
  5. htmlEncode(String html)
  6. htmlEncode(String input)
  7. htmlEncode(String input)
  8. htmlEncode(String s)
  9. htmlEncode(String s)