为什么我不能使用DT来创建使用Mysql数据的表

时间:2016-12-08 14:09:54

标签: jquery mysql json servlets datatables

package servlet;

import bean.Student;
import dao.StudentDAO;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 
 * 
 */
public class GetStuInfoServlet extends HttpServlet {
    private String stuNumber;
    private String stuName;
    private String stuNamed;
    private String stuSex;
    private String stuNation;
    private String stuBirth;
    private String stuNative;
    private String stuRegious;
    private String stuPolitical;
    private String stuHealth;
    private String stuSpecial;
    private String stuResidence;
    private String stuSchoolRoll;
    private String regiousSeat;
    private String stuID;
    private String stuAddress;
    private String stuMobile;
    private String stuEmail;
    private String stuEntranceWay;
    private String stuAlone;
    private String stuMartyr;
    private String stuSingle;
    private String stuFarmer;
    private String stuEnteranceDate;
    private String stuClass;

    String datastr="{ \"data\":[";//ajax  json

    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException,IOException{
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=utf-8");
        String classNumbers = null;
        String stuNumbers = null;
        ResultSet resultSet = null;
        classNumbers = request.getParameter("classNumber");

        StudentDAO studentDAO = new StudentDAO();
        Student student = null;
        PrintWriter out = response.getWriter();
        out.flush();
        try {
            resultSet = studentDAO.getStudentByClassNumber(classNumbers);
        } catch (Exception e) {
            e.printStackTrace();
        }
            resultSet = studentDAO.getStudentByStuNumber(stuNumber);
           resultSet = studentDAO.getStudentByClassNumber(classNumbers);

        try {
            while (resultSet != null & resultSet.next()){
                this.stuNumber = resultSet.getString("stu_number");
                this.stuName = resultSet.getString("stu_name");
                this.stuNamed = resultSet.getString("stu_named");
                this.stuSex = resultSet.getString("stu_sex");
                this.stuNation = resultSet.getString("stu_nation");
                this.stuBirth = resultSet.getString("stu_birth");
                this.stuNative = resultSet.getString("stu_native");
                this.stuRegious = resultSet.getString("stu_religious");
                this.stuPolitical = resultSet.getString("stu_political");
                this.stuHealth = resultSet.getString("stu_health");
                this.stuSpecial = resultSet.getString("stu_special");
                this.stuResidence = resultSet.getString("stu_residence");
                this.stuSchoolRoll = resultSet.getString("stu_school_roll");
                this.regiousSeat = resultSet.getString("regious_seat");
                this.stuID = resultSet.getString("stu_id");
                this.stuAddress = resultSet.getString("stu_adress");
                this.stuMobile = resultSet.getString("stu_mobile");
                this.stuEmail = resultSet.getString("stu_email");
                this.stuEntranceWay = resultSet.getString("stu_entrance_way");
                this.stuAlone = resultSet.getString("stu_alone");
                this.stuMartyr = resultSet.getString("stu_martyr");
                this.stuSingle = resultSet.getString("stu_single");
                this.stuFarmer = resultSet.getString("stu_farmer");
                this.stuEnteranceDate = resultSet.getString("stu_enterance_date");
                this.stuClass = resultSet.getString("stu_class");

                if (stuNumber==null){stuNumber="";}
                if (stuName==null){stuName="";}
                if (stuNamed==null){stuNamed="";}
                if (stuSex==null){stuSex="";}
                if (stuNation==null){stuNation="";}
                if (stuBirth==null){stuBirth="";}
                if (stuNative==null){stuNative="";}
                if (stuRegious==null){stuRegious="";}
                if (stuPolitical==null){stuPolitical="";}
                if (stuHealth==null){stuHealth="";}
                if (stuSpecial==null){stuSpecial="";}
                if (stuResidence==null){stuResidence="";}
                if (stuSchoolRoll==null){stuSchoolRoll="";}
                if (regiousSeat==null){regiousSeat="";}
                if (stuID ==null){stuID ="";}
                if (stuAddress==null){stuAddress="";}
                if (stuMobile==null){stuMobile="";}
                if (stuEmail==null){stuEmail="";}
                if (stuEntranceWay==null){stuEntranceWay="";}
                if (stuAlone==null){stuAlone="";}
                if (stuMartyr==null){stuMartyr="";}
                if (stuSingle==null){stuSingle="";}
                if (stuFarmer==null){stuFarmer="";}
                if (stuEnteranceDate==null){stuEnteranceDate="";}
                if (stuClass==null){stuClass="";}


                datastr = datastr + "{\"stuNumber\":\""+stuNumber+"\","
                    + "\"stuName\":\""+stuName+"\","
                    + "\"stuNamed\":\""+stuNamed+"\","
                    + "\"stuSex\":\""+stuSex+"\","
                    + "\"stuNation\":\""+stuNation+"\","
                    + "\"stuBirth\":\""+stuBirth+"\","
                    + "\"stuNative\":\""+stuNative+"\","
                    + "\"stuRegious\":\""+stuRegious+"\","
                    + "\"stuPolitical\":\""+stuPolitical+"\","
                    + "\"stuHealth\":\""+stuHealth+"\","
                    + "\"stuSpecial\":\""+stuSpecial+"\","
                    + "\"stuResidence\":\""+stuResidence+"\","
                    + "\"stuSchoolRoll\":\""+stuSchoolRoll+"\","
                    + "\"regiousSeat\":\""+regiousSeat+"\","
                    + "\"stuID\":\""+stuID+"\","
                    + "\"stuAddress\":\""+stuAddress+"\","
                    + "\"stuMobile\":\""+stuMobile+"\","
                    + "\"stuEmail\":\""+stuEmail+"\","
                    + "\"stuEntranceWay\":\""+stuEntranceWay+"\","
                    + "\"stuAlone\":\""+stuAlone+"\","
                    + "\"stuMartyr\":\""+stuMartyr+"\","
                    + "\"stuSingle\":\""+stuSingle+"\","
                    + "\"stuFarmer\":\""+stuFarmer+"\","
                    + "\"stuEnteranceDate\":\""+stuEnteranceDate+"\","
                    + "\"stuClass\":\""+stuClass+"\"},";
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            datastr=datastr.substring(0,datastr.length()-1);
            datastr=datastr+"]}";
        }
        out.flush();
        out.write(datastr);
        out.close();



    }

    public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
        this.doPost(request,response);
    }
}

