我在 servlet 中使用以下代码:
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
response.setContentType("text/html");
out.println("<html>");
out.println("<body>");
out.println("<script>alert(1)</script>");
out.println("</body>");
out.println("</html>");
}
过滤器的以下代码:
public class SampleFilter implements Filter {
protected FilterConfig config;
public void init(FilterConfig config) throws ServletException {
this.config = config;
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws ServletException, IOException {
long startTime = System.currentTimeMillis();
ServletResponse newResponse = response;
if (request instanceof HttpServletRequest) {
System.out.println("in filter if1");
newResponse = new CharResponseWrapper((HttpServletResponse) response);
}
System.out.println("after filter if1");
chain.doFilter(request, newResponse);
long elapsed = System.currentTimeMillis() - startTime;
if (newResponse instanceof CharResponseWrapper) {
System.out.println("in filter if2");
String text = newResponse.toString();
if (text != null) {
text = SampleFilter.HTMLEntityEncode(text);//.toUpperCase();
response.getWriter().write(text);
}
}
System.out.println("after filter if2");
config.getServletContext().log(" took " + elapsed + " ms");
System.out.println(elapsed);
}
private static String HTMLEntityEncode(String input) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < input.length(); i++) {
char ch = input.charAt(i);
if (Character.isLetterOrDigit(ch) || Character.isWhitespace(ch)) {
sb.append(ch);
} else {
sb.append("&#" + (int)ch + ";");
}
}
return sb.toString();
}
}
我想在浏览器中获取以下显示数据:
<script>alert(1)</script>
而是我得到
<html>
<body>
<script>alert(1)</script>
</body>
</html>
在浏览器中。
任何帮助都会很棒。