我想在前端使用onload事件触发Servlet,然后通过Servlet中的SQL查询语句获取结果集,将结果集存储在JavaBean中,并在转发后将其显示在首页上>
我使用了Tomcat版本9.0,MySql 8.0和最新版本的Eclipse
< html > <head > </head>
<body>
< head >
<script type="text/javascript ">
function f() {
$.ajax({
url: "DCommodityServlet ",
//servlet文件的名称
type: "post ",
success: function(e) {
alert("servlet调用成功!");
}
});
} < /script>
</head > <body onload = "f()" >
request.setCharacterEncoding("utf - 8 ");
String user = "root ";
String password = "123456 ";
HttpSession session = request.getSession(true);
Connection con = null;
DCommodity DCommodityBean = null;
DCommodityBean = new DCommodity();
session.setAttribute("DCommodityBean ", DCommodityBean);
String uri = "jdbc: mysql: //localhost:3306/test?useSSL=false&serverTimezone=UTC";
try {
con = DriverManager.getConnection(uri, user, password);
Statement sql = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
ResultSet rs = sql.executeQuery("SELECT * FROM commodity ");
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();
String[] columnName = new String[columnCount];
for (int i = 0; i < columnName.length; i++) {
columnName[i] = metaData.getColumnName(i + 1);
}
DCommodityBean.setColumnName(columnName);
rs.last();
int rowNumber = rs.getRow();
String[][] tableRecord = DCommodityBean.getTableRecord();
tableRecord = new String[rowNumber][columnCount];
rs.beforeFirst();
int i = 0;
while (rs.next()) {
for (int k = 0; k < columnCount; k++) tableRecord[i][k] = rs.getString(k + 1);
i++;
}
DCommodityBean.setTableRecord(tableRecord);
con.close();
request.getRequestDispatcher("DCommodity.jsp").forward(request, response);
} catch(SQLException e) {
System.out.println(e);
} < /script>
</body > </html>/
期望:我希望在调用Servlet之后从数据库查询并存储在javabeans中以在界面中显示的结果集 实际结果:我得到一个没有结果的JavaBean