Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

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

like image 828
Ralph Avatar asked Jan 10 '12 18:01

Ralph


2 Answers

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
like image 126
Ralph Avatar answered Sep 30 '22 18:09

Ralph


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.

like image 31
AlexR Avatar answered Sep 30 '22 18:09

AlexR