使用servlet和ajax从数据库填充文本框中的值

时间:2014-02-24 18:02:32

标签: javascript jquery ajax jsp servlets

我在数据库中有以下数据。我想通过使用servlet和ajax填充此数据来填充我的文本字段。

data_id ------------------------ char(30)
Lat --------------------------双精度
长-------------------------双精度

Info.class

package org.bean

 public class Info {

private String data_id;
    private String lat;
    private String long;



     public void setData_id(String data_id) {
    this.data_id = data_id;
}
public String getData_id() {
    return data_id;
}

public void setLat(String lat) {
    this.lat = lat;
}

public String getLat() {
    return lat;
}

public void setLong(String long) {
    this.long = long;
}

public String getLong() {
    return long;
}

}

FetchData.class

public class FetchData {

private static Connection connection = null;

public static Connection getConnection() {
    if (connection != null)
        return connection;
    else {
        try {
            Properties prop = new Properties();
            InputStream inputStream =                  

            FetchData.class.getClassLoader().getResourceAsStream("/db.properties");
            prop.load(inputStream);
            String driver = prop.getProperty("driver");
            String url = prop.getProperty("url");
            String user = prop.getProperty("user");
            String password = prop.getProperty("password");
            Class.forName(driver);
            connection = DriverManager.getConnection(url, user, password);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return connection;
    }

}

public static ArrayList<Info> getAllInfo() {
    connection = FetchData.getConnection();
    ArrayList<Info> inf = new ArrayList<Info>();
    try {
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery("select * from info_table");

        while(rs.next()) {  
            Info in=new Info();
            in.setData_id(rs.getString("data_id"));
            in.setLat(rs.getString("Lat"));
            in.setLong(rs.getString("Long"));
            inf.add(in);
        }
    } catch (SQLException e) {
        e.printStackTrace();
    }

    return inf;
}
}

PopulateTable.class

public class PopulateTable extends HttpServlet {
  private static final long serialVersionUID = 1L;

public PopulateTable() {

}

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    ArrayList<Info> in=new ArrayList<Info>();
    in=FetchData.getAllInfo();
    Gson gson = new Gson();
    JsonElement element = gson.toJsonTree(in, new TypeToken<List<Info>>() {}.getType());

    JsonArray jsonArray = element.getAsJsonArray();
    response.setContentType("application/json");
    response.getWriter().print(jsonArray);

}


protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

}

}

的index.jsp

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
 $(document).ready(function() {
$("#tablediv").hide();
 $("#showTable").click(function(event){
       $.get('PopulateTable',function(responseJson) {
           if(responseJson!=null){
               $("#infotable").find("tr:gt(0)").remove();
               var table1 = $("#infotable");
               $.each(responseJson, function(key,value) { 
                       var rowNew = $("<tr><td></td><td></td><td></td></tr>");
                       rowNew.children().eq(0).text(value['data_id']); 
                       rowNew.children().eq(1).text(value['lat']); 
                       rowNew.children().eq(2).text(value['long']);
                       rowNew.appendTo(table1);
               });
            }
        });
        $("#tablediv").show();          
 });      
});
</script>
</head>

 <input type="button" value="Show Table" id="showTable"/>
 <br/>
 <br/>
<div id="tablediv">
<table cellspacing="0" id="infotable"> 
<tr> 
    <th scope="col">Data_id</th> 
    <th scope="col">Latitude</th> 
    <th scope="col">Longitude</th> 

</tr> 
</table>
</div>
</body>
</html>

我基本上是在jsp页面上使用servlet和ajax在表中填充数据库数据而不刷新页面。我希望采取同样的行动。我没有单击按钮,而是希望用户输入要从数据库填充的文本字段纬度和经度值的data_id和onkeyup事件。我该怎么做呢。

如果我将jsp页面更改为

<input type="text" id="data_id" onblur=""/>
<input type="text" id="latitude"/>
<input type="text" id="longitude"/>

然后onblur事件应该填充具有id纬度和经度的文本字段,其中包含与键入的id相对应的数据。我该怎么做呢?

2 个答案:

答案 0 :(得分:0)

而不是将您的Ajax调用放在$(document).ready(function() {...});中,而是将其置于具有名称的函数中,并让您的onblur调用它:

function populatefields()
{
  ... //Ajax stuff
}
...
...
<input type="text" id="data_id" onblur="populatefields()" />

答案 1 :(得分:-1)

<%@page import="java.util.logging.Logger"%>
<%@page import="java.util.logging.Level"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="javax.swing.JFrame"%>
<%@page import="javax.swing.JButton"%>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Student view</title>
<link href="style.css" rel="stylesheet" type="text/css" />
 <script>
    function selectItem()
    {
    var sel=document.getSelection("drop").value;
    var c=document.getElementById("drop").value;
    var xmlhttp,url;
    if(c=="hand")
        url="StudentView_2.jsp";
    else
        url="StudentView.jsp";
    if (window.XMLHttpRequest)
{
    xmlhttp = new XMLHttpRequest(); //for IE7+, Firefox, Chrome, Opera, Safari
}
else
{
    xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); //for IE6, IE5
}
xmlhttp.open("GET",url,true);
xmlhttp.send();

xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4) { 
        if (xmlhttp.status == 200) 
        {

            document.getElementById("message1").innerHTML = xmlhttp.responseText;
        } 
        else
        {
            alert('Something is wrong !!');
        }
    }

    }
}

    </script>
</head>


<body>
<div id="topPan"> <!--<a href="http://www.free-css.com/"><img src="" alt="Education Zone" width="245" height="37" border="0"  class="logo" title="Education Zone"/></a>-->
    <h1> <p>Library Manager</p></h1>
  <div id="topContactPan"> </div>
  <div id="topMenuPan">
    <div id="topMenuLeftPan"></div>
    <div id="topMenuMiddlePan">
      <ul>
          <li class="home"><a href="StudentView.jsp">Home</a></li>
        <li><a href="index.jsp">Logout</a></li>


<!--        <li class="contact"><a href="" class="contact">Contact</a></li>-->
      </ul>
    </div>
    <div id="topMenuRightPan"></div>
  </div>
</div>
<div id="bodyPan">
  <div id="bodyLeftPan">
    <h2><span>Student View</span> </h2>
<!--    <p>Education Zone is a free, tableless, W3C-compliant web design layout by <span>Template World</span>. This template has been tested and proven compatible with all major browser environments and operating systems. You are free to modify the design to suit your tastes in any way you like.</p>
    <p>We only ask you to not remove "Design by Template World" and the link <span>http://www.templateworld.com</span> from the footer of the template.</p>
    <p>If you are interested in seeing more of our free web template designs feel free to visit our website, Template World. We intend to add at least 25 new <span>free templates</span> in the coming month.</p>
    -->


<!--    <form action="StudentView_1.jsp">
        <input type="submit" value="View All Books"  >
    </form>   
    <form action="StudentView_2.jsp">
        <input type="submit" value="In Hand"  >
    </form> -->
<form >
    <select name="drop" id="drop" onchange="selectItem()">

        <option value="view" >View All</option>
        <option value="hand">In Hand</option>
    </select>
        <!--<input type="" value="In Hand"  >-->
    </form>
   <%
//       try{
//            // TODO add your handling code here:
//            String [] colname={"Book Id","Book Name","Book Author"};
//            Class.forName("com.mysql.jdbc.Driver");
//            Connection conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","mysql");
//            Statement st=conn.createStatement();
//            System.out.println("success");
//            String sql1="select * from book where Available='1'";
//            ResultSet rs=st.executeQuery(sql1);
//            int n=0,i=0;
//            while(rs.next())
//            {   
//               n++;
//            }
//            rs.beforeFirst();
//            Object [][] o=new Object[n][3];
//            out.println("<table border=1>");
//            out.println("<tr><td>Book Id</td><td>Book Name</td><td>Book Author</td></tr>");
//            
//            while(rs.next())
//            {
//             o[i][0]=rs.getString(1);
//             o[i][1]=rs.getString(2);
//             o[i][2]=rs.getString(3);
//             out.println("<tr><td>"+o[i][0]+"</td><td>"+o[i][1]+"</td><td>"+o[i][2]+"</td></tr>");
//             i++;
//            }
//            out.println("</table>");
//            
//       }catch(Exception ee)
//       {
//           
//       }
    //   Object ss=request.getParameter("xx");
       //System.out.println(ss);
      // session.setAttribute("pp",ss );
   %>

  </div>
  <form>

  </form>
   <div id="message1" class="aaa">



<%@ page language="java" contentType="text/html; charset=ISO-8859-1" %>

<%@ page import="java.sql.PreparedStatement"  %>

<%@ page import="java.sql.ResultSet" %>

<%@ page import="java.sql.Connection" %>

<%@ page import="java.sql.DriverManager" %>

<%!

public int Converter(String str)

{   

    int convrtr=0;

    if(str==null)

        {

            str="0";

        }

    else if((str.trim()).equals("null"))

        {

            str="0";

        }

    else if(str.equals(""))

        {

            str="0";

        }

    try{

            convrtr=Integer.parseInt(str);

        }

    catch(Exception e)

        {

        }

    return convrtr;

}

%>

<%

    Connection con = null;

    Class.forName("com.mysql.jdbc.Driver").newInstance();

    con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root", "mysql");



    ResultSet rsPgin = null;

    ResultSet rsRwCn = null;

    PreparedStatement psPgintn=null;

    PreparedStatement psRwCn=null;



    // Number of records displayed on each page

    int iSwRws=4;  

    // Number of pages index displayed

    int iTotSrhRcrds=10; 



    int iTotRslts=Converter(request.getParameter("iTotRslts"));

    int iTotPags=Converter(request.getParameter("iTotPags"));

    int iPagNo=Converter(request.getParameter("iPagNo"));

    int cPagNo=Converter(request.getParameter("cPagNo"));



    int iStRsNo=0;

    int iEnRsNo=0;



    if(iPagNo==0)

        {

            iPagNo=0;

        }

    else{

            iPagNo=Math.abs((iPagNo-1)*iSwRws);

        }



    String sqlPgintn="SELECT SQL_CALC_FOUND_ROWS * FROM book limit "+iPagNo+","+iSwRws+"";

    psPgintn=con.prepareStatement(sqlPgintn);

    rsPgin=psPgintn.executeQuery();

    // Count total number of fetched rows

    String sqlRwCnt="SELECT FOUND_ROWS() as cnt";

    psRwCn=con.prepareStatement(sqlRwCnt);

    rsRwCn=psRwCn.executeQuery();



    if(rsRwCn.next())

      {

        iTotRslts=rsRwCn.getInt("cnt");

      }

