I have a Spring 3.0 application, with an Web Controller Method. This method normaly return a file in the http response, therefore I used the return type org.springframework.http.HttpEntity
. But now there is a second requirement: if the file is larger than 1MB and it is after 10 o'clock, a HTML page should be displayed.
So my problem is, that the method sometimes should be return a HttpEntity<byte[]>
and sometimes a ModelAndView
. But how can one have this two different kinds of a return type?
(Ok the requirement is not 10 o'clock, it is much more complicated, but the point is, that this dessicion can be made only in the controller.)
(This application uses classic JSPX for rendering HTML paged.)
Its too easy (sorry for the question): one could define the method with return type Object
, so one could return instances of ModelAndView
or HttpEntity
.
This works because the AnnotationMethodHandlerAdapter#getModelAndView
takes the return value as an Object
and then has a if-then-else cascade with an lot of inncstanceof
statements to determine the concreate instance type.
If one feels that the return type Object
is too common, then one could define its own class (compound-class), witch contains a ModelAndView
or HttpEntity
in two different fields. And then one have to write a custom ModelAndViewResolver
.
This custom ModelAndViewResolver
take the compound-object and
ModelAndView
orwebRequest
like AnnotationMethodHandlerAdapter#handleHttpEntityResponse
does and then returns nullI think that the better solution here is using regular HTTP filter that checks the conditions and either forwards the request to "normal" flow or to HTML page.
This allows you to decouple your logic. Probably in future you will receive yet another requirement that forwards request to yet another path. You can implement this in yet another filter.
The filters can use the same Spring context and therefore use the same beans, DB etc.
EDIT. Think about Spring interceptor too. I personally have not used this technique but it can help here also.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With