开发者

Spring MVC - Force a controller to produce MappingJacksonJsonView(s)

Here we have a basic webapp using JSP which needs to provide a few JSON based REST service URLs.

These urls will all reside under /services and be generated by a MyRestServicesController.

The examples I see for settings up JSON based views all use ContentNegotiatingViewResolver. But it seems like overkill to me as this resolver seems meant for situations where the same URL might produce different output.

I just want my one RestServicesController to always produce MappingJacksonJsonView(s)开发者_StackOverflow中文版.

Is there a cleaner, more straight forward way to simply direct the controller to do this?


Is there a cleaner, more straight forward way to simply direct the controller to do this?

Yes there is. You can have a look at this sample I posted in Spring forums. In short the way I prefer to do it is through the following.

ApplicationContext:

<!-- json view, capable of converting any POJO to json format -->
<bean id="jsonView" class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>

Controller

@RequestMapping("/service")
public ModelAndView getResultAsJson() {
    Object jsonObj = // the java object which we want to convert to json
    return new ModelAndView("jsonView", "result", jsonObj);
}

EDIT 2013: In these modern days, @skaffman's approach would be a nice alternative.


If all you need to do is output JSON, then the view layer itself is redundant. You can use the @ResponseBody annotation to instruct Spring to serialize your model directly, using Jackson. It requires less configuration than the MappingJacksonJsonView approach, and the code is less cluttered.


As long as you are using mvc:annotation-driven and Jackson is on the classpath then all you should need to do is use @ResponseBody on on your methods and the return type will be converted to JSON per Spring's standard HTTP Message Conversion functionality.

Also check out this video at around 37:00: Mastering Spring MVC.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