根据请求网址自动选择viewResolver? [英] automatically choose viewResolver based on request url?
问题描述
我希望能够做的是编写一个返回对象的方法,将方法映射到请求,并根据url更改对象的格式。因此,如果我有一个客户端对象数组被返回 / clients
,我希望默认情况下将对象解析为速度模板(clients.vm) )处理格式。但是,如果url是 /clients.json
,那么我想将对象传回响应主体,并让消息转换器弄清楚如何处理它。
What I'd like to be able to do is write one method that will return an object, map the method to a request, and alter how the object is formatted based on the url. So, if I had an array of Client objects that get returned for /clients
, I'd like to, by default, resolve the object to a velocity template (clients.vm) to handle the formatting. However, if the url is /clients.json
, than I'd like to pass the object back in the response body, and let the message converter figure out how to handle it.
所以,我的问题是,如何配置Spring,以及如何编写控制器?
So, my question is, how do I configure Spring, and how do I write the controller?
Thx
推荐答案
在处理程序方法中使用 PathVariable
,使用它切换要使用的视图:
Use a PathVariable
in your handler method, use that to toggle which view to use:
@RequestMapping("/myapp/{viewtype}/view.do")
public String myHandler(
@PathVariable String viewtype,
Model model) {
// do stuff
return "viewname." + viewtype;
}
查看类型可以是 vm
,或 jsp
,或者其他什么。如果返回类型只是更改为 @ResponseBody
,并且你在类路径上有Jackson JAR,它也可以返回JSON。
View type could be vm
, or jsp
, or whatever. It could also return JSON if the return type is simply changed to @ResponseBody
and you have the Jackson JARs on the classpath.
这篇关于根据请求网址自动选择viewResolver?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!