JSF + JSON: Output "plain" text in servlet?
Asked Answered
M

2

3

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?

Malar answered 2/12, 2011 at 14:45 Comment(0)
V
5

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:

Vorous answered 2/12, 2011 at 15:0 Comment(2)
I figured I could add JAX-RS webservice as I'm already using JAX-WS anyway but your solution doesn't seem that ugly to me either. Spring's HttpRequestHandlerServlet allows me to inject beans too. Guess as always there's no real solution and I'll have to choose based on performance and maintainability.Malar
I forgot to mention that I was not able to access JSF ManagedProperties in a JAX-RS webservice. I still don't understand enough about all those components, but I especially with JS and JSON there really is a need for sessions (-objects) so that's rather strange.Malar
U
2

If you want to use facelets you can do it like this. (I don't know if spring injected beans work, but if you add @named or @managedBean then it should be accessible in the facelet)

<f:view contentType="application/json" xmlns:f="http://java.sun.com/jsf/core" >
{ test : 'value' ,
 some : #{someBean.someValue} }
 </f:view>
Uela answered 24/7, 2012 at 11:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.