package com.bean; public class Example7_2_Bean { String[] columnName;// 存放列名 String[][] tableRecord = null;// 存放查询到的记录 int pageSize = 1; int totalPages = 1; int currentPage = 1; public Example7_2_Bean(){ } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } public int getTotalPages() { return totalPages; } public void setTotalPages(int totalPages) { this.totalPages = totalPages; } public int getCurrentPage() { return currentPage; } public void setCurrentPage(int currentPage) { this.currentPage = currentPage; } public String[] getColumnName() { return columnName; } public void setColumnName(String[] columnName) { this.columnName = columnName; } public String[][] getTableRecord() { return tableRecord; } public void setTableRecord(String[][] tableRecord) { this.tableRecord = tableRecord; } }
package com.servlet; import com.bean.Example7_2_Bean; import java.sql.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Example7_2_Servlet extends HttpServlet { /** * */ private static final long serialVersionUID = 1L; Connection con; Statement sql; ResultSet rs = null; @Override public void init(ServletConfig config) throws ServletException { // TODO Auto-generated method stub super.init(config); } public String handleString(String s) { try { byte b[] = s.getBytes("iso-8859-1"); s = new String(b); } catch (Exception ee) { } return s; } @Override public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub Example7_2_Bean resultBean = null;// 放在外面是为了判断这个是否为空, try { resultBean = (Example7_2_Bean) req.getAttribute("resultBean"); // 获取的是bean的对象 if (resultBean == null) {// 对获取到的javabean对象进行判断 resultBean = new Example7_2_Bean();// 若为空则创建javabean对象 req.setAttribute("resultBean", resultBean);// } } catch (Exception e) { // TODO: handle exception resultBean = new Example7_2_Bean();// 若为空则创建javabean对象 req.setAttribute("resultBean", resultBean);// } try { Class.forName("com.mysql.jdbc.Driver"); } catch (Exception e) { } String dataBase = req.getParameter("dataBase"); String tableName = req.getParameter("tableName"); String nu = req.getParameter("number"); String na = req.getParameter("name"); String mT = req.getParameter("madeTime"); String pr = req.getParameter("price"); // trim函数用于删除文本的空格 Float p = Float.parseFloat(pr); String condition = "insert into" + tableName + "values" + "(" + "'" + nu + "','" + na + "','" + mT + "'," + p + ")"; boolean boo = (nu.length() > 0); try { String uri = "jdbc:mysql://127.0.0.1/warehouse?" + "user=root&password=123456&characterEncoding=gb2312"; con = DriverManager.getConnection(uri); sql = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY); if (boo) sql.executeUpdate(condition); boolean m = rs.next(); if (m == true) { // 调用登入成功的方法: success(req, resp); } else { String backNews = "你输入的用户名不存在或密码不匹配"; // 调用失败的方法 fail(req, resp, backNews); } con.close(); // boolean m = rs.next(); // if (m == true) { // // 调用登入成功的方法: // success(req, resp, logname, password); // // RequestDispatcher dispatcher = req // .getRequestDispatcher("shanping/showRecord.jsp"); // dispatcher.forward(req, resp); // // } else { // String backNews = "你输入的用户名不存在或密码不匹配"; // // 调用失败的方法 // fail(req, resp, logname, backNews); // } } catch (SQLException e) { System.out.println(e); fail(req, resp, "添加记录失败" + e.toString()); } } public void success(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException { // TODO Auto-generated method stub Example7_2_Bean resultBean = null;// 放在外面是为了判断这个是否为空, try { resultBean = (Example7_2_Bean) req.getAttribute("resultBean"); // 获取的是bean的对象 if (resultBean == null) {// 对获取到的javabean对象进行判断 resultBean = new Example7_2_Bean();// 若为空则创建javabean对象 req.setAttribute("resultBean", resultBean);// } } catch (Exception e) { // TODO: handle exception resultBean = new Example7_2_Bean();// 若为空则创建javabean对象 req.setAttribute("resultBean", resultBean);// } rs = sql.executeQuery("select * from product"); 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);// 获得列名 } resultBean.setColumnName(columnName);// 更新javabean数据模型 rs.last();// 为BoolEAN类型 int rowNumber = rs.getRow();// 得到记录数 String[][] tableRecord = resultBean.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++; } resultBean.setTableRecord(tableRecord);// 更新javabean数据模型 con.close(); RequestDispatcher dispatcher = req .getRequestDispatcher("shanping/showRecord.jsp"); dispatcher.forward(req, resp); } } // public void success(HttpServletRequest req, HttpServletResponse resp, // String logname, String password) { // // TODO Auto-generated method stub // // Example7_2_Bean resultBean = null;// 放在外面是为了判断这个是否为空, // try { // resultBean = (Example7_2_Bean) req.getAttribute("resultBean");// // 获取的是bean的对象 // if (resultBean == null) {// 对获取到的javabean对象进行判断 // resultBean = new Example7_2_Bean();// 若为空则创建javabean对象 // req.setAttribute("resultBean", resultBean);// // } // // } catch (Exception e) { // // TODO: handle exception // resultBean = new Example7_2_Bean();// 若为空则创建javabean对象 // req.setAttribute("resultBean", resultBean);// // } // // // } // } public void fail(HttpServletRequest req, HttpServletResponse resp, String backNews) { // TODO Auto-generated method stub resp.setContentType("text/html;charset=gb2312"); try { PrintWriter out = resp.getWriter(); out.print("<html><body>"); out.print("<h2>" + backNews + "<h2>"); out.print("<a href='example7_2.jsp'>输入正确信息"); out.print("</html></body>"); } catch (IOException exp) { } } @Override public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { // TODO Auto-generated method stub doPost(req, resp); } }
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'example7_2.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> 查询warehouse数据库product表中 <form action="<%=request.getContextPath()%>/Example7_2_Servlet" method="post"> <br>产品号<input type="text" name="number" > <br>名称:<input type="text" name="name" > <br>生产日期:<input type="text" name="madeTime" > <br>价格:<input type="text" name="price" > <input type="submit" name="g" value="提交"> </form> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="gb2312"%> <jsp:useBean id="resultBean" class="com.bean.Example7_2_Bean" scope="request"></jsp:useBean> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'showRecord.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <br>当前显示的内容是: <jsp:setProperty property="pageSize" name="resultBean" param="pageSize"/> <jsp:setProperty property="currentPage" name="resultBean" param="currentPage"/> <table border="1"> <% String[] columnName = resultBean.getColumnName(); if(columnName!=null){ out.print("<tr>"); for(int i=0;i<columnName.length;i++){ out.print("<th>"+columnName[i]+"</th>"); } out.print("<tr>"); } String[][] record = resultBean.getTableRecord(); if(record==null){ out.print("没有记录"); return; } int totalRecord = record.length; out.println("全部记录数" + totalRecord);//全部记录数 int pageSize = resultBean.getPageSize();//每页显示的记录数 int totalPages = resultBean.getTotalPages(); if (totalRecord % pageSize == 0) totalPages = totalRecord / pageSize;//总页数 else totalPages = totalRecord / pageSize + 1; resultBean.setPageSize(pageSize); resultBean.setTotalPages(totalPages); if (totalPages >= 1) { if (resultBean.getCurrentPage() < 1) resultBean.setCurrentPage(resultBean.getTotalPages()); if (resultBean.getCurrentPage() > resultBean.getTotalPages()) resultBean.setCurrentPage(1); int index = (resultBean.getCurrentPage() - 1) * pageSize; int start=index;//查询位置移动到currentPage页起始位置 for (int i = index; i < pageSize+index; i++) { if(i==totalRecord) break; out.print("<tr>"); for(int j=0;j<columnName.length;j++){ out.print("<td>"+record[i][j]+"</td>");} } out.print("</tr>"); } %> </table> <br>每页最多显示<jsp:getProperty property="pageSize" name="resultBean" />条信息 <br>当前显示第 <font color=blue> <jsp:getProperty property="currentPage" name="resultBean" /> 页,共有<jsp:getProperty property="totalPages" name="resultBean" /></font>页。 <table> <tr> <td> <form action="" method="post"> <input type="hidden" name="currentPage" value="<%=resultBean.getCurrentPage() - 1 %>"> <input type="submit" name="g" value="上一页"> </form> </td> <td><form action="" method="post"> <input type="hidden" name="currentPage" value="<%=resultBean.getCurrentPage() + 1%>"> <input type="submit" name="g" value="下一页"> </form></td> </tr> <tr> <td><form action="" method="post"> 每页显示<input type="text" name="PageSize" value=1 size=3> 条记录<input type="submit" name="g" value="确定"> </form></td> <td><form action="" method="post"> 输入页码<input type="text" name="currentPage" size=2> <input type="submit" name="g" value="提交"> </form></td> </tr> </table> </body> </html>
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>Example7_2_Servlet</servlet-name> <servlet-class>com.servlet.Example7_2_Servlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>Example7_2_Servlet</servlet-name> <url-pattern>/Example7_2_Servlet</url-pattern> </servlet-mapping> </web-app>
经过长时间的检查。发现最终还是代码有问题,一定要仔细代码, 从最基础, 最没有可能错误的地方开始查找错误。