Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
88
Chapter 3 Handling the Client Request: Form Data
Code for Filtering
Replacing
<
,
>
,
"
, and
&
in strings is a simple matter, and there are a number
of different approaches that would accomplish the task. However, it is impor
tant to remember that Java strings are immutable (i.e., can't be modified), so
string concatenation involves copying and then discarding many string seg
ments. For example, consider the following two lines:
String s1 = "Hello";
String s2 = s1 + " World";
Since
s1
cannot be modified, the second line makes a copy of
s1
and appends
"World"
to the copy, then the copy is discarded. To avoid the expense of gener
ating these temporary objects (garbage), you should use a mutable data structure,
and
StringBuffer
is the natural choice. Listing 3.8 shows a static
filter
method that uses a
StringBuffer
to efficiently copy characters from an input
string to a filtered version, replacing the four special characters along the way.
Listing 3.8 ServletUtilities.java
package coreservlets;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletUtilities {
// Other methods in ServletUtilities shown elsewhere...
/** Given a string, this method replaces all occurrences of
* < with < , all occurrences of > with
* > , and (to handle cases that occur inside attribute
* values), all occurrences of double quotes with
* " and all occurrences of & with & .
* Without such filtering, an arbitrary string
* could not safely be inserted in a Web page.
*/
public static String filter(String input) {
StringBuffer filtered = new StringBuffer(input.length());
char c;
for(int i=0; i
c = input.charAt(i);
if (c == < ) {
filtered.append("<");
} else if (c == > ) {
filtered.append(">");
Second edition of this book: www.coreservlets.com; Sequel: www.moreservlets.com.
Servlet and JSP training courses by book's author: courses.coreservlets.com.
footer
Our partners:
PHP: Hypertext Preprocessor Best Web Hosting
Java Web Hosting
Jsp Web Hosting
Cheapest Web Hosting
Visionwebhosting.net Business web hosting division of Web
Design Plus. All rights reserved