Posts Tagged ‘content type’

ZTemplates 0.9.9.6 and custom content types

Wednesday, September 30th, 2009

Quite recently I have been in a situation where I wanted to expose some XML using ZTemplates. So I used the servlet serivce to get the HttpServletResponse instance:

final HttpServletResponse response = ZTemplates.getServletService().getResponse();
response.setCharacterEncoding("utf-8");
response.setContentType("application/xml");

Followed by rendering a view:

ZTemplates.getServletService().render(view);

When I inspected the HTTP traffic using wireshark I noticed that I saw:

Content-Type: text/html;charset=utf-8

Rather than the expected application/xml. So I started looking into the code of the ZServletService that is responsible for rendering:

public void render(Object obj) throws Exception {
    render(obj, "text/html");
}
 
public void render(Object obj, String mimeType) throws Exception {
    String html = renderService.render(obj);
    // response.setCharacterEncoding(UTF8);
    response.setContentType(mimeType);
    response.getWriter().print(html);
}

That explained a lot, so now you could go ahead and do:

ZTemplates.getServletService().render(view, "application/xml");

However that does not give you control on the encoding, so I decided to create a custom rendering method instead:

public static void render(Object view, String encoding, String contentType ) throws Exception {
    final HttpServletResponse response = ZTemplates.getServletService().getResponse();
    final String renderResponse = ZTemplates.getRenderService().render(view);
    response.setCharacterEncoding(encoding);
    response.setContentType(contentType);
    response.getWriter().print(renderResponse);
}

So to fix my problem I only have to do the following now:

ZRenderUtils.render(view, "utf-8", "application/xml");

p.s. If you are wondering in this example, view, is just a String containing XML.