Prentice Hall and Sun Microsystems. Personal use only; do not redistribute.
3.6 Filtering Strings for HTML Specific Characters
89
Listing 3.8 ServletUtilities.java (continued)
} else if (c == " ) {
filtered.append(""");
} else if (c == & ) {
filtered.append("&");
} else {
filtered.append(c);
}
}
return(filtered.toString());
}
}
Example
By means of illustration, consider a servlet that attempts to generate a Web
page containing the following code listing:
if (a
doThis();
} else {
doThat();
}
If the code was inserted into the Web page verbatim, the
would be
interpreted as the beginning of an HTML tag, and all of the code up to the
next
>
would likely be interpreted as malformed pieces of that tag. For exam
ple, Listing 3.9 shows a servlet that outputs this code fragment, and Figure
3 9 shows the poor result. Listing 3.10 presents a servlet that changes noth
ing except for filtering the string containing the code fragment, and, as Fig
ure 3 10 illustrates, the result is fine.
Listing 3.9 BadCodeServlet.java
package coreservlets;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
/** Servlet that displays a fragment of some Java code,
* but forgets to filter out the HTML specific characters
* (the less than sign in this case).
*/
public class BadCodeServlet extends HttpServlet {
private String codeFragment =
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