%>

<html>

    <head>

        <title>Pagination using JSP page</title>

    </head>

<body>

    <form name="frm">

        <input type="hidden" name="iPagNo" value="<%=iPagNo%>">

        <input type="hidden" name="cPagNo" value="<%=cPagNo%>">

        <input type="hidden" name="iSwRws" value="<%=iSwRws%>">



        <table cellpadding="0" cellspacing="0" border="1" >

        <tr>

        <td>BookId</td>

        <td>BookName</td>

        <td>BookAuthor</td>

        </tr>

<%

    while(rsPgin.next())

      {

%>

        <tr>

            <td><%=rsPgin.getString(1)%></td>

            <td><%=rsPgin.getString(2)%></td>

            <td><%=rsPgin.getString(3)%></td>

            <td><a href="www.google.com>view </a></td>

        </tr>

<% 

     }

%>

<%

    // Calculate next record start and end position 

    try{

        if(iTotRslts<(iPagNo+iSwRws))

            {

                iEnRsNo=iTotRslts;

            }

        else

            {

                iEnRsNo=(iPagNo+iSwRws);

            }



            iStRsNo=(iPagNo+1);

            iTotPags=((int)(Math.ceil((double)iTotRslts/iSwRws)));

        }

    catch(Exception e)

        {

                e.printStackTrace();

        }

%>

<tr>

<td colspan="3">

<div>

<%

     // Create index of pages 

    int i=0;

    int cPge=0;

    if(iTotRslts!=0)

       {

        cPge=((int)(Math.ceil((double)iEnRsNo/(iTotSrhRcrds*iSwRws))));

        int prePageNo=(cPge*iTotSrhRcrds)-((iTotSrhRcrds-1)+iTotSrhRcrds);

        if((cPge*iTotSrhRcrds)-(iTotSrhRcrds)>0)

            {

        %>

        <a href="StudentView.jsp?iPagNo=<%=prePageNo%>&cPagNo=<%=prePageNo%>"><< Previous</a>

        <%

        }



        for(i=((cPge*iTotSrhRcrds)-(iTotSrhRcrds-1));i<=(cPge*iTotSrhRcrds);i++)

        {

            if(i==((iPagNo/iSwRws)+1))

            {

            %>

        <a href="StudentView.jsp?iPagNo=<%=i%>" style="cursor:pointer;color:red"><b><%=i%></b></a>

            <%

            }

            else if(i<=iTotPags)

            {

            %>

        <a href="StudentView.jsp?iPagNo=<%=i%>"><%=i%></a>

            <% 

            }

        }



        if(iTotPags>iTotSrhRcrds&& i<iTotPags)

        {

         %>

        <a href="StudentView.jsp?iPagNo=<%=i%>&cPagNo=<%=i%>">>> Next</a>

        <%

        }

      }

      %>

    <b>Rows <%=iStRsNo%> - <%=iEnRsNo%>   Total Result  <%=iTotRslts%></b>

</div>

</td>

</tr>

</table>

</form>

</body>

</html>

<%

try{

    if(psPgintn!=null){

        psPgintn.close();

    }

    if(rsPgin!=null){

        rsPgin.close();

    }   

    if(psRwCn!=null){

        psRwCn.close();

    }

    if(rsRwCn!=null){

        rsRwCn.close();

    }

    if(con!=null){

        con.close();

    }

  }

catch(Exception e)

  {

    e.printStackTrace();

  }

%>


   </div>
<!--<table id="message1" align="left" width="200" border="1" class="aaa">
</table>-->
<!--<form>
<select name="message1" id="message1">

</select>
</form>-->
  <div id="bodyRightPan1">


  </div>
</div>
<div id="footermainPan">
  <div id="footerPan">
    <ul>
     <li><a href="index.jsp">Home</a>| </li>
      <li><a href="Registration.jsp">Registration</a>| </li>
    </ul>
    <p class="copyright">©education zone. All right reserved.</p>
    <ul class="templateworld">
      <li>design by:</li>
      <li><a href="http://www.templateworld.com" target="_blank">Template World</a></li>
    </ul>
    <div id="footerPanhtml"><a href="http://validator.w3.org/check?uri=referer" target="_blank">HTML</a></div>
    <div id="footerPancss"><a href="http://jigsaw.w3.org/css-validator/check/referer" target="_blank">css</a></div>
  </div>
</div>
</body>
</html>