无法通过在java中使用ajax从数据库中获取数据

时间:2014-05-15 09:23:25

标签: java javascript ajax jsp servlets

您正在实现使用ajax从java中的数据库中获取数据的程序。但不幸的是,这里没有退出输出是我的代码。程序正在成功运行,但无法显示它的数据库数据。

的index.jsp

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AJAX JsonArray Example</title>
<link href='http://fonts.googleapis.com/css?family=Oxygen' rel='stylesheet' type='text/css'>
<style type="text/css">
table, td, th
{
border:1px solid green;

font-family: 'Oxygen', sans-serif;

}

th
{

background-color:green;

color:white;

}
body
{
 text-align: center;

}
.container

{

 margin-left: auto;

 margin-right: auto;

 width: 40em;

}
</style>
<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){
                $("#countrytable").find("tr:gt(0)").remove();
                var table1 = $("#countrytable");
                $.each(responseJson, function(key,value) {
                     var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
                        rowNew.children().eq(0).text(value['code']);
                        rowNew.children().eq(1).text(value['name']);
                        rowNew.children().eq(2).text(value['continent']);
                        rowNew.children().eq(3).text(value['region']);
                        rowNew.children().eq(4).text(value['population']);
                        rowNew.children().eq(5).text(value['capital']);
                        rowNew.appendTo(table1);
                });
                }
            });
            $("#tablediv").show();         
  });     
});
</script>
</head>
<body class="container">
<h1>AJAX Retrieve Data from Database in Servlet and JSP using JSONArray</h1>
<input type="button" value="Show Table" id="showTable"/>
<div id="tablediv">
<table cellspacing="0" id="countrytable">
    <tr>
        <th scope="col">Code</th>
        <th scope="col">Name</th>
        <th scope="col">Continent</th>
        <th scope="col">Region</th>
        <th scope="col">Population</th>
       <th scope="col">Capital</th>         
    </tr>
</table>
</div>
</body>
</html>

FetchData.jsp

  /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */


import Countries.Countries;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Properties;


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("jdbc:mysql:");

                String url = prop.getProperty("localhost:3306/country_db");

                String user = prop.getProperty("root");

                String password = prop.getProperty("");

                Class.forName(driver);

                connection = DriverManager.getConnection("localhost:3306/country_db", "root", "");

            } 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<Countries> getAllCountries() {

     connection = FetchData.getConnection();

        ArrayList<Countries> countryList = new ArrayList<Countries>();

        try {

            Statement statement = connection.createStatement();

            ResultSet rs = statement.executeQuery("select * from country");


            while(rs.next()) {

             Countries country=new Countries();

             country.setCode(rs.getString("Code"));

             country.setName(rs.getString("Name"));

                country.setContinent(rs.getString("Continent"));

                country.setRegion(rs.getString("Region"));

             country.setPopulation(rs.getInt("Population"));

             country.setCapital(rs.getString("Capital"));

             countryList.add(country);

            }

        } catch (SQLException e) {

            e.printStackTrace();

        }



        return countryList;

    }

}

PopulateTable.java

    /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

import Countries.Countries;


import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


@WebServlet("/PopulateTable")

public class PopulateTable extends HttpServlet {

 private static final long serialVersionUID = 1L;



    public PopulateTable() {



    }



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



  ArrayList<Countries> country=new ArrayList<Countries>();

  country=FetchData.getAllCountries();

  Gson gson = new Gson();

  JsonElement element = gson.toJsonTree(country, new TypeToken<List<Countries>>() {}.getType());



  JsonArray jsonArray = element.getAsJsonArray();

  response.setContentType("application/json");

  response.getWriter().print(jsonArray);

 }

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

 }


}

Coutries.java

  /*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Countries;

public class Countries {



 public Countries(String code,String name, String continent,String region,int population, String capital )

        {     

          this.setCode(code);

          this.setName(name);
          this.setContinent(continent);

          this.setRegion(region);

          this.setPopulation(population);

          this.setCapital(capital);

        }



 public Countries() {


 }


    private String code;

    private String name;

    private String continent;

    private String region;

    private int population;  

    private String capital;





    public void setCode(String code) {

  this.code = code;

 }

 public String getCode() {

  return code;

 }



 public void setName(String name) {

  this.name = name;

 }



 public String getName() {

  return name;

 }



 public void setContinent(String continent) {

  this.continent = continent;

        }



 public String getContinent() {

  return continent;

 }



 public void setRegion(String region) {

  this.region = region;

 }



 public String getRegion() {

  return region;

 }





 public void setPopulation(int population) {

  this.population = population;

 }



 public int getPopulation() {

  return population;

 }





 public void setCapital(String capital) {

  this.capital = capital;

 }



 public String getCapital() {

  return capital;

 }

}

这是mysql数据库及其表的图像。 this is a image which contain database information

1 个答案:

答案 0 :(得分:0)

您可以先尝试找出实际问题发生的位置。
- 首先,您可以检查数据是否实际从数据库中检索。在servlet doGet方法中,您遍历国家/地区列表并使用system.out.println打印其数据 - 如果您能够检索数据,那么在客户端看到正确的Json数据即将到来。您可以使用firebug检查客户端的响应 - 在jQuery代码中使用console.log来检查数据是否来了。您可以在if(responseJson!=null)之前和之后放置日志语句,以检查数据是否实际为空。
- 如果数据不为空,则必须存在数据来源的格式或如何迭代数据的问题。