KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > lutris > util > HtmlEncoder


1
2 /*
3  * Enhydra Java Application Server Project
4  *
5  * The contents of this file are subject to the Enhydra Public License
6  * Version 1.1 (the "License"); you may not use this file except in
7  * compliance with the License. You may obtain a copy of the License on
8  * the Enhydra web site ( http://www.enhydra.org/ ).
9  *
10  * Software distributed under the License is distributed on an "AS IS"
11  * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
12  * the License for the specific terms governing rights and limitations
13  * under the License.
14  *
15  * The Initial Developer of the Enhydra Application Server is Lutris
16  * Technologies, Inc. The Enhydra Application Server and portions created
17  * by Lutris Technologies, Inc. are Copyright Lutris Technologies, Inc.
18  * All Rights Reserved.
19  *
20  * Contributor(s):
21  *
22  * $Id: HtmlEncoder.java,v 1.1 2004/04/21 19:31:58 slobodan Exp $
23  */

24
25
26
27
28 package com.lutris.util;
29
30 /**
31  * This class contains a utility method for encoding a
32  * <code>String</code> so that it may be safely embedded within
33  * a HTML document without affecting the formatting of the
34  * document.<p>
35  *
36  * The following characters are encoded:
37  * <p>
38  * <ul>
39  * <li> &lt;
40  * <li> &gt;
41  * <li> &amp;
42  * <li> &#39;
43  * <li> &quot;
44  * <li> &#92;
45  * <li> &#133;
46  * </ul>
47  *
48  * @author Kyle Clark
49  */

50 public final class HtmlEncoder {
51
52     /**
53      * Translates a string into a HTML safe format.
54      *
55      * @param s the string to encode
56      * @return the encoded string
57      */

58     public static String JavaDoc encode(String JavaDoc s) {
59         char [] htmlChars = s.toCharArray();
60         StringBuffer JavaDoc encodedHtml = new StringBuffer JavaDoc();
61         for (int i=0; i<htmlChars.length; i++) {
62             switch(htmlChars[i]) {
63             case '<':
64                 encodedHtml.append("&lt;");
65                 break;
66             case '>':
67                 encodedHtml.append("&gt;");
68                 break;
69             case '&':
70                 encodedHtml.append("&amp;");
71                 break;
72             case '\'':
73                 encodedHtml.append("&#39;");
74                 break;
75             case '"':
76                 encodedHtml.append("&quot;");
77                 break;
78             case '\\':
79                 encodedHtml.append("&#92;");
80                 break;
81             case (char)133:
82                 encodedHtml.append("&#133;");
83                 break;
84             default:
85                 encodedHtml.append(htmlChars[i]);
86                 break;
87             }
88         }
89         return encodedHtml.toString();
90     }
91 }
92
Popular Tags