1

I have a JSP page which shows items included in an Array (Just a very simple list).
In the background the Array might change i.e. adds a new Item or remove one.

How can I auto refresh the page when the Array changes?

Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276
MBZ
  • 26,084
  • 47
  • 114
  • 191

3 Answers3

3

There are 2 ways that are most popular to perform such operation

  • pool a method that would send 1 or 0 to see if you refresh the page or not
  • keep asking for that data array and populate it through javascript

Option 1

  • create a .jsp page and call it, for example, updateList.jsp
  • add a single method that will check if there is more data to be filled and output 1 or 0 like: out.println(1)
  • in your page, and using jQuery to simplify things
 $.get("updateList.jsp", function(data) {
    if(data !== null && data.length > 0 && data === 1) {
        // refresh this page
        document.location = document.location.href;
    }
 });

Option 2

  • create a .jsp page and call it, for example, data.jsp
  • add a single method that will output a JSON string containing all data you need to populate the list
  • in your page, and using jQuery and JsRender to simplify things
 $.get("updateList.jsp", function(data) {
    if(data !== null && data.length > 0) {
        $("#my-list").html(
            $("#my-template").render(data);
        );
    }
 });

and in your HTML you will have:

<ul id="my-list"></ul>

<script id="my-template" type="text/x-jsrender">
    {{for items}}
      <li>{{:name}}</li>
    {{/for}}
</script>

assuming your JSON would be something like:

item: [
    { name: "Name A" },
    { name: "Name B" },
    { name: "Name C" },
]
balexandre
  • 73,608
  • 45
  • 233
  • 342
1

Once the JSP has been executed, the HTML code that it has generated has been sent to the browser, and there is no connection between the browser and the JSP anymore. If you want to refresh some part of the page, you need to poll the server using AJAX, or use WebSockets to maintain a connection between the page and the server.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
0

To refresh page silently use AJAX. Below are some examples

Example 1

Example 2

Google Search

Community
  • 1
  • 1
Fahim Parkar
  • 30,974
  • 45
  • 160
  • 276