{"id":15353511,"url":"https://github.com/peterpeterparker/jsf-dogs","last_synced_at":"2026-02-13T00:37:35.513Z","repository":{"id":39951705,"uuid":"218707342","full_name":"peterpeterparker/jsf-dogs","owner":"peterpeterparker","description":"Trick JavaServer Faces, load your bean data from the client side","archived":false,"fork":false,"pushed_at":"2022-05-20T21:14:17.000Z","size":11,"stargazers_count":5,"open_issues_count":2,"forks_count":2,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-06-07T12:43:50.275Z","etag":null,"topics":["java","javascript","javaserver-faces","jsf","primefaces","tutorial"],"latest_commit_sha":null,"homepage":null,"language":"Java","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/peterpeterparker.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-10-31T07:21:23.000Z","updated_at":"2023-09-30T16:20:15.000Z","dependencies_parsed_at":"2022-08-25T08:50:50.745Z","dependency_job_id":null,"html_url":"https://github.com/peterpeterparker/jsf-dogs","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/peterpeterparker/jsf-dogs","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peterpeterparker%2Fjsf-dogs","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peterpeterparker%2Fjsf-dogs/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peterpeterparker%2Fjsf-dogs/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peterpeterparker%2Fjsf-dogs/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/peterpeterparker","download_url":"https://codeload.github.com/peterpeterparker/jsf-dogs/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/peterpeterparker%2Fjsf-dogs/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":274529029,"owners_count":25302535,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-10T02:00:12.551Z","response_time":83,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["java","javascript","javaserver-faces","jsf","primefaces","tutorial"],"created_at":"2024-10-01T12:14:11.604Z","updated_at":"2026-02-13T00:37:30.488Z","avatar_url":"https://github.com/peterpeterparker.png","language":"Java","funding_links":[],"categories":[],"sub_categories":[],"readme":"### Trick JavaServer Faces, load your bean data from the client side\n\n![](https://cdn-images-1.medium.com/max/1600/1*QSKH-4KVY9VB1ssOElKYhQ.jpeg)\n\n*Photo by [Shawn Pang](https://unsplash.com/@shawnpangg?utm_source=unsplash\u0026utm_medium=referral\u0026utm_content=creditCopyText) on [Unsplash](https://unsplash.com/?utm_source=unsplash\u0026utm_medium=referral\u0026utm_content=creditCopyText)*\n\nCommonly we are using JavaServer Faces (JSF) to access to server-side data and logic but it might happen, that we would actually have to fetch data on the client side and would then have to inject these in our server managed beans.\n\nFor example, let’s imagine that your client absolutely want to display a random cute picture provided by the third party [Dog API](https://dog.ceo/dog-api/), which we are going to use in this article, in the application but that the server, where the Java application is running, have definitely no internet access despite trying to convince both company and server administrator, that it can’t be developed without internet access.\n\nIn such a special case and in a classical Swiss🇨🇭 way of resolving issue, you will probably then have to find a consensus and to implement a trick (or hack, depends if you see the glass half full or half empty 😉) as the one we are going to develop in this blog post.\n\n### Before We Start\n\nTo follow this solution you will need a Java project where both JSF and [Primefaces](https://www.primefaces.org) are implemented. If you have none or if you would like to create a blank one, you could proceed as I displayed in my previous article “[Create a Primefaces JSF project with Maven and Widfly](https://medium.com/swlh/create-a-primefaces-jsf-project-with-maven-and-wildfly-bb695bed84c8)”.\n\n### Getting Started\n\nThe first time I faced such a dead end as pictured above, I didn’t knew where to begin. After a bit of research I finally found out the cornerstone of the solution respectively the [Primefaces](https://www.primefaces.org/showcase/ui/ajax/remoteCommand.xhtml) `\u003cp:remotecommand/\u003e` which provides a simple way to execute backing bean methods with Javascript. Using it, we are able to send data from Javascript to the beans, decode these information and ultimately “convert” them in bean’s values.\n\n#### Workflow\n\nThe workflow of the solution and the steps we are going to follow are the following:\n\n1.  Fetch data from the 3rd party API using Javascript\n1.  Pass the results from Javascript to the Java bean using `\u003cp:remotecommand/\u003e`\n1.  Parse the information to actual bean object values\n1.  Display the bean values on the client side\n1.  Init the page with a data\n\nLet’s get started 🚀\n\n### 1. Fetch data from the 3rd party API using Javascript\n\nTo begin our implementation we are firstly creating a new page `src/main/webapp/dogs.xhtml` which contains a button, to trigger manually the start of our process, and the remote command. Both components have to be contained in a form.\n\nMoreover we also add the actual implementation of the 3rd party API data fetching. For that purpose, we use the Javascript [Fetch API](https://developer.mozilla.org/fr/docs/Web/API/Fetch_API/Using_Fetch).\n\n```html\n\u003c!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\"\n          \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\"\u003e\n\u003chtml xmlns=\"http://www.w3.org/1999/xhtml\"\n     xmlns:h=\"http://java.sun.com/jsf/html\"\n     xmlns:p=\"http://primefaces.org/ui\"\u003e\n\u003ch:head\u003e\n   \u003ctitle\u003eRandom dog\u003c/title\u003e\n\u003c/h:head\u003e\n\u003ch:body\u003e\n\n   \u003cscript type=\"text/javascript\"\u003e\n      const randomDog = async () =\u003e {\n        const rawResponse =\n          await fetch('https://dog.ceo/api/breeds/image/random');\n        if (!rawResponse || !rawResponse.ok) {\n           console.error(rawResponse);\n          return;\n        }\n        const result = await rawResponse.text();\n      };\n  \u003c/script\u003e\n\n  \u003ch:form\u003e\n     \u003cp:remoteCommand name=\"loadResult\"/\u003e\n\n     \u003cp:commandButton value=\"Load a random dog\"\n                      onclick=\"randomDog();\"\u003e\n         \u003cf:ajax execute=\"@form\" render=\"@none\" /\u003e\n     \u003c/p:commandButton\u003e\n  \u003c/h:form\u003e\n\n\u003c/h:body\u003e\n\n\u003c/html\u003e\n```\n\n### 2. Pass the results to the bean\n\nYou may have noticed that the above `\u003cp:button/\u003e` doesn’t classically call a bean action or listener but rather call immediately the Javascript function `randomDog();` . It means that first of all, we are fetching the data from the client side. Therefore we should now to pass the results to the bean. For that purpose we create a new bean `src/main/java/DogsBean.java` which exposes a method `load()` in order to, guess what, load later one our data 😁.\n\n```java\nimport java.io.Serializable;\nimport javax.faces.view.ViewScoped;\nimport javax.inject.Named;\n\n@Named(\"dogs\")\n@ViewScoped\npublic class DogsBean implements Serializable {\n   public void load() {\n      // TODO load the data to object values\n   }\n}\n```\n\nOur bean being ready, we could now improve our servlet respectively we link the `\u003cp:remotecommand/\u003e` with the bean `load()` method.\n\n```html\n\u003ch:form\u003e\n     \u003cp:remoteCommand name=\"loadResult\"\n                      action=\"#{dogs.load()}\"\n                      process=\"@this\" update=\"@form\"/\u003e\n\u003c/h:form\u003e\n```\n\nWe complete the chain by calling the remote command with the result of the Javascript `fetch` 🤓 . For that purpose, we use the function created by the Primefaces remote command, identified with the name `loadResult` we provided, and we pass the information as a new JSON array containing an identifier, a `name` , and a `value` , the result of the fetch respectively the data as text.\n\n```html\n\u003cscript type=\"text/javascript\"\u003e\n      // same code as above\n\n      const result = await rawResponse.text();\n\n      loadResult([{\n        name: 'dog',\n        value: result\n      }]);\n    };\n\u003c/script\u003e\n```\n\nThis call will submit a new request to the server. We could therefore access the parameters of the request in our bean to find out the data we are interested in. These are identified with the identifier, the `name` we provided above respectively `'dog'` .\n\n```java\npublic void load() {\n   final String jsonData = FacesContext.getCurrentInstance()\n                           .getExternalContext()\n                           .getRequestParameterMap()\n                           .get(\"dog\");\n}\n```\n\n### 3. Parse the information to bean object values\n\nThe data delivered by the Dog API are provided as JSON data, for example:\n\n```\n{\n    \"message\": \"https://images.dog.ceo/breeds/coonhound/n02089078_2794.jpg\",\n    \"status\": \"success\"\n}\n```\n\nTherefore, in order to parse these to Java object values, we create a new corresponding data transfer object (DTO).\n\n```java\nimport java.io.Serializable;\n\npublic class DogDTO implements Serializable {\n\n   private String message;\n   private String status;\n\n   public String getMessage() {\n      return message;\n   }\n   public void setMessage(String message) {\n      this.message = message;\n   }\n   public String getStatus() {\n      return status;\n   }\n   public void setStatus(String status) {\n      this.status = status;\n   }\n}\n```\n\nHaving both data and Java object, we could now deserialize the information using the Google [gson](https://github.com/google/gson) library which we add as a new dependency in our `pom.xml` .\n\n```xml\n\u003cdependency\u003e\n  \u003cgroupId\u003ecom.google.code.gson\u003c/groupId\u003e\n  \u003cartifactId\u003egson\u003c/artifactId\u003e\n  \u003cversion\u003e2.8.6\u003c/version\u003e\n\u003c/dependency\u003e\n```\n\nWe declare declare the above DTO as a member of the bean class and we effectively process the parsing of the data in our `load()` method.\n\n```java\nimport java.io.Serializable;\nimport javax.faces.context.FacesContext;\nimport javax.faces.view.ViewScoped;\nimport javax.inject.Named;\nimport com.google.gson.Gson;\nimport com.google.gson.GsonBuilder;\n\n@Named(\"dogs\")\n@ViewScoped\npublic class DogsBean implements Serializable {\n   \n   private DogDTO dog;\n\n   public void load() {\n      final String jsonData = FacesContext.getCurrentInstance()\n                           .getExternalContext()\n                           .getRequestParameterMap()\n                           .get(\"dog\");\n      final Gson gson = new GsonBuilder().create();\n      dog = gson.fromJson(jsonData, DogDTO.class);\n   }\n\n   public DogDTO getDog() {\n      return dog;\n   }\n}\n```\n\n### 4. Display the bean values on the client side\n\nWe have now fetched data on the client side, sent these to the server but the user still don’t notice any results. For that reason we add a new image to our page which uses our DTO `message` variable as source.\n\n```html\n\u003ch:form\u003e\n     \u003cp:outputPanel layout=\"block\" rendered=\"#{dogs.dog != null}\"\u003e\n        \u003cimg src=\"#{dogs.dog.message}\" alt=\"A random dog\"/\u003e\n     \u003c/p:outputPanel\u003e\n\u003c/h:form\u003e\n```\n\nThat’s it, our implementation is ready. We could start our application server in a terminal to try out the solution.\n\n```bash\nmvn clean install \u0026\u0026 mvn wildfly:run\n```\n\nIf everything goes according plan, we could open  our application in our favorite browser at the address [http://localhost:8080/jsf-dogs/dogs.xhtml](http://localhost:8080/jsf-dogs/dogs.xhtml) and should now be able to fetch a random dog each time we call our action 😊\n\n![](https://cdn-images-1.medium.com/max/1600/1*lolMm4r-XdSiapWohK4pLg.gif)\n\n*So much doggy 😍*\n\n### 5. Init the page with a data\n\nThis step isn’t mandatory but I think it’s interesting to notice that it is also possible to load data from the client side when the page is accessed. Basically, from the sever side, in our bean, we execute  a Javascript function on the client side, once everything is loaded from the lifecycle `PostContruct` .\n\n```java\n@PostConstruct\npublic void init() {\n   PrimeFaces.current().executeScript(\"randomDog();\");\n}\n```\n\nThat’s it, we dit it! We could restart our server and test our final implementation 🎉\n\n![](https://cdn-images-1.medium.com/max/1600/1*jjw6lTngEY7xlODjsbKYjQ.gif)\n\n*An initial doggy and so much other doggy 😍*\n\n### Cherry on the cake 🍒🎂\n\nIf you want to avoid the hassle of creating your own project and copying/pasting the above code, I have published the source code and project online on [GitHub](https://github.com/peterpeterparker/jsf-dogs), be my guest and as always, I would be really happy to hear your feedback 😃\n\nTo infinity and beyond 🚀\n\nDavid\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpeterpeterparker%2Fjsf-dogs","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpeterpeterparker%2Fjsf-dogs","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpeterpeterparker%2Fjsf-dogs/lists"}