/*
* 通过mysql来查询表单数据并显示
*/
package servlet;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class viewTeams extends HttpServlet{
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection cn = null;
PreparedStatement pst = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");//加载MySQL驱动程序
//建立与数据库的连接
String url = "jdbc:mysql://localhost:3306/training";
String user = "root";
String password = "jakeyouxiang";
cn = DriverManager.getConnection(url,user,password);
pst = cn.prepareStatement("select * from team"); //创建PreparedStatement对象
rs = pst.executeQuery(); //执行查询
// 通过response向客户端应答
response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>显示小组</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1 align=center>显示</h1>");
out.println("<table border='1' align='center'>");
out.println("<tr><th>编号</th><th>组名</th><th>口号</th><th>组长</th></tr>");
//把结果集里的数据在表格里显示出来
while(rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getString("id") + "</td>");
out.println("<td>" + rs.getString("name") + "</td>");
out.println("<td>" + rs.getString("slogan") + "</td>");
out.println("<td>" + rs.getString("leader") + "</td>");
out.println("</tr>");
}
out.println("</table>");
out.println("<p><a href='../addTeam.html'>增加小组</a>");
out.println("<a href='../index.html'>返回首页</a>");
out.println("</body>");
out.println("</html>");
} catch (Exception e) {
e.printStackTrace();
// 通过response向客户端应答,显示增加失败
response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>显示小组失败</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1 align=center>显示小组失败</h1>");
out.println("<p><a href='../addTeam.html'>增加小组</a>");
out.println("<a href='viewTeams'>显示小组</a>");
out.println("<a href='../index.html'>返回首页</a>");
out.println("</body>");
out.println("</html>");
}
finally {
try {
rs.close();
pst.close();
cn.close();
}
catch(Exception e) {
e.printStackTrace();
}
}
}
}