Search code examples
liferayportlet

Liferay Portlet Response: how to set status code?


I have a simple method accepting PortletResponse and PortletRequest in my liferay portlet

public void remove(PortletResponse response, PortletRequest request) {

}

I want to set response status to 404, like I can do with HttpServletResponse by httpResponse.sendError(HttpServletResponse.SC_BAD_REQUEST)

Can you tell me how I can do it?


Solution

  • What does Portlet Specification 2.0 have to say - you can set the response status only when handling resource request:

    If the portlet want to set a response status code it should do this via setProperty with the key ResourceResponse.HTTP_STATUS_CODE.

    That means, you can set the response status code this way when serving resources:

    resourceResponse.setProperty(ResourceResponse.HTTP_STATUS_CODE, 
                                 Integer.toString(HttpServletResponse.SC_BAD_REQUEST));
    

    With Liferay, you can get instance of the underlying HttpServletResponse and set status code there. The portal will return it to the client. This way, you can set the response status for any portal request, not only resource request.

    HttpServletResponse httpServletResponse = PortalUtil.getHttpServletResponse(portletResponse);
    httpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
    

    However, such practice is strongly discouraged as well explained in Olaf Kock's answer. See it to get the bigger picture.