auto refresh jsp page when data changes

ε祈祈猫儿з 提交于 2019-12-08 05:26:34

问题


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?


回答1:


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" },
]



回答2:


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.




回答3:


To refresh page silently use AJAX. Below are some examples

Example 1

Example 2

Google Search



来源:https://stackoverflow.com/questions/10774446/auto-refresh-jsp-page-when-data-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!