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.

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 two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

2 Responses to "How to get JSON response from JSF?"

  1. Mauricio says:

    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???

Leave a Reply


+ four = 7



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close