View Javadoc

1   /*
2   * Licensed to the Apache Software Foundation (ASF) under one or more
3   * contributor license agreements.  See the NOTICE file distributed with
4   * this work for additional information regarding copyright ownership.
5   * The ASF licenses this file to You under the Apache License, Version 2.0
6   * (the "License"); you may not use this file except in compliance with
7   * the License.  You may obtain a copy of the License at
8   *
9   *     http://www.apache.org/licenses/LICENSE-2.0
10  *
11  * Unless required by applicable law or agreed to in writing, software
12  * distributed under the License is distributed on an "AS IS" BASIS,
13  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */
17  
18  package util;
19  
20  /**
21   * HTML filter utility.
22   *
23   * @author Craig R. McClanahan
24   * @author Tim Tye
25   * @version $Revision: 664175 $ $Date: 2008-06-06 18:43:44 -0400 (Fri, 06 Jun 2008) $
26   */
27  
28  public final class HTMLFilter {
29  
30  
31      /**
32       * Filter the specified message string for characters that are sensitive
33       * in HTML.  This avoids potential attacks caused by including JavaScript
34       * codes in the request URL that is often reported in error messages.
35       *
36       * @param message The message string to be filtered
37       */
38      public static String filter(String message) {
39  
40          if (message == null)
41              return (null);
42  
43          char content[] = new char[message.length()];
44          message.getChars(0, message.length(), content, 0);
45          StringBuffer result = new StringBuffer(content.length + 50);
46          for (int i = 0; i < content.length; i++) {
47              switch (content[i]) {
48                  case '<':
49                      result.append("&lt;");
50                      break;
51                  case '>':
52                      result.append("&gt;");
53                      break;
54                  case '&':
55                      result.append("&amp;");
56                      break;
57                  case '"':
58                      result.append("&quot;");
59                      break;
60                  default:
61                      result.append(content[i]);
62              }
63          }
64          return (result.toString());
65  
66      }
67  
68  
69  }
70