HTTP servlet response wrapper

A wrapper for the response is very useful to implement the new features of the response. In our example, we write an implementation that prints the response as a string. To do it, we can implement the javax.servlet.http.HttpServletResponse interface, as follows:

public class ResponseCharacterWrapper extends HttpServletResponseWrapper {
private CharArrayWriter output;
public String toString() {
return output.toString();
}
public ResponseCharacterWrapper(HttpServletResponse response) {
super(response);
output = new CharArrayWriter();
}
public PrintWriter getWriter() {
return new PrintWriter(output);
}
}

Now, add a servlet mapped with a /filtered/ path:

@WebServlet(urlPatterns = { "/CharacterServlet", "/filtered/CharacterServlet" })
public class CharacterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.print("bar");
}
}
}

Without filters, if we do a GET HTTP call through the http://localhost:8080/servlets-jsp/filtered/CharacterServlet URL, we should obtain a page with a row bar. As the filter intercepts all the /filtered/ paths, we will obtain a page as illustrated:


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.222.125.171