java - Error handling by redirection in spring download file controller -
this question nicely explains on how write download file controllers in spring. this question nicely explains post request cannot sent using response.sendredirect()
i user redirected same page error caused file download error. here workflow
- user hits www.abc.com/index [controller has mapping /index.jsp , return modelandview]
- at page, have file download has url www.abc.com/download?resource_id=123. [controller has mapping /download , returns void]
- when there error in file download, user should redirected www.abc.com/index error display.
- when there no error in file download, user stays @ same page , file download dialog appears.
following snippet forwarding:
@requestmapping(/download) public void execute(@requestparam(value = "resource_id" required = true) final string resource, final httpservletrequest request, final httpservletresponse response) { try { //some processing } catch { requestdispatcher dispatcher = request.getrequestdispatcher("/index" + "?is_downloaded=false"); dispatcher.forward(request, response) } } @requestmapping(/index) public void execute(@requestparam(value = "is_downloaded" required = false) final string isdownloaded, final httpservletrequest request) { //do stuff here }
step 3 problem.
- using forwarding changes url download url of report on error.
- using redirect response.sendredirect() hidden parameters impossible not modify url @ all.
- using redirect response.sendredirect() hidden parameters , introduce "?is_downloaded=false" @ end of url
can tell workaround this.
i've been having similar issue , solved below code.
i have following exception handler in controller. if there error takes care of re-direct , error messaging.
@exceptionhandler(filenotfoundexception.class) public modelandview exceptionhandler(exception ex) { modelandview modelandview = new modelandview(); modelandview.setviewname("rescues/general"); modelandview.addobject("message", ex.getmessage()); return modelandview; }
here requestmapping
@requestmapping(value = "s3download.request", method = requestmethod.get) @responsebody public responseentity<inputstreamresource> download(@requestparam(value = "s3key") string s3key) throws ioexception { httpheaders responseheaders = new httpheaders(); inputstreamresource inputstreamresource = s3downloadservice.gets3file(s3key, responseheaders); return new responseentity<>(inputstreamresource, responseheaders, httpstatus.ok); }
if files locally on server can use filesystemresource in place of inputstreamresource.
the service layer takes care of setting response header values on httpheaders object
responseheaders.setcontenttype(mediatype.parsemediatype(objectmetadata.getcontenttype())); responseheaders.setcontentlength(objectmetadata.getcontentlength()); responseheaders.setcontentdispositionformdata("attachment", filename);
Comments
Post a Comment