Sunday, March 16, 2014

Changes required in serveResource to serve special characters

It seems that returning UTF-8 characters from characters from serveResource method requires some additional steps.

I created this sample portlet which returns some Chinese characters from both 
doView() and serveResource() method. The content returned from doView() is ok, but the content returned by serveResource() returns garbage character

public void doView(RenderRequest request, RenderResponse response) 
throws PortletException, IOException {
  // Set the MIME type for the render response
  response.setContentType("text/html; charset=UTF-8");
  response.getWriter().println("
这是世界您好");
}

public void serveResource(ResourceRequest request,
  ResourceResponse response)
  throws PortletException, IOException {
    response.setContentType("text/html; charset=UTF-8");
    response.getWriter().println("
这是世界您好");
}

It seems that in order to return valid response from 
serveResource method we have to add some additional properties on the response

public void serveResource(ResourceRequest request, ResourceResponse response)
  throws PortletException, IOException {
  response.setContentType("text/html; charset=UTF-8");
  response.setCharacterEncoding("UTF-8");
  response.setProperty("Content-Type","text/html; charset=UTF-8");
  response.getWriter().println("
这是世界您好");
}

No comments:

Post a Comment