在Spring Controller方法中返回HTML或JSON

时间:2011-02-04 20:59:58

标签: json spring-mvc response

我想知道根据Spring Controller方法的逻辑,在同一方法中返回HTML或JSON的正确方法。我在.NET中完成了这个,只需要知道如何在Spring中执行此操作。

    UserModel user = new UserModel();       
    user.setFirstName("Michael");
    user.setLastName("Flynn");

    model.getList().add(user);
    model.setSearchTerm("test");

    if(true)
    {
        return new ModelAndView("controls/tables/users", "model", model);
    }
    else
        return model;

2 个答案:

答案 0 :(得分:0)

我最近需要解决这个问题,并且幸运地从SpringSource发布了this博客文章。

答案 1 :(得分:0)

我假设请求使用标准HTTP内容协商指示他们想要的格式。如果是这样,您可以使用ContentNegotiatingViewResolver。它还支持使用URL的“扩展名”选择格式,例如:http://localhost/content.json将选择JSON,http://localhost/content.html将选择HTML。