August 15, 2017

Gzip compression working Spring MVC

GZIP compression

public static String gzipCompression(String strNew) throws IOException {
    if (strNew == null || strNew.length() == 0) {
        return str;
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    GZIPOutputStream gzip = new GZIPOutputStream(out);
    String outStr = out.toString("UTF-8");
    return outStr;

Using BufferedWriter

public static String compressString(String str) throws IOException{
if (str == null || str.length() == 0) {
    return str;

BufferedWriter writer = null;

    File file =  new File("your.gzip")
    GZIPOutputStream zip = new GZIPOutputStream(new FileOutputStream(file));

    writer = new BufferedWriter(new OutputStreamWriter(zip, "UTF-8"));

    if(writer != null){

Using compression filter

package : com.planetj.servlet.filter.compression
spring compression filter

How to enable HTTP response compression

Read 69.18

GZip compression in spring

Handling filters in spring MVC

Working with @controllerAdvice and ResponseAdvice in spring 4


Interceptors are use to manipulate entities like inputstream and outputstreams. There are two kinds of interceptors ReaderInterceptor and WriterInterceptors

public class GzipWriterInterceptor implements writerinterceptors {
public void aroundwriteto(writerinterceptorcontext context){
outputstream os = context.getoutputstream();
context.setoutputstream(new Gzipoutputsream(os));

Using ResponseWrapper

public void doFilter(ServletRequest request, ServletResponse response,
                     FilterChain chain) throws IOException, ServletException {

    ResponseWrapper responseWrapper = new ResponseWrapper((HttpServletResponse) response);

    chain.doFilter(request, responseWrapper);

    String responseContent = new String(responseWrapper.getDataStream());

    RestResponse fullResponse = new RestResponse(/*status*/, /*message*/,responseContent);

    byte[] responseToSend = restResponseBytes(fullResponse);



using response body advice

@controllerAdvice +  implements ResponseBodyAdvice<Object>

public class HeaderModifierAdvice implements ResponseBodyAdvice<Object> {

    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;

    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        return body;

Rest Easy spring integration

Facebook comments