2013-10-04 107 views
-1

我有一個jsp.i中的arraylist需要另一個jsp上的java腳本中的arraylist值。請你告訴我該怎麼做。以下是我的code.i有兩個jsp。將arraylist的值傳遞給javascript

getuser.jsp


Class.forName(driver).newInstance(); 
     conn = DriverManager.getConnection(url+dbName,userName,password); 
      String query = "select user_registeration_code from system_user_master where user_first_name ='"+firstname+"' and user_last_name='"+lastname+"' and user_phone_no='"+emp_id+"'"; 
     st = conn.createStatement(); 

     ArrayList<String> addressLists1 = new ArrayList<String>(); 
      ResultSet rs = st.executeQuery(query); 
      while(rs.next()) 
       { 


       addressLists1.add(rs.getString("user_registeration_code")); 


       } 
       out.println(addressLists1.size()); 
       //out.println(data); 
       request.setAttribute("top", addressLists1); 

second.jsp


< script type = "text/javascript" > 


function showEmp(emp_value) { 

    var fname = document.getElementById("txtfirstname").value; 
    alert(fname); 
    var lname = document.getElementById("txtlastname").value; 
    alert(lname); 
    if (document.getElementById("txtmobileno").value != "") { 
     alert("1"); 
     xmlHttp = GetXmlHttpObject(); 
     if (xmlHttp == null) { 
      alert("2"); 
      alert("Browser does not support HTTP Request"); 
      return; 
     } 
     var url = "getuser.jsp"; 
     url = url + "?emp_id=" + emp_value + "&firstname=" + fname + "&lastname=" + lname; 

     xmlHttp.onreadystatechange = stateChanged; 
     xmlHttp.open("GET", url, true); 
     xmlHttp.send(null); 

    } else { 
     alert("Please Select Employee Id"); 
    } 
} 

function stateChanged() { 
    alert("3"); 
    document.getElementById("txtfirstname").value = ""; 
    document.getElementById("txtmobileno").value = ""; 
    if (xmlHttp.readyState == 4 || xmlHttp.readyState == "complete") { 

     alert("4"); 
     var showdata = []; 
     showdata = xmlHttp.responseText; 
     alert("qqqqqqqqq" + showdata.length); 
     var i; 
     for (i = 0; i < showdata.length; i++) { 
      alert("----------------" + showdata.get(i)); 
     } 
    } 
} 

function GetXmlHttpObject() { 
    var xmlHttp = null; 
    try { 
     // Firefox, Opera 8.0+, Safari 
     xmlHttp = new XMLHttpRequest(); 
    } catch (e) { 
     //Internet Explorer 
     try { 
      xmlHttp = new ActiveXObject("Msxml2.XMLHTTP"); 
     } catch (e) { 
      xmlHttp = new ActiveXObject("Microsoft.XMLHTTP"); 
     } 
    } 
    return xmlHttp; 
} 

< /script> 

回答

0

首先,在getuser.jsp變化

request.setAttribute("top", addressLists1); 

session.setAttribute("top", addressLists1); 

然後在second.jsp像

ArrayList<String> addressLists1 = (ArrayList<String>)session.getAttribute("top"); 

,然後遍歷通過和打印清單到您的HTML/JavaScript的輸出。

順便說一下,如果您要連接到JSP中的數據庫,那麼至少應將連接到數據庫的兩行代碼移動到您在JSP中使用的類中而不僅僅是在JSP本身中有這些行。將數據庫連接部分放在JSP中是一個非常糟糕的主意。如果您的數據庫服務器名稱和密碼位於JSP中,並且JSP遇到運行時錯誤,導致它向用戶顯示有問題的代碼行,則您的數據庫密碼可能會暴露給用戶。