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:
 
 
 
 
 
 

1
2
3
4
5
6
<f:view encoding="UTF-8" contentType="text/html"
  <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:

1
2
3
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:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
$.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.

1
2
3
4
5
success: function (data) {
    $.each($.parseJSON(data), function (i, station) {
        ...
    });
}

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

1
[{"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.

Do you want to know how to develop your skillset to become a Java Rockstar?
Subscribe to our newsletter to start Rocking right now!
To get you started we give you our best selling eBooks for FREE!
1. JPA Mini Book
2. JVM Troubleshooting Guide
3. JUnit Tutorial for Unit Testing
4. Java Annotations Tutorial
5. Java Interview Questions
6. Spring Interview Questions
7. Android UI Design
and many more ....
I agree to the Terms and Privacy Policy
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
10 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
10 years ago
Reply to  Mauricio

*Which are the advantages?

Zabeus
Zabeus
9 years ago

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

Oleg
Oleg
9 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.
9 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
9 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
9 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