页面加载后访问数据不成功

时间:2014-06-12 01:41:01

标签: javascript jquery json jsp

我想在页面加载后访问数据,但它不起作用。似乎没有在jsp中调用getConnection函数,也没有调用响应Json。我不知道为什么它不起作用。我的代码有什么问题以及如何修复它?非常感谢你。

MyServlet.java

import java.io.*;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.reflect.TypeToken;

/**
 * Servlet implementation class MyServlet
 */
public class MyServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public MyServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        ArrayList<Dish> country=new ArrayList<Dish>();
        country=SQLConnection.getAllDish();

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

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

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

}

SQLConnection.java

import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.ArrayList;
import java.util.Properties;

public class SQLConnection {    
//  java.sql.Connection connection;
    private static Connection connection = null;
    static String url, driver, username, password;

    public static Connection getConnection() {
        if (connection != null)
            return connection;
        else {
            try {
                Properties prop = new Properties();
                InputStream inputStream = SQLConnection.class.getClassLoader().getResourceAsStream("/db.properties");
                prop.load(inputStream);
                driver = prop.getProperty("driver");
                url = prop.getProperty("url");
                username = prop.getProperty("user");
                password = prop.getProperty("password");
                Class.forName(driver);
                connection = DriverManager.getConnection(url, username, 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<Dish> getAllDish() {
        ArrayList<Dish> arrDish = null;
         try {
                //Creating a statement object
                Statement stmt = connection.createStatement();

                //Executing the query and getting the result set
                ResultSet rs = stmt.executeQuery("select * from dish");
                arrDish = new ArrayList<Dish>();
                //Iterating the resultset and printing the 3rd column
                while (rs.next()) {
                    Dish item = new Dish(rs.getInt(1), rs.getInt(2), rs.getString(3), rs.getDouble(4), rs.getString(5),
                            rs.getString(6), rs.getString(7), rs.getString(8), rs.getInt(9), rs.getInt(10), rs.getInt(11), rs.getInt(12));
                    arrDish.add(item);                  
                }
                //close the resultset, statement and connection.
                rs.close();
                stmt.close();
                connection.close();
                return arrDish;
            } catch (SQLException e) {
                e.printStackTrace();
            }
         return arrDish;
    }
}

的hello.jsp

   <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <html>
    <head>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/style.css" />

    <title><fmt:message key="title" /></title>
    </head>
        <body bgcolor="#FEDDFF">
            <script
                src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
            <script type="text/javascript" src="js/slider.js"></script>

            <script>
                $(window).ready(function() {                
                        $.get('MyServlet',function(responseJson) {
                            if(responseJson!=null){
                                $("#dishes").find("tr:gt(0)").remove();
                                var table1 = $("#dishes");
                                $.each(responseJson, function(key,value) { 
                                       var rowNew = $("<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>");
                                       rowNew.children().eq(0).int(value['dishid']); 
                                       rowNew.children().eq(1).int(value['userid']); 
                                       rowNew.children().eq(2).text(value['dishName']); 
                                       rowNew.children().eq(3).double(value['numberOfPeople']); 
                                       rowNew.children().eq(4).text(value['dishImg']); 
                                       rowNew.children().eq(5).text(value['ingredient']);
                                       rowNew.children().eq(6).text(value['step']); 
                                       rowNew.children().eq(7).text(value['descOfDish']); 
                                       rowNew.children().eq(8).int(value['category1']); 
                                       rowNew.children().eq(9).int(value['category2']); 
                                       rowNew.children().eq(10).int(value['category3']); 
                                       rowNew.children().eq(11).int(value['rate']);
                                       rowNew.appendTo(table1);
                                });
                            }
                        });
                    });
            </script>

<div id="tabledish">
                            <table cellspacing="0" id="dishes">
                                <tr>
                                    <th scope="col">dishid</th>
                                    <th scope="col">userid</th>
                                    <th scope="col">dishName</th>
                                    <th scope="col">numberOfPeople</th>
                                    <th scope="col">dishImg</th>
                                    <th scope="col">ingredient</th>
                                    <th scope="col">step</th>
                                    <th scope="col">descOfDish</th>
                                    <th scope="col">category1</th>
                                    <th scope="col">category2</th>
                                    <th scope="col">category3</th>
                                    <th scope="col">rate</th>
                                </tr>
                            </table>
                        </div>
        </body>

1 个答案:

答案 0 :(得分:0)

在SQLConnection的getAllDish()

检查并调用getConnection();

try{

if(connection==null)
    getConnection();

Statement stmt = connection.createStatement();

...