Saturday 23 August 2014

HttpServletResponseWrapper

This class provides implementation of the HttpServletResponse interface that can be subclassed by developers wishing to adapt the response from a Servlet. Will try to send the response in Upper case using HttpServletResponseWrapper class.

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

public class CharResponseWrapper extends HttpServletResponseWrapper {
    private final CharArrayWriter output;

    @Override
    public String toString() {
        return output.toString().toUpperCase();
    }

    public CharResponseWrapper(HttpServletResponse response) {
        super(response);
        output = new CharArrayWriter();
    }

    @Override
    public PrintWriter getWriter() {
        return new PrintWriter(output);
    }
}

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;

@WebFilter(filterName = "FilterSample", urlPatterns = {"/HttpServletRespWrappEx"})
public class FilterSample implements Filter {
    
    @Override
    public void init(FilterConfig filterConfig) throws ServletException{
        
    }
    
    @Override
    public void destroy(){
        
    }
    
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException {
        PrintWriter out = response.getWriter();
        CharResponseWrapper responseWrapper = new CharResponseWrapper((HttpServletResponse) response);

        chain.doFilter(request, responseWrapper);

        String servletResponse = responseWrapper.toString();

        out.write("Response in Uppercase\n"); 
        out.write(servletResponse);
    }
}

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns = {"/HttpServletRespWrappEx"})
public class HttpServletRespWrappEx extends HttpServlet {
    @Override
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
        response.getWriter().println("hi, how are you");
    }
}

Run the Above servlet like below
'http://localhost:8080/servlet/HttpServletRespWrappEx'

Output




Prevoius                                                 Next                                                 Home

No comments:

Post a Comment