Displaying UTF-8 Characters in resource response

The portlet specification says that when resource request is made the portal only acts as proxy and as a result you have more control on the HTTP request, response, you can set additional headers do things that you cannot in the render method, this issue also has some disadvantages, For example if you want to return UTF-8 characters in the doView() method you dont have to do any thing special but if you want to return same UTF-8 characters through serveResource method then you will have to call PortletResponse.setCharacterEncoding("UTF-8")

I do have this sample portlet which displays some Chinese characters in both doView() and serveResource() method the characters are displayed right in the view mode markup but it displays funny characters while displaying response of the resource URL



When i looked at the HTTP headers of response, it seems that when portal returns response it automatically sets character encoding to UTF-8 irrespective of if your setting UTF-8 characters or not but when you return markup from serveResource , character encoding is not set by portal, so i had to change my code and set the character encoding manually and now it works

public class ServeResourceUTF8Portlet extends GenericPortlet{
protected void doView(RenderRequest request, RenderResponse response)
throws PortletException, IOException {
response.setContentType("text/html");
response.getWriter().println("样本字符");
response.getWriter().println("
");
getPortletContext().getRequestDispatcher("/view.jsp").include(request, response);
}
public void serveResource(ResourceRequest request, ResourceResponse response)
throws PortletException, IOException {
response.setContentType("text/html");
response.setCharacterEncoding("UTF-8");
response.getWriter().println("样本字符");
}
}


This is how the response looks like after setting character encoding manually, as you can see it adds the information to contentType header

2 comments:

Abhi said...

Thanks for info....
SEO Company in Bangalore

IDesignPassion said...

Thank you for sharing article with us. It is reaaly awesome. Keep posting such information.
Custom website design Phoenix