Enterprise Java

How to get JSON response from JSF?

Many JavaScript widgets expect data and options in JSON format. Nowadays, it is really easy to choose a cool widget and wrap it in a composite component. But the first question is how to send an AJAX request and to recieve a response in a proper JSON format. This question is often raised by JSF users. All that you need is a XHTML facelet like this one:
 
 
 
 
 
 

<f:view encoding="UTF-8" contentType="text/html"
    xmlns="http://www.w3.org/1999/xhtml"
    xmlns:h="http://xmlns.jcp.org/jsf/html"
    xmlns:f="http://xmlns.jcp.org/jsf/core">
  <h:outputText value="#{stationView.getClosestStations(param.longitude, param.latitude)}" escape="false"/>
</f:view>

Please consider the contentType=”text/html” (application/json will not work here) and escape=”false” in the h:outputText. The method getClosestStations() in the bean StationView produces an JSON output for a list of special Java objects. I advise to use the Gson library in order to serialize any Java object to JSON. Short example:

String[] strings = {"abc", "def", "ghi"};
Gson gson = new Gson();
gson.toJson(strings);  ==> prints ["abc", "def", "ghi"]

The XHTML file above is located under the web context. Say, under the path /rest/stations.xhtml. Ajax call in your JavaScript code should look like this one:

$.ajax({
    url: requestContextPath + '/rest/stations.xhtml',
    type: "GET",
    data: {
        "longitude": x,
        "latitude": y
    },
    dataType: "json",
    success: function (data) {
        $.each(data, function (i, station) {
            ...
        });
    },
    error: function () {
        ...
    }
});

Please refer the jQuery docu for more information regarding $.ajax. Note: if you omit dataType: “json”, you have to parse the JSON string manually.

success: function (data) {
    $.each($.parseJSON(data), function (i, station) {
        ...
    });
}

The response is a pure JSON string (no HTML tags) like this one:

[{"latitude":46.947045,"longitude":7.443922,"distanz":110,"name":"Bern, Bundesplatz"},{....},...]

Need more examples for JSON response in JSF? In one of my next posts I will probably explain how to implement a cool autocomplete component without writing too much code.

Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

7 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Mauricio
Mauricio
9 years ago

See JAX-RS, there is no reason to make a xhtml in order implement a rest like service… or make a servlet..
What are the advantages of doing that???

Mauricio
Mauricio
9 years ago
Reply to  Mauricio

*Which are the advantages?

Zabeus
Zabeus
8 years ago

The advantage is you’re already building a JSF app you just need to add the XHTML he shows above.

Oleg
Oleg
8 years ago

Mauricio, we are in an JSF app and need to get JSON from an JSF bean! The JSF bean can communicate with REST-, WebServices or whatever. In a multi-tier app your front-end ist JSF. You can not invoke backend directly which is represented by REST-, WebServices, EJB, etc. and delivers quite different model objects.

Edy R.
Edy R.
8 years ago

Great article.

I am using JSF2.2 and setting the f:view transient=true. Also I found no need to use h:outputText but rather directly return the backing bean method (String representing JSON object(s)).

I wonder how this compares to JAX-RS?

Cheers.

MallaReddy
MallaReddy
8 years ago

I got the json response in java script and I need to pass the json object to managed bean, is it possible to pass json object to manged bean?

Oleg
Oleg
8 years ago
Reply to  MallaReddy

Sure. Just use a hidden field. Call JSON.stringify, set the value into a hidden field and submit to the server. On the server-side you can convert JSON string to an Java object again. Even better: use p:remoteCommand (PrimeFaces) or pe:remoteCommand (PrimeFaces Extensions). They are more convienent.

Back to top button