2016-05-30 67 views
0

直到现在发送ajax请求时,在我们的控制器中,我们确实返回了JsonMessage并在客户端装饰数据。但是最近我们正在使用第三方的UI框架,它接受了可以使用HTML作为Ajax回调的准备。Java Spring通过模板创建响应

有没有办法做到这一点,而不是所有的HTML标记到控制器?像一个后处理器,它接受json和一个模板,呈现它然后发送给客户端?

注意:响应采用JSON格式,其中包含一个包含该html的属性。

我们使用springframework 4.2.6。

+0

只是处理它像这样http://stackoverflow.com/questions/22422411/how-to-manually-render-spring-mvc-view-to-html –

回答

0

一般你需要在控制器中添加一些方法,返回ModelAndView对象。

此外,您还需要配置ViewResolver并在ModelAndView对象中设置视图名称和对应的模型。 像这样

@Controller 
public class DefaultController { 
    @RequestMapping(value = "/html", produces = "application/json") 
    public ModelAndView getUserHtml(HttpServletResponse response) throws Exception { 
    response.setContentType("application/json"); 
    return new ModelAndView("user", Collections.singletonMap("user", this.user)); 
    } 
} 

,你会看到响应这样

{ 
    "response": "<div><h1>Java Spring creating response from template</h1><h2>User</h2><p>username: superuser</p><p>password: secret</p><p>email: [email protected]</p></div></html>" 
} 

工作示例项目:https://github.com/sandarkin/so-q37526576

+0

我试过这个,谢谢,但是这样会返回html,而不是包含该html的json:\ –

+0

OK。我已经通过强制设置内容类型来调整示例项目。现在http:// localhost:8080/default/html将返回正确的内容类型的json。 –