JQuery-datatables一直警告错误。还有studentDAO:

    package dao;
import bean.Student;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * Created by Emitor on 16-12-7.
 */
public class StudentDAO {
    private Connection conn ;
    private Student student = null;

    public void initConnection() throws Exception {
        Class.forName("com.mysql.jdbc.Driver");
        conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mysystem","yupei","yupei");
    }
    public void closeConnection() throws Exception {
        conn.close();
    }

    public ResultSet getStudentByClassNumber(String classNumber)throws Exception{
        initConnection();
        String sql = "SELECT * FROM stu_info WHERE stu_class = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1,classNumber);
        ResultSet resultSet = ps.executeQuery();
        ps.close();
        closeConnection();
        return resultSet;
    }
    public ResultSet getStudentByStuNumber(String stuNumber)throws Exception{
        initConnection();
        String sql = "SELECT * FROM stu_info WHERE stu_number = ?";
        PreparedStatement ps = conn.prepareStatement(sql);
        ps.setString(1,stuNumber);
        ResultSet resultSet = ps.executeQuery();
        ps.close();
        closeConnection();
        return resultSet;
    }
}

我尝试使用firebug来查找问题,这似乎不是正确的Json响应。但我真的是Json的新人。所以我现在感到很困惑。请任何人帮我找到这个bug。非常感谢提前。 这是jsp:

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!-- test.html -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <link rel="stylesheet" type="text/css" href="./mysrc/project/reset.css">
    <link rel="stylesheet" type="text/css" href="./mysrc/project/jquery.dataTables.css">
    <title>this is a test</title>
    <script type="text/javascript" src='./mysrc/project/jquery-1.9.1/jquery.js'></script>
    <script type="text/javascript" src="./mysrc/project/jquery.dataTables.js"></script> 
<div>
    <input id="aButton" type="button" name="button" value="clickToShow" onclick="clickButton()" >
    <table id="myTestTable">
        <caption>this is a test</caption>
        <thead>
        <tr>
            <th>姓名</th>
            <th>户口所在地</th>
            <th>曾用名</th>
            <th>身份证号</th>
            <th>性别</th>
            <th>居住地</th>
            <th>民族</th>
            <th>出生日期</th>
            <th>电话号码</th>
            <th>Email</th>
            <th>籍贯</th>
            <th>入学方式</th>
            <th>宗教信仰</th>
            <th>是否留守儿童</th>
            <th>政治面貌</th>
            <th>是否烈士子女</th>
            <th>是否独生子女</th>
            <th>健康状况</th>
            <th>是否进城务工子女</th>
            <th>特长</th>
            <th>户口性质</th>
            <th>入学年月</th>
            <th>学籍状态</th>
            <th>班级</th>
        </tr>
        </thead>
        <tfoot>
        <tr>
            <th>姓名</th>
            <th>户口所在地</th>
            <th>曾用名</th>
            <th>身份证号</th>
            <th>性别</th>
            <th>居住地</th>
            <th>民族</th>
            <th>出生日期</th>
            <th>电话号码</th>
            <th>Email</th>
            <th>籍贯</th>
            <th>入学方式</th>
            <th>宗教信仰</th>
            <th>是否留守儿童</th>
            <th>政治面貌</th>
            <th>是否烈士子女</th>
            <th>是否独生子女</th>
            <th>健康状况</th>
            <th>是否进城务工子女</th>
            <th>特长</th>
            <th>户口性质</th>
            <th>入学年月</th>
            <th>学籍状态</th>
            <th>班级</th>
        </tr>
        </tfoot>
        <tbody>

        </tbody>

    </table>
