支持Spring-MVC控制器中的多种内容类型

Rails控制器使得支持多种内容类型变得非常容易。

respond_to do |format| format.js { render :json => @obj } format.xml format.html end 

美丽。 在一个控制器动作中,我可以轻松地响应多种内容类型,并且具有足够的灵活性,可以呈现我想呈现的内容,无论是模板,我的对象的序列化forms等。

我可以在Spring-MVC中做类似的事情吗? 在Spring中支持多种内容类型的标准是什么? 我见过涉及视图解析器的解决方案,但这看起来很难管理,特别是如果我想支持除xhtml和xml之外的JSON。

任何建议都表示赞赏,但更简单,更优雅的解决方案将更受欢迎;)

编辑

如果我断言查看解析器难以管理,请随时纠正我并提供示例。 最好是可以返回xml,xhtml和JSON的。

在Spring 3中,您希望使用org.springframework.web.servlet.view.ContentNegotiatingViewResolver

它需要一个媒体类型列表和ViewResolvers 。 来自Spring文档 :

                        

控制者:

 import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.web.bind.annotation.RequestMapping; @Controller public class BlogsController { @RequestMapping("/blogs") public String index(ModelMap model) { model.addAttribute("blog", new Blog("foobar")); return "blogs/index"; } } 

您还需要包含Jackson JSONjar子。

这里是工作示例控制器,它根据请求标题“Content-Type”呈现JSON和HTML。

 import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.util.MimeTypeUtils; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; @RestController public class PersonService { @RequestMapping(value = "/persons/{userId}", method = RequestMethod.GET) public ResponseEntity getPersonByName(@RequestHeader("Content-Type") String contentMediaType, @PathVariable("userId") String userId,@RequestParam("anyParam") boolean isAscending) throws IOException { Person person = getPersonById(userId); if (isJSON(contentMediaType)) { return new ResponseEntity(person, HttpStatus.OK); } return new ResponseEntity("Your HTML Goes Here", HttpStatus.OK); //Note: Above you could use any HTML builder framework, like HandleBar/Moustache/JSP/Plain HTML Template etc. } private static final boolean isJSON(String contentMediaType) { if ("application/json".equalsIgnoreCase(contentMediaType)) { return true; } return false; } }