automatically choose viewResolver based on request

2019-08-11 09:34发布

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.

So, my question is, how do I configure Spring, and how do I write the controller?

Thx

1条回答
劳资没心,怎么记你
2楼-- · 2019-08-11 09:49

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;
}

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.

查看更多
登录 后发表回答