java - Spring MVC 3.2 - Content Negotiation for Error Pages? -
to globally handle errors (such http 404's) can occur outside of controller, have entries similar next in web.xml:
<error-page> <error-code>404</error-code> <location>/errors/404</location> </error-page>
in errorcontroller have corresponding methods similar following:
@controller @requestmapping("/errors") public class errorcontroller { @requestmapping(value = "/404", method = requestmethod.get) @responsebody public responseentity<errorresponse> error404() { errorresponse errorbody = new errorresponse(404, "resource not found!"); homecoming new responseentity<errorresponse>(errorbody, httpstatus.not_found); } }
the issue i'm facing contentnegotiationmanager
, message converters have configured not beingness used in case. suspect since request beingness redirected error page, original request's attributes used in content negotiation lost , treated separate request. (i.e. original request /mycontroller/badresource.json --> /errors/404 (w/no file extension))
is there way in error handler determine and/or respond appropriate content type requested in original request?
i came bit of hack seems work. involves forwards in error handling determine file extension of original request.
in web.xml have error forwarded intermediate action:
<error-page> <error-code>404</error-code> <location>/errors/redirect</location> </error-page>
then, before forwarding action generate error response, check done see if there file extension on original request. if there was, ensures appended forwards uri. http headers automatically forwarded, if content negotiation have setup involves file extensions or http header, allow "error page" homecoming error in appropriate content type.
@controller @requestmapping("/errors") public class errorcontroller { @requestmapping(value = "/redirect", method = requestmethod.get) public void errorredirect(httpservletrequest request, httpservletresponse response) { // original request uri string uri = (string)request.getattribute(webutils.error_request_uri_attribute); // seek determine file extension string filename = webutils.extractfullfilenamefromurlpath(uri); string extension = stringutils.getfilenameextension(filename); extension = stringutils.hastext(extension) ? "." + extension : ""; // forwards request appropriate handler original request's file extension (i.e. /errors/404.json) string forwarduri = "/errors/404" + extension); request.getrequestdispatcher(forwarduri).forward(request, response); } @requestmapping(value = "/404", method = requestmethod.get) @responsebody public responseentity<errorresponse> error404() { errorresponse errorbody = new errorresponse(404, "resource not found!"); homecoming new responseentity<errorresponse>(errorbody, httpstatus.not_found); } }
java spring spring-mvc content-negotiation
No comments:
Post a Comment