如何从 JSF 生成 JSON 响应? [英] How to generate JSON response from JSF?

查看:30
本文介绍了如何从 JSF 生成 JSON 响应?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个页面,我想在其中从 JSF 页面获取 JSON 响应,但是当我尝试获取页面时,它显示了整个 html 页面.

I have created a page where I want to get the JSON response from a JSF page, but when i try to get page it shows me whole html page.

<html xmlns="http://www.w3.org/1999/xhtml"><head>
        <title>Facelet Title</title></head><body>
[{"value": "21", "name": "Mick Jagger"},{"value": "43", "name": "Johnny Storm"},{"value": "46", "name": "Richard Hatch"},{"value": "54", "name": "Kelly Slater"},{"value": "55", "name": "Rudy Hamilton"},{"value": "79", "name": "Michael Jordan"}]

</body></html>

推荐答案

JSF 是一个生成 HTML 的 MVC 框架,而不是某种 REST Web 服务框架.您实际上是在滥用 JSF 作为 Web 服务.您的具体问题只是由在视图文件 yourself 中放置 标签等引起的.

JSF is a MVC framework generating HTML, not some kind of a REST web service framework. You're essentially abusing JSF as a web service. Your concrete problem is simply caused by placing <html> tags and so on in the view file yourself.

如果你真的坚持,那么你总是可以通过使用 而不是 来实现这一点.您还需要确保使用了正确的 application/json 内容类型,这在 JSF 中默认为 text/html.

If you really insist, then you can always achieve this by using <ui:composition> instead of <html>. You also need to make sure that the right content type of application/json is been used, this defaults in JSF namely to text/html.

<ui:composition
    xmlns:f="http://java.sun.com/jsf/core"
    xmlns:ui="http://java.sun.com/jsf/facelets">
    <f:event type="preRenderView" listener="#{bean.renderJson}" />
</ui:composition>

public void renderJson() throws IOException {
    FacesContext facesContext = FacesContext.getCurrentInstance();
    ExternalContext externalContext = facesContext.getExternalContext();
    externalContext.setResponseContentType("application/json");
    externalContext.setResponseCharacterEncoding("UTF-8");
    externalContext.getResponseOutputWriter().write(someJsonString);
    facesContext.responseComplete();
}

但我强烈建议您查看 JAX-RS 或 JAX-WS,而不是将 JSF 滥用为 JSON Web 服务.使用适合工作的工具.

But I strongly recommend to look at JAX-RS or JAX-WS instead of abusing JSF as a JSON web service. Use the right tool for the job.

这篇关于如何从 JSF 生成 JSON 响应?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