JSON Renderkit - or how do I return JSON to a JSF client?
I am making an AJAX call using jQuery to a JSF 2.0 server. The "page" I am calling looks something like this:
<ui:composition template="/templates/jsonTemplate.xhtml">
<ui:define name="content">
#{tabBean.jsonUrl}
</ui:define>
</ui:composition>
Where my jsonTemplate.xhtml looks something like this:
<html xmlns:ui="http://java.s开发者_运维技巧un.com/jsf/facelets">
<ui:insert name="content" />
</html>
The result that is send to the client contains my JSON Object and the HTML tags, which I have to strip off on the client.
What I want returned is a pure JSON Object.
{ "url" : "/this/is/my/url.xhtml" }
On the client, I strip off the <HTML> and the </HTML> tags, use jQuery to parseJSON and return a JSON Object. I tried to specify the template without the HTML tags and it complained. Seems like this is the bare minimum response I can generate.
I would like to have a RenderKit that would enable me to return nothing but pure JSON.
I would advise you tp use a RESTEasy library with a Jaxson provider. It's not hard to start with it. After proper configuration you will need only to implement ajax request to a server. Java code would be smth like:
@POST
@Path("/getPossiblePhases")
@Encoded
@Produces("application/json")
public List<Process> getPossiblePhases(@FormParam("prfID") Long prfID){
return new List<Process>(); // some list here for example
}
and as response you will get only JSON. Ofc it supports xml, GET requests and have lots of other features. Supports Spring.
Just don't emit those HTML tags.
Replace
<html xmlns:ui="http://java.sun.com/jsf/facelets">
<ui:insert name="content" />
</html>
By
<ui:composition xmlns:ui="http://java.sun.com/jsf/facelets">
<ui:insert name="content" />
</ui:composition>
Much better is however indeed to use a webservice for this. JSF is a component based MVC framework, not a web service framework. Look at JAX-RS/JAX-WS.
精彩评论