java- 综合实例-增删查改查,删除多项,分页
Posted Archibald Witwicky
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java- 综合实例-增删查改查,删除多项,分页相关的知识,希望对你有一定的参考价值。
重点内容:分页、令牌机制(重定向下防止重复提交)、使用c3p0连接数据库(以及数据库连接类)
项目结构:
类:
项目展示:
数据库:
/* SQLyog Ultimate v12.09 (64 bit) mysql - 5.5.53 : Database - phone_store ********************************************************************* */ /*!40101 SET NAMES utf8 */; /*!40101 SET SQL_MODE=\'\'*/; /*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */; /*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */; /*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE=\'NO_AUTO_VALUE_ON_ZERO\' */; /*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */; CREATE DATABASE /*!32312 IF NOT EXISTS*/`phone_store` /*!40100 DEFAULT CHARACTER SET utf8 */; USE `phone_store`; /*Table structure for table `phone` */ DROP TABLE IF EXISTS `phone`; CREATE TABLE `phone` ( `id` varchar(255) NOT NULL COMMENT \'主键\', `name` varchar(255) NOT NULL COMMENT \'名称\', `price` double NOT NULL COMMENT \'价格\', `mark` varchar(255) DEFAULT NULL COMMENT \'简介\' ) ENGINE=InnoDB DEFAULT CHARSET=utf8; /*Data for the table `phone` */ insert into `phone`(`id`,`name`,`price`,`mark`) values (\'9DE38AA976B34441B1511C0266B07F00\',\'phone555555\',2323.43,\'1phone1mark顶顶顶顶\'),(\'E0923B7C3CC1434B8E2BF55EB47195BE\',\'phone555555\',2323.43,\'2阿达是的发送到发送的\'),(\'13BAEC11CB0D4789BC935B47C396A81D\',\'张三\',234.322222222,\'3阿达是的发送到发送的顶顶顶\'),(\'178B12C84D6E4C1583BC71735F3683FC\',\'phone555555\',234.32,\'4phone1mark顶顶顶顶\'),(\'5DC9D361571B4B9EAD545B57819B7BE0\',\'phone555555\',21341,\'5小米手机\'),(\'9E0B9164FE564A51BC61141017792BF3\',\'phone555555\',21341,\'6小米手机\'),(\'A8936D9946B04FBFA543463F35B0A587\',\'phone555555\',2323.43,\'7阿达是的发送到发送的\'),(\'C623F1FB4A2E4D7FBBF6109BF1DE0471\',\'张三\',2323.43,\'8阿达是的发送到发送的\'),(\'6184E8770C5B471E91EDDBE6B2632DE4\',\'phone555555\',2323.43,\'9phone1mark顶顶顶顶\'),(\'9DE38AA976B34441B1511C0266B07F00\',\'phone555555\',2323.43,\'1phone1mark顶顶顶顶\'),(\'E0923B7C3CC1434B8E2BF55EB47195BE\',\'phone555555\',2323.43,\'2阿达是的发送到发送的\'),(\'13BAEC11CB0D4789BC935B47C396A81D\',\'张三\',234.322222222,\'3阿达是的发送到发送的顶顶顶\'),(\'178B12C84D6E4C1583BC71735F3683FC\',\'phone555555\',234.32,\'4phone1mark顶顶顶顶\'),(\'5DC9D361571B4B9EAD545B57819B7BE0\',\'phone555555\',21341,\'5小米手机\'),(\'9E0B9164FE564A51BC61141017792BF3\',\'phone555555\',21341,\'6小米手机\'),(\'A8936D9946B04FBFA543463F35B0A587\',\'phone555555\',2323.43,\'7阿达是的发送到发送的\'),(\'C623F1FB4A2E4D7FBBF6109BF1DE0471\',\'张三\',2323.43,\'8阿达是的发送到发送的\'),(\'6184E8770C5B471E91EDDBE6B2632DE4\',\'phone555555\',2323.43,\'9phone1mark顶顶顶顶\'); /*!40101 SET SQL_MODE=@OLD_SQL_MODE */; /*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */; /*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */; /*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
src/dao/AddDataDao.java:
package com.gordon.dao; import java.sql.SQLException; import org.apache.commons.dbutils.QueryRunner; import com.gordon.domain.Phone; import com.gordon.utils.DataSourceUtils; public class AddDataDao { public void addData(Phone phone) throws SQLException { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "insert into phone (id, name, price, mark) values (?,?,?,?)"; qr.update(sql, phone.getId(), phone.getName(), phone.getPrice(), phone.getMark()); } }
src/dao/DeleteDataDao.java:
package com.gordon.dao; import java.sql.SQLException; import org.apache.commons.dbutils.QueryRunner; import com.gordon.utils.DataSourceUtils; public class DeleteDataDao { /** * 根据id删除数据 * @param id * @throws SQLException */ public void deleteDataById(String id) throws SQLException { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "delete from phone where id = ?"; qr.update(sql, id); } }
src/dao/GetDataDao.java:
package com.gordon.dao; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.apache.commons.dbutils.QueryRunner; import org.apache.commons.dbutils.handlers.BeanHandler; import org.apache.commons.dbutils.handlers.BeanListHandler; import org.apache.commons.dbutils.handlers.ScalarHandler; import com.gordon.domain.Phone; import com.gordon.utils.DataSourceUtils; public class GetDataDao { /** * 获取所有数据 * * @return * @throws SQLException */ public List<Phone> getAllData() throws SQLException { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "select * from phone"; return qr.query(sql, new BeanListHandler<Phone>(Phone.class)); } /** * 根据id获取数据 * * @param id * @return * @throws SQLException */ public Phone getDataById(String id) throws SQLException { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "select * from phone where id = ?"; return qr.query(sql, new BeanHandler<Phone>(Phone.class), id); } /** * 根据关键词查询信息 * * @param category * @param keyword * @return * @throws SQLException */ public List<Phone> getDataByKeyword(String category, String keyword) throws SQLException { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "select * from phone where 1 = 1 "; ArrayList<String> arrayList = new ArrayList<>(); if (category != null && category.trim().length() > 0) { sql += " and mark like ? "; arrayList.add("%" + category + "%"); } if (keyword != null && keyword.trim().length() > 0) { sql += " and mark like ? "; arrayList.add("%" + keyword + "%"); } return qr.query(sql, new BeanListHandler<Phone>(Phone.class), arrayList.toArray()); } /** * 分页查询 * * @param start * @param page_size * @return * @throws SQLException */ public List<Phone> getDataByLimit(int start, int page_size) throws SQLException { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "select * from phone limit ?, ?"; return qr.query(sql, new BeanListHandler<Phone>(Phone.class), start, page_size); } /** * 获取查询数据总条数 * * @return * @throws SQLException * @throws NumberFormatException */ public int getDataTotalCount() throws NumberFormatException, SQLException { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "select count(*) from phone"; return Integer.valueOf(qr.query(sql, new ScalarHandler(1)).toString()); } }
src/dao/UpdateDataDao.java:
package com.gordon.dao; import java.sql.SQLException; import org.apache.commons.dbutils.QueryRunner; import com.gordon.domain.Phone; import com.gordon.utils.DataSourceUtils; public class UpdateDataDao { /** * 根据id更新数据 * * @param phone * @throws SQLException */ public void updateDataById(Phone phone) throws SQLException { QueryRunner qr = new QueryRunner(DataSourceUtils.getDataSource()); String sql = "update phone set name = ?, price = ?, mark = ? where id = ?"; qr.update(sql, phone.getName(), phone.getPrice(), phone.getMark(), phone.getId()); } }
---------------------------------------------------------------------
src/domain/Page.java:
package com.gordon.domain; import java.util.List; public class Page<T> { private List<T> list = null; // 存储每一页的数据 private int curr_page = 1; // 当前页数 private int page_size = 2; // 每一页大小 private int total_page = 0; // 总页数 private int total_count = 0; // 总记录条数 // 显示页码时,当前页码前后要显示的页数。 // 如,show_page=2,且当前页是第5页,则前面显示3,4 后面显示6,7其余页不显示。 private int show_page = 3; public int getShow_page() { return show_page; } public void setShow_page(int show_page) { this.show_page = show_page; } public List<T> getList() { return list; } public void setList(List<T> list) { this.list = list; } public int getCurr_page() { return curr_page; } public void setCurr_page(int curr_page) { this.curr_page = curr_page; } public int getPage_size() { return page_size; } public void setPage_size(int page_size) { this.page_size = page_size; } public int getTotal_page() { this.total_page = (int) Math.ceil((total_count * 1.0) / page_size); return total_page; } public void setTotal_page(int total_page) { this.total_page = total_page; } public int getTotal_count() { return total_count; } public void setTotal_count(int total_count) { this.total_count = total_count; } }
src/domain/Phone.java:
package com.gordon.domain; public class Phone { private String id; private String name; private Double price; private String mark; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Double getPrice() { return price; } public void setPrice(Double price) { this.price = price; } public String getMark() { return mark; } public void setMark(String mark) { this.mark = mark; } }
---------------------------------------------------------------------
src/service/AddDataService.java:
package com.gordon.service; import java.sql.SQLException; import com.gordon.dao.AddDataDao; import com.gordon.domain.Phone; public class AddDataService { /** * 添加一条数据 * @param phone * @throws SQLException */ public void addData(Phone phone) throws SQLException { new AddDataDao().addData(phone); } }
src/service/DeleteDataService.java:
package com.gordon.service; import java.sql.SQLException; import com.gordon.dao.DeleteDataDao; public class DeleteDataService { /** * 根据id删除数据 * * @param id * @throws SQLException */ public void deleteDataById(String id) throws SQLException { new DeleteDataDao().deleteDataById(id); } }
src/service/GetDataService.java:
package com.gordon.service; import java.sql.SQLException; import java.util.List; import com.gordon.dao.GetDataDao; import com.gordon.domain.Phone; public class GetDataService { /** * 获取所有数据 * * @return * @throws SQLException */ public List<Phone> getAllData() throws SQLException { return new GetDataDao().getAllData(); } /** * 根据id获取数据 * * @param id * @return * @throws SQLException */ public Phone getDataById(String id) throws SQLException { return new GetDataDao().getDataById(id); } /** * 根据关键词查询数据 * * @param category * @param keyword * @return * @throws SQLException */ public List<Phone> getDataByKeyword(String category, String keyword) throws SQLException { return new GetDataDao().getDataByKeyword(category, keyword); } /** * 分页查询 * * @param start * @param page_size * @return * @throws SQLException */ public List<Phone> getDataByLimit(int start, int page_size) throws SQLException { return new GetDataDao().getDataByLimit(start, page_size); } /** * 获取查询数据总条数 * @return * @throws SQLException * @throws NumberFormatException */ public int getDataTotalCount() throws NumberFormatException, SQLException { return new GetDataDao().getDataTotalCount(); } }
src/service/UpdateDataService.java:
package com.gordon.service; import java.sql.SQLException; import com.gordon.dao.UpdateDataDao; import com.gordon.domain.Phone; public class UpdateDataService { /** * 更新数据 * @param phone * @throws SQLException */ public void updateDataById(Phone phone) throws SQLException { new UpdateDataDao().updateDataById(phone); } }
---------------------------------------------------------------------
src/utils/DataSourceUtils.java:
package com.gordon.utils; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import javax.sql.DataSource; import com.mchange.v2.c3p0.ComboPooledDataSource; public class DataSourceUtils { private static ComboPooledDataSource ds=new ComboPooledDataSource(); /** * 获取数据源 * @return 连接池 */ public static DataSource getDataSource(){ return ds; } /** * 获取连接 * @return 连接 * @throws SQLException */ public static Connection getConnection() throws SQLException{ return ds.getConnection(); } /** * 释放资源 * * @param conn * 连接 * @param st * 语句执行者 * @param rs * 结果集 */ public static void closeResource(Connection conn, Statement st, ResultSet rs) { closeResultSet(rs); closeStatement(st); closeConn(conn); } /** * 释放连接 * * @param conn * 连接 */ public static void closeConn(Connection conn) { if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } conn = null; } } /** * 释放语句执行者 * * @param st * 语句执行者 */ public static void closeStatement(Statement st) { if (st != null) { try { st.close(); } catch (SQLException e) { e.printStackTrace(); } st = null; } } /** * 释放结果集 * * @param rs * 结果集 */ public static void closeResultSet(ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } rs = null; } } }
src/utils/RandomNumber.java:
package com.gordon.utils; import java.util.UUID; public class RandomNumber { public static String getRandomId() { return UUID.randomUUID().toString().replace("-", "").toUpperCase(); } }
---------------------------------------------------------------------
src/web.servlet/AddDataServlet.java:
package com.gordon.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils; import com.gordon.domain.Phone; import com.gordon.service.AddDataService; import com.gordon.utils.RandomNumber; /** * 添加用户数据 */ @WebServlet("/addData") public class AddDataServlet extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#HttpServlet() */ public AddDataServlet() { super(); } /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse * response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=utf-8;"); // 判断是否为重复提交 String r_token = request.getParameter("r_token"); String s_token = (String) request.getSession().getAttribute("s_token"); //清除s_token,以便于重新生成。 request.getSession().removeAttribute("s_token"); // 判断session中是否存在Token,并且是否与客户端Token相同,不同则不是同一次请求。 if(s_token == null || !s_token.equals(r_token)) { request.setAttribute("msg", "重复提交!"); request.getRequestDispatcher("/msg.jsp").forward(request, response); return; } try { Phone phone = new Phone(); BeanUtils.populate(phone, request.getParameterMap()); BeanUtils.setProperty(phone, "id", RandomNumber.getRandomId()); new AddDataService().addData(phone); } catch (Exception e) { e.printStackTrace(); } /** * 使用请求转发,会导致数据重复提交。 * 两种解决方法: * 1.使用重定向 sendRedirect()。但是不能再同意请求内传递数据,最好使用令牌技术. * 2.使用令牌技术 */ request.getRequestDispatcher("/getAllData").forward(request, response); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
src/web.servlet/DeleteDataByIdServlet.java:
package com.gordon.web.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.gordon.service.DeleteDataService; /** * 根据id删除数据 */ @WebServlet("/deleteDataById") public class DeleteDataByIdServlet extends HttpServlet { private static final long serialVersionUID = 1L; public DeleteDataByIdServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String id = request.getParameter("id"); try { new DeleteDataService().deleteDataById(id); } catch (SQLException e) { e.printStackTrace(); } response.sendRedirect(request.getContextPath() + "/getAllData"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
src/web.servlet/DeleteMultipleDataByIdServlet.java:
package com.gordon.web.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.gordon.service.DeleteDataService; /** * 删除多项数据 */ @WebServlet("/deleteMultipleDataByIds") public class DeleteMultipleDataByIdsServlet extends HttpServlet { private static final long serialVersionUID = 1L; public DeleteMultipleDataByIdsServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String[] ids = request.getParameterValues("ids"); try { for (int i = 0; i < ids.length; i++) { new DeleteDataService().deleteDataById(ids[i]); } } catch (SQLException e) { e.printStackTrace(); } response.sendRedirect(request.getContextPath() + "/getAllData"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
src/web.servlet/GetAllDataServlet.java:
package com.gordon.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.gordon.domain.Page; import com.gordon.domain.Phone; import com.gordon.service.GetDataService; /** * 获取所有数据 */ @WebServlet("/getAllData") public class GetAllDataServlet extends HttpServlet { private static final long serialVersionUID = 1L; public GetAllDataServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); Page<Phone> page_phone = new Page<Phone>(); try { // 当前页,不存在默认为 1 int curr_page = (request.getParameter("page") == null) ? 1 : Integer.valueOf(request.getParameter("page")); page_phone.setCurr_page(curr_page); // 总条数 page_phone.setTotal_count(new GetDataService().getDataTotalCount()); // 开始位置&每页大小 int start = (Integer.valueOf(curr_page) - 1) * page_phone.getPage_size(); int pagesize = page_phone.getPage_size(); // 设置获取的结果集 page_phone.setList(new GetDataService().getDataByLimit(start, pagesize)); } catch (Exception e) { e.printStackTrace(); } // 向域中传递Page&list对象 request.setAttribute("list", page_phone.getList()); // 数据集 request.setAttribute("page", page_phone); //page对象 request.getRequestDispatcher("/show_data.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
src/web.servlet/GetDataByIdServlet.java:
package com.gordon.web.servlet; import java.io.IOException; import java.sql.SQLException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.gordon.domain.Phone; import com.gordon.service.GetDataService; /** * 根据id获取数据,并转发到修改数据页面 */ @WebServlet("/getDataById") public class GetDataByIdServlet extends HttpServlet { private static final long serialVersionUID = 1L; public GetDataByIdServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String id = request.getParameter("id"); Phone phone = null; try { phone = new GetDataService().getDataById(id); } catch (SQLException e) { e.printStackTrace(); } request.setAttribute("phone", phone); request.getRequestDispatcher("/update_data.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
src/web.servlet/GetDataByKeyword.java:
package com.gordon.web.servlet; import java.io.IOException; import java.sql.SQLException; 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; import com.gordon.domain.Phone; import com.gordon.service.GetDataService; /** * 根据关键字查询数据库 */ @WebServlet("/getDataByKeyword") public class GetDataByKeywordServlet extends HttpServlet { private static final long serialVersionUID = 1L; public GetDataByKeywordServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); String category = request.getParameter("category"); String keyword = request.getParameter("keyword"); List<Phone> plist = null; try { plist = new GetDataService().getDataByKeyword(category, keyword); } catch (SQLException e) { e.printStackTrace(); } request.setAttribute("list", plist); request.getRequestDispatcher("/show_data.jsp").forward(request, response); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
src/web.servlet/UpdateDataByIdServlet.java:
package com.gordon.web.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.BeanUtils; import com.gordon.domain.Phone; import com.gordon.service.UpdateDataService; /** * 修改数据 */ @WebServlet("/updateDataById") public class UpdateDataByIdServlet extends HttpServlet { private static final long serialVersionUID = 1L; public UpdateDataByIdServlet() { super(); } protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); try { Phone phone = new Phone(); BeanUtils.populate(phone, request.getParameterMap()); new UpdateDataService().updateDataById(phone); } catch (Exception e) { e.printStackTrace(); } response.sendRedirect(request.getContextPath() + "/getAllData"); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
---------------------------------------------------------------------
c3po-config.xml
<c3p0-config> <!-- 默认配置,如果没有指定则使用这个配置 --> <default-config> <!-- 基本配置 --> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/phone_store</property> <property name="user">root</property> <property name="password">root</property> <!--扩展配置--> <property name="checkoutTimeout">30000</property> <property name="idleConnectionTestPeriod">30</property> <property name="initialPoolSize">10</property> <property name="maxIdleTime">30</property> <property name="maxPoolSize">100</property> <property name="minPoolSize">10</property> <property name="maxStatements">200</property> </default-config> <!-- 命名的配置 --> <named-config name="itcast"> <property name="driverClass">com.mysql.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://127.0.0.1:3306/xxxx</property> <property name="user">root</property> <property name="password">1234</property> <!-- 如果池中数据连接不够时一次增长多少个 --> <property name="acquireIncrement">5</property> <property name="initialPoolSize">20</property> <property name="minPoolSize">10</property> <property name="maxPoolSize">40</property> <property name="maxStatements">20</property> <property name="maxStatementsPerConnection">5</property> </named-config> </c3p0-config>
---------------------------------------------------------------------
add_data.jsp
<%@page import="com.gordon.utils.RandomNumber"%> <%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <% String randomToken = RandomNumber.getRandomId(); request.getSession().setAttribute("s_token", randomToken); %> <form action="${ pageContext.request.contextPath }/addData" method="post"> <input type="hidden" name="r_token" value="<%= randomToken %>"> <table border="1" align="center"> <tr> <td>名称:</td> <td><input type="text" name="name"></td> </tr> <tr> <td>价格:</td> <td><input type="text" name="price"></td> </tr> <tr> <td>简介:</td> <td><input type="text" name="mark"></td> </tr> <tr> <td><input type="submit" value="提交"></td> </tr> </table> </form> </body> </html>
index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <a href="${ pageContext.request.contextPath }/getAllData">显示所有数据</a><br/> <a href="${ pageContext.request.contextPath }/add_data.jsp">添加数据</a><br/> </body> </html>
msg.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> ${ msg } </body> </html>
show_data.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="${ pageContext.request.contextPath }/getDataByKeyword" method="post"> <table border="1" align="center"> <tr> <td colspan="5">分类查询:<input type="text" name="category"> 关键字查询:<input type="text" name="keyword"></td> <td><input type="submit" value="查询"></td> </tr> </table> </form> <br> <form id="deleteMultipleForm" action="${ pageContext.request.contextPath }/deleteMultipleDataByIds" method="post"> <table border="1" align="center"> <tr> <td><input type="checkbox" onclick="allCheck(this)"></td> <td>ID</td> <td>名称</td> <td>价格</td> <td>简介</td> <td>操作</td> </tr> <c:forEach items="${ list }" var="p"> <tr> <td><input type="checkbox" name="ids" value="${ p.id }"></td> <td>${ p.id }</td> <td>${ p.name }</td> <td>${ p.price }</td> <td>${ p.mark }</td> <td><a href="${ pageContext.request.contextPath }/getDataById?id=${ p.id }">修改</a> | <a href="javascript:void(0);" onclick="deleteData(\'${ p.id }\')">删除</a></td> </tr> </c:forEach> <tr> <td colspan="6"><input type="button" onclick="deleteMultiple()" value="删除"></td> </tr> </table> </form> <br> <table border="1" align="center"> <tr> <td colspan="5"> <c:choose> <c:when test="${ empty page.list }"> [首页][下一页][上一页][尾页] </c:when> <c:otherwise> <!-- 首页&上一页 --> <c:choose> <c:when test="${ page.curr_page == 1 }"> [首页] [上一页] </c:when> <c:otherwise> <!-- 首页 --> <a href="${ pageContext.request.contextPath }/getAllData">[首页]</a> <!-- 上一页 --> <c:choose> <c:when test="${ (page.curr_page - 1) <= 0 }"> <a href="${ pageContext.request.contextPath }/getAllData">[上一页]</a> </c:when> <c:otherwise> <a href="${ pageContext.request.contextPath }/getAllData?page=${ page.curr_page - 1 }">[上一页]</a> </c:otherwise> </c:choose> </c:otherwise> </c:choose> <!-- 显示页码 --> <c:set var="showpage" value="${ page.show_page }"></c:set> <!-- 计算起始位置 --> <c:choose> <c:when test="${ page.curr_page - showpage > 0}"> <c:set var="start" value="${ page.curr_page - showpage }"></c:set> </c:when> <c:otherwise> <c:set var="start" value="1"></c:set> </c:otherwise> </c:choose> <!-- 计算结束位置 --> <c:choose> <c:when test="${ page.curr_page + showpage <= page.total_page }"> <c:set var="end" value="${ page.curr_page + showpage }"></c:set> </c:when> <c:otherwise> <c:set var="end" value="${ page.total_page }"></c:set> </c:otherwise> </c:choose> <!-- 循环显示页码 --> <c:forEach begin="${ start }" end="${ end }" var="i"> <c:choose> <c:when test="${ page.curr_page == i }"> ${ i } </c:when> <c:otherwise> <a href="${ pageContext.request.contextPath }/getAllData?page=${ i }">${ i }</a> </c:otherwise> </c:choose> </c:forEach> <!-- 下一页&尾页 --> <c:choose> <c:when test="${ page.curr_page == page.total_page }"> [下一页] [尾页] </c:when> <c:otherwise> <!-- 下一页 --> <c:choose> <c:when test="${ (page.curr_page + 1) > page.total_page }"> <a href="${ pageContext.request.contextPath }/getAllData?page=${ page.curr_page }">[下一页] </a> </c:when> <c:otherwise> <a href="${ pageContext.request.contextPath }/getAllData?page=${ page.curr_page + 1 }">[下一页]</a> </c:otherwise> </c:choose> <!-- 尾页 --> <a href="${ pageContext.request.contextPath }/getAllData?page=${ page.total_page }">[尾页]</a> </c:otherwise> </c:choose> <!-- 信息 --> 第${ page.curr_page }页 / 共${ page.total_page }页 </c:otherwise> </c:choose> </td> </tr> </table> </body> <script type="text/javascript"> //根据id删除数据 function deleteData(id) { if (confirm("确定删除吗?")) { window.location.href = "${ pageContext.request.contextPath }/deleteDataById?id=" + id; } } //全选/全不选 function allCheck(this_obj) { var arrs = document.getElementsByName("ids"); for (var i = 0; i < arrs.length; i++) { arrs[i].checked = this_obj.checked; } } //多选删除时,判断是否选中 function deleteMultiple() { var flag = false; var arrs = document.getElementsByName("ids"); for (var i = 0; i < arrs.length; i++) { if (arrs[i].checked) { flag = true; break; } } if (flag) { if (confirm("确定删除选中项目?")) { document.getElementById("deleteMultipleForm").submit(); } } else { alert("请选择删除项目!"); } } </script> </html>
update_data.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title> </head> <body> <form action="${ pageContext.request.contextPath }/updateDataById" method="post"> <input type="hidden" name="id" value="${ phone.id }"> <table border="1" align="center"> <tr> <td>名称:</td> <td><input type="text" name="name" value="${ phone.name }"></td> </tr> <tr> <td>价格:</td> <td><input type="text" name="price" value="${ phone.price }"></td> </tr> <tr> <td>简介:</td> <td><input type="text" name="mark" value="${ phone.mark }"></td> </tr> <tr> <td><input type="submit" value="修改"></td> </tr> </table> </form> </body> </html>
以上是关于java- 综合实例-增删查改查,删除多项,分页的主要内容,如果未能解决你的问题,请参考以下文章