Reputation: 431
Is it possible for a method in Spring Controller to be able to return either a JSON or a view based on some conditions?
Can someone please share examples.
Regards, Farhan
Upvotes: 2
Views: 1382
Reputation: 3838
Here's one solution among others : you can use two methods in your Controller
, one using the @ResponseBody
annotation and returning a JSON value and one classical method returning a ModelAndView
.
Both methods could use the same http endpoint with different parameters (query or header parameters). In my point of view, the cleaner way to route the request to the expected format is using Content-Type
header with the following values : text/html
and application/json
(or a path extension .html
or .json
but I'd prefer the header solution).
To do that you can use the consumes
attribute of the @RequestMapping
annotation : https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/bind/annotation/RequestMapping.html
An even better design would be to separate your methods that return JSON in @RestController
annoted classes with real restfull endpoints and your your classical MVC's methods with non-restfull endpoints (generally bad for the SEO) in @Controller
annoted classes that are only reserved for MVC (and both controller's families can use the same business logic in @Service
annoted classes that not expose http endpoints).
If you really want to use a single method and determine with some conditions the format of your output, I think that would be a really bad design for your http clients but it's still possible using ViewResolvers
like Bart suggests in comments.
Upvotes: 1