JSP--TOMCAT-MYSQL web页面查询

时间:2023-11-16 16:58:50

queryStudent.jsp代码如下

<%@ page language="java" contentType="text/html; charset=gb2312"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>queryStudentinfo</title>
</head>
<body>
<table style="border-right:#89d4f8 1px solid;
border-top:#89d4f8 1px solid;
border-left:#89d4f8 1px solid"
cellSpacing= cellpadding= align=center bgColor=#ffffff border=>
<tbody>
<tr>
<td height=>&nbsp;&nbsp;添加学生信息</td>
</tr>
<tr>
<td height= bgColor=#89d4f8> </td>
</tr>
</tbody>
</table>
<!-- 点击按钮查询 -->
<form name=messages method="post" action="after_queryStudent.jsp">
<table width="" align="center" border="">
<tr>
<td width=""></td>
<td><input type="submit" value="查询所有学生信息"></td>
</tr>
</table> </form>
</body>
</html>

after_queryStudent.jsp页面代码

<%@ page language="java"
import="java.util.*"
import="com.mysql.jdbc.Driver"
import="java.sql.*"
contentType="text/html;charset=gb2312"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>after_queryStudent</title>
</head>
<body>
<%
Connection conn;
Statement stat;
//设置连接的url,其中student是数据库名称
String url="jdbc:mysql://localhost:3306/student";
//我使用的是免安装版的mysql,用户:root,密码:zhangweijie
String userName="root";
String password="zhangweijie";
try{
//注册JDBC驱动程序
Class.forName("com.mysql.jdbc.Driver");
}
catch(ClassNotFoundException ex)
{
out.println("找不到驱动程序!");
}
//打开数据库连接
conn=DriverManager.getConnection(url,userName,password);
try{
stat=conn.createStatement();
//如果存在同名的数据表,先进行删除
ResultSet result=stat.executeQuery("select * from Student_Info;");
//绘制一张表格,用来显示数据
out.println("<table border>");
out.println("<tr><td colspan=3 align=center>学生信息</td></tr>");
out.println("<tr>");
out.println("<td width=150>学号 </td>");
out.println("<td width=150>姓名 </td>");
out.println("<td width=150>联系电话 </td>");
out.println("</tr>");
while(result.next()){
//读取查询结果,并显示
out.println("<tr>");
out.println("<td>"+result.getInt(1)+"</td>");
out.println("<td>"+result.getString(2)+"</td>");
out.println("<td>"+result.getString(3)+"</td>");
out.println("</tr>"); } }
catch(SQLException ex)
{
out.println("数据表操作失败!");
}
finally{ conn.close();
}
%>
</body>
</html>