How to create one Controller which returns same Model to arbitrary view (HTML-Form or Ajax)?

浪子不回头ぞ 提交于 2020-01-25 03:45:41

问题


In my classic understanding of the MVC pattern the controller doesn't have to know any implementation details of the view. I want to have a controller which gets triggered by an event (a @RequestMapping) and returns a model. It's up to the view how to present the Model.

The concret use case is adding an item into a shopping cart. I have two views, a simple HTML view and a richer Ajax-View. In my dream scenario both views make a request to the identical URI and hit the only method in my Controller:

@Controller
public class ShoppingCartController {

    @RequestMapping("/add")
    public String addItem(@RequestParam String itemId, Model model) {
        // …
        model.add(shoppingCart);
        return "cart";
    }

}

My Ajax view sends a request to /add?itemId=abc and would get ideally the model in JSON. My HTML view sends to the same request and renders the model into a JSP.

My current approach is implementing a second method in the controller which calls addItem() and returns the JSON:

@RequestMapping(value="/add", headers="x-requested-with=XMLHttpRequest")
public @ResponseBody ShoppingCart addItemByAjax(@RequestParam String itemId, Model model) {
    addItem(itemId, model);
    return model.asMap().get("shoppingCart");
}

I don't really like that idea of decorating every controller with a view dependent Model adapter. Is there are more generic way to serve the view with the approriate presentation of the model? I want to have only one method in my controller which sends the model to any view. Of course there must exist somewhere on the stack a handler which decides to serve the model as JSON if some condition is true (let's say x-requested-with=XMLHttpRequest).


回答1:


ContentNegotiatingViewResolver configured with a MappingJackson2JsonView as default view seems to help. It was more trial and error than reading documentation. Plus for me it reads not so intuitiv setting the default view to JSON. And I wonder how you guys solved this common use case before Spring 3.2.



来源:https://stackoverflow.com/questions/14076682/how-to-create-one-controller-which-returns-same-model-to-arbitrary-view-html-fo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!