</div>
<script type="text/javascript">
    function clickButton(){
        var table=$('#myTestTable').dataTable();
        if(table){
            table.fnDestroy();}
//        $.fn.dataTable.ext.errMode = 'throw';

        $('#myTestTable').dataTable( {
            "processing": true,
            "serverSide": true,
            "bInfo":false,//是否显示是否启用底边信息栏
            "sAjaxSource": "${pageContext.request.contextPath}../src/servlet.GetStuInfoServlet?classNumber=1401",
            'autoWidth': true,
            'pagingType': 'full_numbers',
            "language": {
                'lengthMenu': '每页显示 _MENU_ 记录',
                'zeroRecords': '没有数据 - 抱歉',
                'info': ' 第_PAGE_ 页/共 _PAGES_页',
                'infoEmpty': '没有符合条件的记录',
                'search': '查找',
                'infoFiltered': '(从  _MAX_ 条记录中过滤)',
                'paginate': { "first":  "首页 ", "last": "末页", "next": "下一页","previous": "上一页"}

            },
            "retrieve":true,
            "paging":   true,
            "ordering": true,
            "info":     true,
            "columns": [
                { "data": "stuNumber" },
                { "data": "stuName" },
                { "data": "stuNamed" },
                { "data": "stuSex" },
                { "data": "stuNation" },
                { "data": "stuBirth" },
                { "data": "stuNative" },
                { "data": "stuRegious" },
                { "data": "stuHealth" },
                { "data": "stuSpecial" },
                { "data": "stuResidence" },
                {"data": "stuSchoolRoll"},
                {"data": "regiousSeat"},
                {"data": "stuID"},
                {"data": "stuAddress"},
                {"data": "stuMobile"},
                {"data": "stuEmail"},
                {"data": "stuEntranceWay"},
                {"data": "stuAlone"},
                {"data": "stuMartyr"},
                {"data": "stuSingle"},
                {"data": "stuFarmer"},
                {"data": "stuEnteranceDate"},
                {"data": "stuClass"}
            ]
        } );
    }
</script>
</body>
</html>

2 个答案:

答案 0 :(得分:0)

好的,您在dataStr中使用的GetStuInfoServlet变量存在问题。

请参阅JSON响应以{ "data" : [ ] }开头,但由于您正在实施serverSide处理,因此您需要发送一个特定类型的响应,其中包含更多参数,如下所示:

{
  "draw": 2,
  "recordsTotal": 57,
  "recordsFiltered": 57,
  "data":[ [ "Your Student Details Data goes here.. "] ]
}

您可以阅读更多内容serverSide here

如果您使用的是Chrome,则可以在网络标签下查看该页面上的ajax响应。尝试相应地修改JSON响应。

答案 1 :(得分:-1)

 {
  "processing": true,
  "serverSide": true,
  "bInfo": false,
  "sAjaxSource": "${pageContext.request.contextPath}../src/servlet.GetStuInfoServlet?classNumber=1401",
  'autoWidth': true,
  'pagingType': 'full_numbers',
  "language": {
    'lengthMenu': '每页显示 _MENU_ 记录',
    'zeroRecords': '没有数据 - 抱歉',
    'info': ' 第_PAGE_ 页/共 _PAGES_页',
    'infoEmpty': '没有符合条件的记录',
    'search': '查找',
    'infoFiltered': '(从  _MAX_ 条记录中过滤)',
    'paginate': {
      "first": "首页 ",
      "last": "末页",
      "next": "下一页",
      "previous": "上一页"
    }
  },
  "retrieve": true,
  "paging": true,
  "ordering": true,
  "info": true,
  "columns": [
    {
      "data": "stuNumber"
    },
    {
      "data": "stuName"
    },
    {
      "data": "stuNamed"
    },
    {
      "data": "stuSex"
    },
    {
      "data": "stuNation"
    },
    {
      "data": "stuBirth"
    },
    {
      "data": "stuNative"
    },
    {
      "data": "stuRegious"
    },
    {
      "data": "stuHealth"
    },
    {
      "data": "stuSpecial"
    },
    {
      "data": "stuResidence"
    },
    {
      "data": "stuSchoolRoll"
    },
    {
      "data": "regiousSeat"
    },
    {
      "data": "stuID"
    },
    {
      "data": "stuAddress"
    },
    {
      "data": "stuMobile"
    },
    {
      "data": "stuEmail"
    },
    {
      "data": "stuEntranceWay"
    },
    {
      "data": "stuAlone"
    },
    {
      "data": "stuMartyr"
    },
    {
      "data": "stuSingle"
    },
    {
      "data": "stuFarmer"
    },
    {
      "data": "stuEnteranceDate"
    },
    {
      "data": "stuClass"
    }
  ]
}

更正Json格式,错误:注释不应包含在json中。