I'm using JSP to develop a short project that stores a session Arraylist that contains beans, in another JSP page i have a delete() function called from a button onClick="Delete()", also is placed at the end of </body>.

<script>
function Delete(){
    var e = document.getElementById("DPwatches");
           var strUser = e.options[e.selectedIndex].text;

           var size=${fn:length(list)};
           if(size>0){
              <%
              ArrayList<Resource.Watch> list = (ArrayList<Resource.Watch>) request.getSession()
            .getAttribute("list");
              list.clear();
              %>
           }
           else{
               alert("No elements");
           }                     
}

The problem is that my function is called when page is loaded and it removes my objects from the arraylist without the button event. This is kinda frustrating since my Arraylist is working fine in others JSP pages that i have. PD: i have also implemented <body onLoad="Delete()">without results.

有帮助吗?

解决方案

Your problem is confusing server-side scriptlets with client-side JavaScript.

The following code is going to execute every time the page is loaded:

<%
    ArrayList<Resource.Watch> list = (ArrayList<Resource.Watch>) request.getSession()
        .getAttribute("list");
    list.clear();
%>

Your assumption is that it's only going to execute as part of the JavaScript function, which is incorrect. You can verify this by viewing your rendered HTML, where you will see an empty if block.

A better approach would be to do something like executing an Ajax call to a servlet method that does the same thing, instead of putting this code directly into your JSP.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top