I am using the following code in 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>");
}
And following code for the filter:
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();
}
}
I want to get the following display data in the browser:
<script>alert(1)</script>
rather i am getting
<html>
<body>
<script>alert(1)</script>
</body>
</html>
in the browser.
Any help will be great.