MinifyFilter

package com.ofrick.filters;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.regex.*;

public class MinifyFilter implements Filter {

private Pattern regex = null;
 
 // This method is called once on server startup
 public void init(FilterConfig filterConfig) 
 {
 regex = Pattern.compile("^\\s*$\\n|\\t", Pattern.MULTILINE);
 }
 
 // This method is called for every request and needs to be thread safe.
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 
 throws java.io.IOException, javax.servlet.ServletException 
 {
 HttpServletResponse resp = (HttpServletResponse) response;
 ResponseWrapper wrapper = new ResponseWrapper(resp);
 chain.doFilter(request, wrapper);
 
 String html = wrapper.toString();

html = regex.matcher(html).replaceAll("");
 //html = multipleSpaces.matcher(html).replaceAll(" ");
 resp.setContentLength(html.getBytes().length);
 PrintWriter out = resp.getWriter();
 out.write(html);
 out.flush();
 out.close();
 }
 
 // This method is called once on server shut down
 public void destroy() 
 {
 //
 }
 
 static class ResponseWrapper extends HttpServletResponseWrapper {
 private CharArrayWriter output;

public ResponseWrapper(HttpServletResponse response) {
 super(response);
 this.output = new CharArrayWriter();
 }

public String toString() {
 return output.toString();
 }

public PrintWriter getWriter() {
 return new PrintWriter(output);
 }
 }
 
}
Dieser Eintrag wurde veröffentlicht in Allgemein von admin. Setze ein Lesezeichen zum Permalink.