JSF + JSON:输出“纯" servlet中的文本? [英] JSF + JSON: Output "plain" text in servlet?
问题描述
我正尝试将Mootools( Request.JSON )与JSF一起使用-主要是因为前段时间我在CakePHP中编写了类似的应用程序,并且希望重用大部分JS部分. /p>
有什么方法可以使用无标记的facelet之类的请求来返回纯文本("application/json")?
我想到的唯一解决方案是使用 HttpServlet 并将其注册到web.xml中的服务URL.这种方法有效并且确实返回了没有任何标记的文件,但是我宁愿使用我的Spring注入的ManagedProperties而不是仅限于WebApplicationContextUtils.
我错过了什么吗?还是推荐的方式?
有一种方法.但这是对JSF/Facelets的丑陋且实质上是滥用,就像在使用错误的工具来完成工作一样.
例如
<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 Web服务.我不确定是否可以在其中注入Spring托管的bean,但是新的Java EE 6 CDI允许您通过@Inject
在任何地方注入@Named
bean,即使是在简单的@WebServlet
中.
另请参见:
I'm trying to use Mootools (Request.JSON) together with JSF - mainly because I wrote a similar application in CakePHP some time ago and would like to reuse most of the JS part.
Is there any way to return plain text ("application/json") using an request from something like a markup-less facelet?
The only solution I came up with was using an HttpServlet and registering it to a service URL in web.xml. That approach works and really returns an file without any markup, but I'd rather use my Spring-injected ManagedProperties than being restricted to WebApplicationContextUtils.
Did I miss something or is that the recommended way?
There is a way. But it's ugly and essentially abuse of JSF/Facelets as in using the wrong tool for the job.
E.g.
<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>
with
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();
}
Much better is to use a JAX-RS web service. I'm not sure if Spring managed beans are injectable in there, but the new Java EE 6 CDI allows you to inject @Named
beans everywhere by @Inject
, even in a simple @WebServlet
.
See also:
这篇关于JSF + JSON:输出“纯" servlet中的文本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!