简体   繁体   中英

How to alternate the web controller response between HttpEntity and ModelAndView in Spring

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

  • return a model and view if it is the compound-class for ModelAndView or
  • updates the webRequest like AnnotationMethodHandlerAdapter#handleHttpEntityResponse does and then returns null

I 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM