开发者

Return HTML or JSON in a Spring Controller Method

开发者 https://www.devze.com 2023-02-08 10:07 出处:网络
I am wondering the correct way to return HTML or JSON inside the same method depending on logic on a Spring Controller method.I have done this in .NET, just need to know how to do this in Spring.

I am wondering the correct way to return HTML or JSON inside the same method depending on logic on a Spring Controller method. I have done this in .NET, just need to know how to do this in Spring.

    UserModel user = new UserModel();       
    user.setFirstName("Michael");
    user.setLastName("开发者_JS百科Flynn");

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

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


I needed to figure this out recently and had luck with this blog post from SpringSource.


I am assuming that the requests are indicating which format they want using standard HTTP content negotation. If so you can use the ContentNegotiatingViewResolver. It also supports selection of format using an "extension" of a URL, for example: http://localhost/content.json would select JSON and http://localhost/content.html would select HTML.

0

精彩评论

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