Spring MVC:Controller方法中的JSP或JSON视图,具体取决于请求

时间:2010-09-29 14:22:28

标签: java spring spring-mvc

使用@ResponseBody我的控制器默认返回我的pojo的JSON表示,但默认情况下可以将视图更改为JSP,并且仅当您的内容类型为application/json时才返回JSON响应?

@RequestMapping(value="/myRequest")
public @ResponseBody myPojo myRequest() throws Exception  {     
    return service.getMyPojo();
}

PS:我已经尝试ContentNegotiatingViewResolver,但我不确定是否是实现这一目标的最佳方式。

1 个答案:

答案 0 :(得分:2)

您可以有两个映射:

@RequestMapping(value = "/myRequest", headers="content-type=application/json")
public @ResponseBody jsonExample() throws Exception  {     
    return service.getMyPojo();
}

@RequestMapping(value = "/myRequest", headers="content-type=text/*")
public String jspExample() throws Exception  {     
    return "myJspView";
}