package demo; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ArrayList; import java.util.List; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class Queryalldata */ @WebServlet("/queryalldata.jsp") public class Queryalldata extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public Queryalldata() { super(); // TODO Auto-generated constructor stub } /** * @see HttpServlet#service(HttpServletRequest request, HttpServletResponse response) */ protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //查询所有数据 //设置数据库连接参数 String url="jdbc:mysql://localhost:3306/库名?serverTimezone=UTC"; String user="用户名"; String password="密码"; //加载数据库驱动 try { Class.forName("com.mysql.jdbc.Driver");//加载数据库的JDBC驱动程序 } catch (ClassNotFoundException e) { e.printStackTrace(); } List<Customer> list = new ArrayList<Customer>();//初始化一个Customer线性列表 try(Connection connection=DriverManager.getConnection(url, user, password)){//连接数据库 Statement statement = connection.createStatement(); String sql="SELECT*FROM customers";//查询所有数据的sql语句,customers为表名 ResultSet rs=statement.executeQuery(sql); //遍历数据库所有数据,并添加到列表list中 while(rs.next()) { Customer customer = new Customer(); customer.setCustomerID(rs.getInt("CustomerID")); customer.setCustomerName(rs.getString("CustomerName")); customer.setContactName(rs.getString("ContactName")); customer.setAddress(rs.getString("Address")); customer.setCity(rs.getString("City")); customer.setPostalCode(rs.getString("PostalCode")); customer.setCountry(rs.getString("Country")); list.add(customer); } rs.close(); statement.close(); }catch(SQLException e) { e.printStackTrace(); } String msg =(String) request.getAttribute("msg"); if(msg!=null || msg !=" ") request.setAttribute("msg", msg); //将有数据的列表传递到显示记录所有界面 request.setAttribute("customers", list); request.getRequestDispatcher("all.jsp").forward(request, response); } }