I am wanting to return a view from a Spring MVC Controller depending on logic. If an error occurs I want to return JSON, if not, an HTML view. This is like ASP.NET MVC ActionResult, where you can return any kind of view and it will render the result, and it won't depend on the content-type being sent in the request. I can't find any examples of this.
相关问题
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- java.lang.IllegalArgumentException: Cannot set to
- Spring Data MongoDB - lazy access to some fields
相关文章
- java JDK动态代理和cglib动态代理最后获取的代理对象都为null的问题
- org.xml.sax.SAXParseException; lineNumber: 7; colu
- spring-mvc a标签带参怎样向controller发送请求。路径格式?
- SpringMVC如何把File封装到Map中?
- json_encode 没有把数组转为json
- Livy Server: return a dataframe as JSON?
- Spring: controller inheritance using @Controller a
- How to load @Configuration classes from separate J
Program your controller to return a different logical view name depending on a condition. For example:
Configure the view resolvers to resolve the view name
"error"
to the JSON view. Spring provides many ways to configure the view name to view mapping, including:For example, to use BeanNameViewResolver:
Perhaps you can look at ResolveBundleViewResolver, which allows you to mix views. The docs give some info on how to use this.
From the docs (example is to mix tiles and jstl, but should apply for others as well)...
context file
views.properties
To extend Chin Huang's answer, here is what works for me. No configuration required.
This will automatically convert the model into JSON and write to response. Here model is of type
Map<String,Object>
and response is of typeHttpServletResponse
There's nothing to prevent you from returning an actual
View
object directly from your controller method - it doesn't have to be a view name. So your controller can construct aView
object using its own logic, and return that, with or without being wrapped in aModelAndView
object.This is probably simpler than trying to persuade the
ViewResolver
framework from doing this for you, although that would work as well.I achieved this with the following.
JsonView.java
JS Function that makes the call
Just in case and you want to return Json on exception you can do the following:
I'm not sure that this is what you wanted to do, but just in case.... :)