当前位置: 首页 > news >正文

java web 练习 简单增删改查,多选删除,包含完整的sql文件demo。生成简单验证码前端是jsp

目录结构

demo1
lib/
│   ├── javax.annotation.jar
│   ├── javax.ejb.jar
│   ├── javax.jms.jar
│   ├── javax.persistence.jar
│   ├── javax.resource.jar
│   ├── javax.servlet.jar
│   ├── javax.servlet.jsp.jar
│   └── javax.transaction.jar
src/
│   ├── com/
│   │   └── demo/
│   │       ├── dao/
│   │       │   ├── impl/
│   │       │   │   └── CustomerDaoImpl.java  # CustomerDaoImpl数据访问接口
│   │       │   └── CustomerDao.java  # CustomerDao数据访问接口
│   │       ├── entity/
│   │       │   ├── Customer.java
│   │       │   ├── PageBean.java
│   │       │   └── User.java
│   │       ├── service/
│   │       │   ├── impl/
│   │       │   │   └── CustomerServiceImpl.java  # CustomerService业务实现
│   │       │   └── CustomerService.java  # CustomerService业务接口
│   │       ├── servlet/  # servlet web 层
│   │       │   ├── AddCustomerServlet.java
│   │       │   ├── CheckCodeServlet.java
│   │       │   ├── DelCustomerServlet.java
│   │       │   ├── DelSelectedServlet.java
│   │       │   ├── FindCustomerByPageServlet.java
│   │       │   ├── FindCustomerServlet.java
│   │       │   ├── ListServlet.java
│   │       │   ├── LoginServlet.java
│   │       │   ├── UpdateCustomerServlet.java
│   │       │   └── UpdateServlet.java
│   │       ├── test/
│   │       │   ├── TestDemo1.java
│   │       │   └── TestUser.java
│   │       └── utils/
│   │           ├── DateUtils.java
│   │           ├── DownLoadUtils.java
│   │           └── JDBCUtils.java
│   └── druid.properties  # Druid连接池配置
web/
│   ├── WEB-INF/
│   │   ├── lib/
│   │   │   ├── c3p0-0.9.1.2.jar
│   │   │   ├── commons-beanutils-1.8.3.jar
│   │   │   ├── commons-dbutils-1.4.jar
│   │   │   ├── commons-logging-1.1.1.jar
│   │   │   ├── druid-1.0.9.jar
│   │   │   ├── hamcrest-core-1.3.jar
│   │   │   ├── javax.servlet.jsp.jstl.jar
│   │   │   ├── jstl-impl.jar
│   │   │   ├── junit-4.12.jar
│   │   │   ├── mysql-connector-j-8.0.33.jar
│   │   │   ├── mysql-connector-java-5.1.18-bin.jar
│   │   │   ├── spring-beans-4.2.4.RELEASE.jar
│   │   │   ├── spring-core-4.2.4.RELEASE.jar
│   │   │   ├── spring-jdbc-4.2.4.RELEASE.jar
│   │   │   └── spring-tx-4.2.4.RELEASE.jar
│   │   └── web.xml
│   ├── css/
│   │   ├── bootstrap-theme.css
│   │   ├── bootstrap-theme.min.css
│   │   ├── bootstrap.css
│   │   └── bootstrap.min.css
│   ├── fonts/
│   │   ├── glyphicons-halflings-regular.eot
│   │   ├── glyphicons-halflings-regular.svg
│   │   ├── glyphicons-halflings-regular.ttf
│   │   ├── glyphicons-halflings-regular.woff
│   │   └── glyphicons-halflings-regular.woff2
│   ├── js/
│   ├── add.jsp
│   ├── index.jsp  # 网站首页
│   ├── list.jsp
│   ├── login.jsp
│   └── update.jsp

Sql

/*Navicat Premium Data TransferSource Server         : rootSource Server Type    : MySQLSource Server Version : 50651Source Host           : localhost:3306Source Schema         : testTarget Server Type    : MySQLTarget Server Version : 50651File Encoding         : 65001Date: 19/05/2022 18:56:11
*/SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;-- ----------------------------
-- Table structure for customer
-- ----------------------------
DROP TABLE IF EXISTS `customer`;
CREATE TABLE `customer`  (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`gender` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`age` int(11) NULL DEFAULT NULL,`address` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`qq` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`email` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 7 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;-- ----------------------------
-- Records of customer
-- ----------------------------
INSERT INTO `customer` VALUES (1, '张的小群', '男', 44, '湖南', '111', 'ss.@163.com');
INSERT INTO `customer` VALUES (2, '张的小群', '女', -22, '河南', '111', '55');
INSERT INTO `customer` VALUES (3, '张的小群', '男', 44, '广西', '111', 'ew56464@163.com');
INSERT INTO `customer` VALUES (4, '1', '男', 1, '河南', '111', 'a');
INSERT INTO `customer` VALUES (5, '张的小群', '男', -22, '河南', '111', '55');
INSERT INTO `customer` VALUES (6, '张的小群', '男', 44, '河南', '111', 'zq13353612655@163.com');-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user`  (`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',`username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,`password` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL,PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Compact;-- ----------------------------
-- Records of user
-- ----------------------------SET FOREIGN_KEY_CHECKS = 1;

Java Web客户信息管理系统练习demo分析

这个demo是一个完整的Java Web客户信息管理系统,主要练习了Java Web开发的核心技术和MVC架构模式的应用。

一、项目技术栈

  • 后端:Java、Servlet、JDBC
  • 数据库访问:Druid连接池、Apache Commons DBUtils
  • 前端:JSP、Bootstrap、jQuery
  • 数据库:MySQL

二、项目结构

项目采用典型的MVC三层架构设计:

demo1/
├── lib/            # 后端依赖库
├── src/            # Java源代码
│   ├── com/demo/entity/    # 实体类
│   ├── com/demo/dao/       # 数据访问层
│   ├── com/demo/service/   # 业务逻辑层
│   ├── com/demo/servlet/   # 控制器层
│   ├── com/demo/utils/     # 工具类
│   └── druid.properties       # 数据库连接池配置
└── web/            # 前端资源├── WEB-INF/    # Web配置文件├── css/        # 样式文件├── js/         # JavaScript文件├── fonts/      # 字体文件└── *.jsp       # 页面文件

三、核心功能模块练习

1. 用户登录模块

练习了用户身份验证、验证码生成与校验、Session管理等功能:

  • LoginServlet:处理用户登录请求,验证用户名密码,管理用户会话
  • CheckCodeServlet:生成随机验证码图片,用于防止暴力破解
  • login.jsp:用户登录界面,包含表单验证

关键代码如验证码生成:

// 生成随机验证码
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuilder stringBuilder = new StringBuilder();
for (int i = 1; i <=4 ; i++) {int index = random.nextInt(str.length());char c = str.charAt(index);stringBuilder.append(c);graphics.drawString(c+"",width/5 * i,height/2);
}
// 存储验证码到session
HttpSession session = request.getSession();
session.setAttribute("checkCode_session",stringBuilder.toString());

2. 客户信息CRUD模块

练习了完整的增删改查操作,包括:

  • Customer实体类:封装客户信息数据(id、name、gender、age、address、qq、email)
  • 数据访问层:CustomerDao接口及实现类,负责数据库操作
  • 业务逻辑层:CustomerService接口及实现类,处理业务逻辑
  • 控制器层:多个Servlet处理不同请求
    • ListServlet:查询所有客户
    • AddCustomerServlet:添加客户
    • UpdateServlet:修改客户
    • DelCustomerServlet:删除单个客户
    • DelSelectedServlet:批量删除客户

3. 分页查询模块

练习了分页查询的实现,包括:

  • PageBean实体类:封装分页相关数据(当前页、每页显示条数、总记录数、总页数、数据列表)
  • FindCustomerByPageServlet:处理分页查询请求
  • 动态SQL构建:根据条件动态生成SQL语句

分页查询的关键实现:

@Override
public List<Customer> findByPage(int start, int rows, Map<String, String[]> condition) throws Exception {// 初始化SQLString sql = "SELECT * FROM CUSTOMER where 1=1";StringBuilder sb = new StringBuilder(sql);// 动态构建条件查询SQLSet<String> set = condition.keySet();List<Object> params = new ArrayList<Object>();for (String key : set) {// 排除分页参数if("currentPage".equals(key)||"rows".equals(key)){continue;}String value = condition.get(key)[0];if (value != null && !"".equals(value)) {sb.append(" and " + key + " like ?");params.add("%"+value+"%");}}// 添加分页条件sb.append(" limit ?,?");params.add(start);params.add(rows);return queryRunner.query(sb.toString(), new BeanListHandler<Customer>(Customer.class), params.toArray());
}

4. 数据库连接管理

练习了使用连接池管理数据库连接:

  • druid.properties:配置Druid连接池参数
  • JDBCUtils工具类:提供获取数据库连接的方法
  • QueryRunner:使用DBUtils简化数据库操作

四、前端技术应用

  • 使用Bootstrap实现响应式布局和美观的UI组件
  • 使用jQuery处理前端交互和表单验证
  • 使用JSTL标签库在JSP页面中展示数据
  • 实现了客户信息的表格展示、表单提交、确认对话框等交互功能

五、练习的核心知识点

  1. Servlet编程:请求处理、响应生成、请求转发与重定向
  2. JSP技术:EL表达式、JSTL标签库、表单处理
  3. MVC架构:分层设计、职责分离
  4. 数据库操作:SQL语句、连接池、ORM映射
  5. 前端技术:HTML、CSS、JavaScript、Bootstrap
  6. 会话管理:Session、Cookie的使用
  7. 数据校验:前后端数据验证
  8. 分页查询:分页算法、动态SQL构建

六、项目功能总结

这个demo完整实现了一个客户信息管理系统,包含用户登录、客户信息的增删改查、分页查询、条件搜索和批量操作等功能,是一个非常经典的Java Web入门练习项目,全面覆盖了Web开发的核心知识点。

通过这个demo的练习,可以掌握Java Web开发的基本流程和核心技术,为更复杂的Web应用开发打下坚实的基础。

代码文件

一、配置文件

无配置文件

二、业务代码

实体类(Entity/Model)

src\com\demo\entity\Customer.java
package com.demo.entity;public class Customer {
//    id int primary key auto_increment,
//    name varchar(20) not null,
//    gender varchar(5),
//    age int,
//    address varchar(32),
//    qq	varchar(20),
//    email varchar(50)private Integer id;private String name;private String gender;private Integer age;private String address;private String qq;private String email;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public String getGender() {return gender;}public void setGender(String gender) {this.gender = gender;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getAddress() {return address;}public void setAddress(String address) {this.address = address;}public String getQq() {return qq;}public void setQq(String qq) {this.qq = qq;}public String getEmail() {return email;}public void setEmail(String email) {this.email = email;}@Overridepublic String toString() {return "User{" +"id=" + id +", name='" + name + '\'' +", gender='" + gender + '\'' +", age=" + age +", address='" + address + '\'' +", qq='" + qq + '\'' +", email='" + email + '\'' +'}';}
}
src\com\demo\entity\PageBean.java
package com.demo.entity;import java.util.List;
//分页对象
public class PageBean<T> {private int currentPage;//当前页private int rows;//每页显示条数private int totalPage;//总页码private int totalCount;//总记录数private List<T> list;//每页数据的集合public int getCurrentPage() {return currentPage;}public void setCurrentPage(int currentPage) {this.currentPage = currentPage;}public int getRows() {return rows;}public void setRows(int rows) {this.rows = rows;}public int getTotalPage() {return totalPage;}public void setTotalPage(int totalPage) {this.totalPage = totalPage;}public int getTotalCount() {return totalCount;}public void setTotalCount(int totalCount) {this.totalCount = totalCount;}public List<T> getList() {return list;}public void setList(List<T> list) {this.list = list;}@Overridepublic String toString() {return "PageBean{" +"currentPage=" + currentPage +", rows=" + rows +", totalPage=" + totalPage +", totalCount=" + totalCount +", list=" + list +'}';}
}
src\com\demo\entity\User.java
package com.demo.entity;public class User {
private Integer id;
private String username;
private String password;public User(Integer id, String username, String password) {this.id = id;this.username = username;this.password = password;}public User() {}public int getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}
}

数据访问层(DAO接口)

src\com\demo\dao\CustomerDao.java
package com.demo.dao;import com.demo.entity.Customer;
import com.demo.entity.User;import java.util.List;
import java.util.Map;public interface CustomerDao {//登入验证public User checkUser(String username, String password) throws Exception;//查询全部public List<Customer> getCustomerList() throws Exception;//查询单个public Customer getCustomerById(Integer id) throws Exception;//添加客户public int addCustomer(Customer customer) throws Exception;//修改客户public int updateCustomer(Customer customer) throws Exception;//删除客户public int deleteCustomerById(Integer id) throws Exception;
//查询总记录数int findTotalCount(Map<String, String[]> condition)throws Exception;
//根据分页查询返回满足条件的list集合List<Customer> findByPage(int start, int rows, Map<String, String[]> condition)throws Exception;
}

数据访问层(DAO实现)

src\com\demo\dao\impl\CustomerDaoImpl.java
package com.demo.dao.impl;import com.demo.dao.CustomerDao;
import com.demo.entity.Customer;
import com.demo.entity.User;
import com.demo.utils.JDBCUtils;
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 java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;public class CustomerDaoImpl implements CustomerDao {private final String CHECK_USER = "SELECT * FROM USER WHERE USERNAME=? AND PASSWORD=?";private final String GET_USERLIST = "SELECT * FROM CUSTOMER";private final String GET_USERID = "SELECT * FROM CUSTOMER WHERE ID=?";private final String ADD_USER = "INSERT INTO CUSTOMER VALUES (NULL,?,?,?,?,?,?)";private final String UPDATE_USER = "UPDATE CUSTOMER SET NAME=?,GENDER=?,AGE=?,ADDRESS=?,QQ=?,EMAIL=? WHERE ID=?";private final String DELETE_USERID = "DELETE FROM CUSTOMER WHERE ID=?";//    private final String FINDTOTSLCOUNT="SELECT COUNT(*) FROM CUSTOMER";private final String FINDBYPAGE = "SELECT * FROM CUSTOMER LIMIT ?,?";private QueryRunner queryRunner = new QueryRunner(JDBCUtils.getDataSource());@Overridepublic User checkUser(String username, String password) throws Exception {return queryRunner.query(CHECK_USER, new BeanHandler<User>(User.class), username, password);}@Overridepublic List<Customer> getCustomerList() throws Exception {return queryRunner.query(GET_USERLIST, new BeanListHandler<Customer>(Customer.class));}@Overridepublic Customer getCustomerById(Integer id) throws Exception {return queryRunner.query(GET_USERID, new BeanHandler<Customer>(Customer.class), id);}@Overridepublic int addCustomer(Customer customer) throws Exception {return queryRunner.update(ADD_USER, customer.getName(), customer.getGender(), customer.getAge(), customer.getAddress(), customer.getQq(), customer.getEmail());}@Overridepublic int updateCustomer(Customer customer) throws Exception {return queryRunner.update(UPDATE_USER, customer.getName(), customer.getGender(), customer.getAge(), customer.getAddress(), customer.getQq(), customer.getEmail(), customer.getId());}@Overridepublic int deleteCustomerById(Integer id) throws Exception {return queryRunner.update(DELETE_USERID, id);}//居合函数@Overridepublic int findTotalCount(Map<String, String[]> condition) throws Exception {//初始化sqlString sql = "SELECT COUNT(*) FROM CUSTOMER where 1=1";//StringBuilder动态sqlStringBuilder sb = new StringBuilder(sql);//2.遍历MapSet<String> set = condition.keySet();//存储value的集合List<Object> params = new ArrayList<Object>();for (String key : set) {//去掉两个参数currentPage,rowsif("currentPage".equals(key)||"rows".equals(key)){continue;}//根据key获取valueString value = condition.get(key)[0];//3.判断value值是否有if (value != null && !"".equals(value)) {//有值的状态,开始拼动态sqlsb.append(" and " + key + " like ? ");//?中的值存储起来params.add("%"+value+"%");}}sql = sb.toString();// System.out.println(sql);//System.out.println(params);//ScalarHandler有居合函数的时候才用这个类return ((Long) queryRunner.query(sql, new ScalarHandler(), params.toArray())).intValue();}@Overridepublic List<Customer> findByPage(int start, int rows, Map<String, String[]> condition) throws Exception {//初始化sqlString sql = "SELECT * FROM CUSTOMER where 1=1";//StringBuilder动态sqlStringBuilder sb = new StringBuilder(sql);//2.遍历MapSet<String> set = condition.keySet();//存储value的集合List<Object> params = new ArrayList<Object>();for (String key : set) {//去掉两个参数currentPage,rowsif("currentPage".equals(key)||"rows".equals(key)){continue;}//根据key获取valueString value = condition.get(key)[0];//3.判断value值是否有if (value != null && !"".equals(value)) {//有值的状态,开始拼动态sql
//    sb.append(" and " + key + " like ?");sb.append(" and " + key + " like ?");//?中的值存储起来params.add("%"+value+"%");}}
//添加分页的条件sb.append(" limit ?,?");
//把start和rows装进params中params.add(start);params.add(rows);sql=sb.toString();// System.out.println(sql);// System.out.println(params);return queryRunner.query(sql, new BeanListHandler<Customer>(Customer.class),params.toArray());}
}

业务逻辑层(Service接口)

src\com\demo\service\CustomerService.java
package com.demo.service;import com.demo.entity.Customer;
import com.demo.entity.PageBean;import java.util.List;
import java.util.Map;public interface CustomerService {//登入验证public boolean checkCustomer(String username, String password) throws Exception;//查询全部public List<Customer> getCustomerList() throws Exception;//查询单个public Customer getCustomerById(Integer id) throws Exception;//添加客户public boolean addCustomer(Customer customer) throws Exception;//修改客户public boolean updateCustomer(Customer customer) throws Exception;//删除客户public boolean deleteCustomerById(Integer id) throws Exception;//批量删除客户public void delSelectedCustomers(String[] ids) throws Exception;
//分页查询 返回PageBean对象PageBean findCustomerByPage(int currentPage, int rows, Map<String, String[]> condition)throws Exception;//查询总记录数int findTotalCount(Map<String, String[]> condition)throws Exception;}

业务逻辑层(Service实现)

src\com\demo\service\impl\CustomerServiceImpl.java
package com.demo.service.impl;import com.demo.dao.CustomerDao;
import com.demo.dao.impl.CustomerDaoImpl;
import com.demo.entity.Customer;
import com.demo.entity.PageBean;
import com.demo.service.CustomerService;import java.util.List;
import java.util.Map;//业务逻辑层service实现类
public class CustomerServiceImpl implements CustomerService {private CustomerDao customerDao = new CustomerDaoImpl();@Overridepublic boolean checkCustomer(String username, String password) throws Exception {return customerDao.checkUser(username, password) != null ? true : false;}@Overridepublic List<Customer> getCustomerList() throws Exception {return customerDao.getCustomerList();}@Overridepublic Customer getCustomerById(Integer id) throws Exception {return customerDao.getCustomerById(id);}@Overridepublic boolean addCustomer(Customer customer) throws Exception {return customerDao.addCustomer(customer) > 0 ? true : false;}@Overridepublic boolean updateCustomer(Customer customer) throws Exception {return customerDao.updateCustomer(customer) > 0 ? true : false;}@Overridepublic boolean deleteCustomerById(Integer id) throws Exception {return customerDao.deleteCustomerById(id) > 0 ? true : false;}@Overridepublic void delSelectedCustomers(String[] ids) throws Exception {if (null != ids && ids.length > 0) {//1.遍历idsfor (String id : ids) {//调用dao逐个删除customerDao.deleteCustomerById(Integer.parseInt(id));}}}@Overridepublic PageBean findCustomerByPage(int currentPage, int rows, Map<String, String[]> condition) throws Exception {if (currentPage <= 0) {currentPage = 1;}//1.创建空的PageBean对象PageBean pageBean = new PageBean();//2.设置当前页码属性和rows属性pageBean.setCurrentPage(currentPage);//当前页pageBean.setRows(rows);//3.调用到查询totalCount总记录数int totalCount = customerDao.findTotalCount(condition);pageBean.setTotalCount(totalCount);// System.out.println("总记录数"+totalCount);//4.计算开始查询的索引int start = (currentPage - 1) * rows;//5.调用dao查询list集合List<Customer> list = customerDao.findByPage(start, rows, condition);pageBean.setList(list);//6.计算总页码int totalPage = totalCount % rows == 0 ? totalCount / rows : totalCount / rows + 1;pageBean.setTotalPage(totalPage);//System.out.println("总页数"+totalPage);if (currentPage==totalPage){currentPage = totalPage;}return pageBean;}@Overridepublic int findTotalCount(Map<String, String[]> condition) throws Exception {return customerDao.findTotalCount(condition);}
}

Servlet(控制层)

src\com\demo\servlet\AddCustomerServlet.java
package com.demo.servlet;import com.demo.entity.Customer;
import com.demo.service.CustomerService;
import com.demo.service.impl.CustomerServiceImpl;
import org.apache.commons.beanutils.BeanUtils;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 java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;@WebServlet("/addCustomerServlet")
public class AddCustomerServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置编码方式request.setCharacterEncoding("utf-8");//2.获取表单数据Map<String, String[]> map = request.getParameterMap();//封装对象Customer customer = new Customer();try {BeanUtils.populate(customer, map);} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}//调用service保存数据CustomerService customerService = new CustomerServiceImpl();try {boolean flag = customerService.addCustomer(customer);if (flag) {//5.跳转到 userListServlet重新查询数据库response.sendRedirect(request.getContextPath() + "/findCustomerByPageServlet");}} catch (Exception e) {e.printStackTrace();}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
}
src\com\demo\servlet\CheckCodeServlet.java
package com.demo.servlet;import javax.imageio.ImageIO;
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 javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;@WebServlet("/checkCodeServlet")
public class CheckCodeServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {int width = 100;int height = 50;//1、创建一个对象,用来生成验证码图片BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);//2、美化//2.1填充背景颜色Graphics graphics = bufferedImage.getGraphics();//画图对象graphics.setColor(Color.PINK);graphics.fillRect(0,0,width,height);//2.2画边框graphics.setColor(Color.BLUE);graphics.drawRect(0,0,width-1,height-1);//2.3实现验证码随机生成String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";//随机生成角标Random random = new Random();//存储生成的验证码StringBuilder stringBuilder = new StringBuilder();for (int i = 1; i <=4 ; i++) {int index = random.nextInt(str.length());char c = str.charAt(index);stringBuilder.append(c);graphics.drawString(c+"",width/5 * i,height/2);}String checkCode_session = stringBuilder.toString();//存储验证码到session中HttpSession session = request.getSession();session.setAttribute("checkCode_session",checkCode_session);//2.4画干扰线graphics.setColor(Color.GREEN);for (int i = 0; i < 10 ; i++) {int x1 = random.nextInt(width);int x2 = random.nextInt(width);int y1 = random.nextInt(height);int y2 = random.nextInt(height);graphics.drawLine(x1,x2,y1,y2);}//3、输出验证码到浏览器ImageIO.write(bufferedImage,"jpg", response.getOutputStream());}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request,response);}
}
src\com\demo\servlet\DelCustomerServlet.java
package com.demo.servlet;import com.demo.service.CustomerService;
import com.demo.service.impl.CustomerServiceImpl;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 java.io.IOException;@WebServlet("/delCustomerServlet")
public class DelCustomerServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.获取idsString id = request.getParameter("id");//2.调用serviceCustomerService customerService = new CustomerServiceImpl();try {boolean flag = customerService.deleteCustomerById(Integer.parseInt(id));if (flag){// 3.跳转到查询所有servletresponse.sendRedirect(request.getContextPath() + "/listServlet");}} catch (Exception e) {e.printStackTrace();}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);}
}
src\com\demo\servlet\DelSelectedServlet.java
package com.demo.servlet;import com.demo.service.CustomerService;
import com.demo.service.impl.CustomerServiceImpl;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 java.io.IOException;//刪除选中
@WebServlet("/delSelectedServlet")
public class DelSelectedServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.获取idsString[] ids = request.getParameterValues("cid");//2.调用serviceCustomerService customerService = new CustomerServiceImpl();try {customerService.delSelectedCustomers(ids);} catch (Exception e) {e.printStackTrace();}// 3.跳转到查询所有servletresponse.sendRedirect(request.getContextPath() + "/listServlet");}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}
}
src\com\demo\servlet\FindCustomerByPageServlet.java
package com.demo.servlet;import com.demo.entity.PageBean;
import com.demo.service.CustomerService;
import com.demo.service.impl.CustomerServiceImpl;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 java.io.IOException;
import java.util.Map;@WebServlet("/findCustomerByPageServlet")
public class FindCustomerByPageServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//设置 编码方式request.setCharacterEncoding("utf-8");//1.接受请求参数String currentPage = request.getParameter("currentPage");//当前页码//System.out.println("当前页aaaaa"+currentPage);String rows = request.getParameter("rows");//显示每页条数
//        String totalPage = request.getParameter("totalPage");//总页数
//        String totalCount = request.getParameter("totalCount");//总记录数
//        System.out.println("总页数aaaaaaaaaaa"+totalPage);
//        System.out.println("总记录数aaaaaaaaa"+totalCount);//第一页然后再往前就让其一直在第一页if (currentPage == null || "".equals(currentPage)) {currentPage = "1";}if (rows == null || "".equals(rows)) {rows = "5";}//获取表单数据Map<String, String[]> condition = request.getParameterMap();//2.调用service查询CustomerService customerService = new CustomerServiceImpl();PageBean pb = null;int i=0;int totalCounts=0;//总记录数int rowss=5;try {//总记录数totalCounts = customerService.findTotalCount(condition);int totalPage = totalCounts % rowss == 0 ? totalCounts / rowss : totalCounts / rowss + 1;//总页数//最后一页然后再往后就让其一直在尾页i=Integer.parseInt(currentPage);//currentPage当前页if (i == totalPage || i>=totalPage) {currentPage =totalPage+"";
//                System.out.println("i=="+i);
//                System.out.println("当前页currentPage=="+currentPage);
//                System.out.println("尾页totalPage=="+totalPage);}//            System.out.println("当前页"+Integer.parseInt(currentPage)+"当前页加一"+(i+1));
//            System.out.println("当前页-----"+currentPage+"----");
//            System.out.println("总页数==="+totalCounts);if (rows == null || "".equals(rows)) {rows = "5";}pb = customerService.findCustomerByPage(Integer.parseInt(currentPage), Integer.parseInt(rows),condition);} catch (Exception e) {e.printStackTrace();}//System.out.println(pb);
//3.将pageBean对象存入requestrequest.setAttribute("pb", pb);//request.setAttribute("params",condition);//转发到list.jsp显示request.getRequestDispatcher("/list.jsp").forward(request, response);}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}
}
src\com\demo\servlet\FindCustomerServlet.java
package com.demo.servlet;import com.demo.entity.Customer;
import com.demo.entity.PageBean;
import com.demo.service.CustomerService;
import com.demo.service.impl.CustomerServiceImpl;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 java.io.IOException;@WebServlet("/findCustomerServlet")
public class FindCustomerServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//1.获取idString id = request.getParameter("id");//System.out.println(id);//调用service查询CustomerService customerService = new CustomerServiceImpl();try {Customer customer = customerService.getCustomerById(Integer.parseInt(id));// System.out.println(customer.getAddress());//将对象customer保存到request中request.setAttribute("customer", customer);//4.将页面跳转到update.jsprequest.getRequestDispatcher("/update.jsp").forward(request,response);} catch (Exception e) {e.printStackTrace();}
//        //转发到list.jsp显示
//        response.sendRedirect("./list.jsp");}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}
}
src\com\demo\servlet\ListServlet.java
package com.demo.servlet;import com.demo.entity.Customer;
import com.demo.service.CustomerService;
import com.demo.service.impl.CustomerServiceImpl;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 java.io.IOException;
import java.util.List;@WebServlet( "/listServlet")
public class ListServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//查询全部//创建一个UserService实例CustomerService customerService=new CustomerServiceImpl();try {List<Customer> customerList = customerService.getCustomerList();//把userList传递给页面list.jsp进行显示request.setAttribute("customerList",customerList);//跳转页面request.getRequestDispatcher("/list.jsp").forward(request,response);}catch (Exception e){e.printStackTrace();}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {this.doPost(request,response);}
}
src\com\demo\servlet\LoginServlet.java
package com.demo.servlet;import com.demo.entity.User;
import com.demo.service.CustomerService;
import com.demo.service.impl.CustomerServiceImpl;
import org.apache.commons.beanutils.BeanUtils;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 javax.servlet.http.HttpSession;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {//设置编码方式request.setCharacterEncoding("utf-8");//获取参数
//        String username = request.getParameter("username");
//        String password = request.getParameter("password");//获取页面上所有的数据Map<String, String[]> map = request.getParameterMap();//创建一个Login对象User login = new User();//把map中的数据拷贝到user对象中try {BeanUtils.populate(login, map);} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}//用户如入的信息String verifycode = request.getParameter("verifycode");//3.获取验证码HttpSession session = request.getSession();String checkCode_session = (String) session.getAttribute("checkCode_session");//移除验证码保证验证码的唯一性session.removeAttribute("checkCode_session");//4、判断用户输入的验证码和生成的验证码是否一致//判断输入的验证码不能为空if (verifycode != null && checkCode_session.equalsIgnoreCase(verifycode)) {// 验证码正确//判断用户名和密码发是否正确//1、创建UserService实例对象CustomerService customerService = new CustomerServiceImpl();try {boolean flag = customerService.checkCustomer(login.getUsername(), login.getPassword());if (flag) {//用户合法//存储用户信息到session中
//                    session.setAttribute("username", login.getUsername());session.setAttribute("user",login);//跳转页面index.jspresponse.sendRedirect(request.getContextPath() + "/index.jsp");} else {//非法用户//用户名或者密码错误,给用户返回提示信息request.setAttribute("msg_error", "用户名或者密码错误");//跳转页面(转发)request.getRequestDispatcher("/login.jsp").forward(request, response);}} catch (Exception e) {e.printStackTrace();}} else {//验证码错误,给用户返回提示信息request.setAttribute("msg_error", "验证码错误!");//跳转页面(转发)request.getRequestDispatcher("/login.jsp").forward(request, response);}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doPost(request, response);}
}
src\com\demo\servlet\UpdateCustomerServlet.java
package com.demo.servlet;import com.demo.entity.Customer;
import com.demo.service.CustomerService;
import com.demo.service.impl.CustomerServiceImpl;
import org.apache.commons.beanutils.BeanUtils;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 java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;@WebServlet("/updateCustomerServlet")
public class UpdateCustomerServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置编码方式request.setCharacterEncoding("utf-8");//获取表单数据Map<String, String[]> map = request.getParameterMap();// 封装对象Customer customer = new Customer();try {BeanUtils.populate(customer,map);//调用修改serviceCustomerService customerService=new CustomerServiceImpl();boolean flag= customerService.updateCustomer(customer);if (flag){//跳转到查询所有response.sendRedirect(request.getContextPath()+"/findCustomerByPageServlet");}} catch (Exception e) {e.printStackTrace();}}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
}
src\com\demo\servlet\UpdateServlet.java
package com.demo.servlet;import com.demo.entity.Customer;
import com.demo.service.CustomerService;
import com.demo.service.impl.CustomerServiceImpl;
import org.apache.commons.beanutils.BeanUtils;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 java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.util.Map;@WebServlet( "/updateServlet")
public class UpdateServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {Customer customer=null;try {//设置编码方式request.setCharacterEncoding("utf-8");//获取参数Map<String,String[]>map=request.getParameterMap();//封装对象customer=new Customer();//拷贝数据BeanUtils.populate(customer,map);} catch (IllegalAccessException e) {e.printStackTrace();} catch (InvocationTargetException e) {e.printStackTrace();}//保存数据CustomerService customerService=new CustomerServiceImpl();try {customerService.updateCustomer(customer);} catch (Exception e) {e.printStackTrace();}//跳转资源response.sendRedirect(request.getContextPath()+"/listServlet");}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.doPost(request,response);}
}

工具类(Utils/Util)

src\com\demo\utils\DateUtils.java
package com.demo.utils;import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;/*** 日期工具类*/
public class DateUtils {/*** @param date 需要格式化的日期* @return 字符串类型的日期*/public String fromDateToString(Date date) {SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");String strDate = format.format(date);return strDate;}/*** @param strDate 字符串类型的日期* @return Date类型的日期*/public Date fromStringToDate(String strDate) throws Exception {SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");Date date = format.parse(strDate);return date;}
}
src\com\demo\utils\DownLoadUtils.java
package com.demo.utils;import sun.misc.BASE64Encoder;import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;public class DownLoadUtils {public static String getFileName(String agent, String filename) throws UnsupportedEncodingException {if (agent.contains("MSIE")) {// IE浏览器filename = URLEncoder.encode(filename, "utf-8");filename = filename.replace("+", " ");} else if (agent.contains("Firefox")) {// 火狐浏览器BASE64Encoder base64Encoder = new BASE64Encoder();filename = "=?utf-8?B?" + base64Encoder.encode(filename.getBytes("utf-8")) + "?=";} else {// 其它浏览器filename = URLEncoder.encode(filename, "utf-8");}return filename;}
}
src\com\demo\utils\JDBCUtils.java
package com.demo.utils;import com.alibaba.druid.pool.DruidDataSourceFactory;import javax.sql.DataSource;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;/*** JDBC工具类 使用Durid连接池*/
public class JDBCUtils {private static DataSource ds ;static {try {//1.加载配置文件Properties pro = new Properties();//使用ClassLoader加载配置文件,获取字节输入流InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("druid.properties");pro.load(is);//2.初始化连接池对象ds = DruidDataSourceFactory.createDataSource(pro);} catch (IOException e) {e.printStackTrace();} catch (Exception e) {e.printStackTrace();}}/*** 获取连接池对象*/public static DataSource getDataSource(){return ds;}/*** 获取连接Connection对象*/public static Connection getConnection() throws SQLException {return  ds.getConnection();}
}

测试类(Test)

src\com\demo\test\TestDemo1.java
package com.demo.test;import java.util.ArrayList;
import java.util.List;public class TestDemo1 {public static void main(String[] args) {List<Object> list =new ArrayList<Object>();list.add("123");list.add("213");list.add("312");for (Object s : list) {System.out.println(s);}System.out.println(list);}
}
src\com\demo\test\TestUser.java
package com.demo.test;import com.demo.entity.Customer;
import com.demo.service.CustomerService;
import com.demo.service.impl.CustomerServiceImpl;
import org.junit.Test;import java.util.List;public class TestUser {//查询全部@Testpublic void testuserlist(){CustomerService customerService=new CustomerServiceImpl();try {List<Customer> list=customerService.getCustomerList();for (Customer customer : list) {System.out.println(customer);}} catch (Exception e) {e.printStackTrace();}}//查询单个@Testpublic void testuser(){CustomerService customerService=new CustomerServiceImpl();try {Customer customer=customerService.getCustomerById(2);System.out.println(customer);} catch (Exception e) {e.printStackTrace();}}//添加@Testpublic void testadduser(){CustomerService customerService=new CustomerServiceImpl();Customer customer =new Customer();customer.setName("mo");customer.setGender("www");customer.setAge(18);customer.setAddress("河南");customer.setQq("821428181");customer.setEmail("821428181@qq.com");boolean flag=false;try {flag=customerService.addCustomer(customer);if (flag){System.out.println("添加成功!");}else {System.out.println("添加失败!");}} catch (Exception e) {e.printStackTrace();}}//修改@Testpublic void testupdateuser(){CustomerService customerService=new CustomerServiceImpl();Customer customer =new Customer();customer.setName("momo");customer.setGender("www");customer.setAge(19);customer.setAddress("河南");customer.setQq("821428181");customer.setEmail("821428181@qq.com");customer.setId(7);boolean flag=false;try {flag=customerService.updateCustomer(customer);if (flag){System.out.println("修改成功!");}else {System.out.println("修改失败!");}} catch (Exception e) {e.printStackTrace();}}//删除@Testpublic void testdeleteuser(){CustomerService customerService=new CustomerServiceImpl();try {boolean flag=customerService.deleteCustomerById(Integer.parseInt("7"));if (flag){System.out.println("删除成功!");}else {System.out.println("删除失败!");}} catch (Exception e) {e.printStackTrace();}}}

JSP页面

web\add.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><!-- 指定字符集 --><meta charset="utf-8"><!-- 使用Edge最新的浏览器的渲染方式 --><meta http-equiv="X-UA-Compatible" content="IE=edge"><!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。width: 默认宽度与设备的宽度相同initial-scale: 初始的缩放比,为1:1 --><meta name="viewport" content="width=device-width, initial-scale=1"><!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --><title>添加用户</title><!-- 1. 导入CSS的全局样式 --><link href="css/bootstrap.min.css" rel="stylesheet"><!-- 2. jQuery导入,建议使用1.9以上的版本 --><script src="js/jquery-2.1.0.min.js"></script><!-- 3. 导入bootstrap的js文件 --><script src="js/bootstrap.min.js"></script>
</head>
<script>function back() {
//跳转到listServletlocation.href='${pageContext.request.contextPath}/listServlet';// history.back();}
</script>
<body>
<div class="container"><center><h3>添加客户页面</h3></center><form action="${pageContext.request.contextPath}/addCustomerServlet" method="post"><div class="form-group"><label for="name">姓名:</label><input type="text" class="form-control" id="name" name="name" placeholder="请输入姓名"></div><div class="form-group"><label>性别:</label><input type="radio" name="gender" value="" checked="checked"/><input type="radio" name="gender" value=""/></div><div class="form-group"><label for="age">年龄:</label><input type="text" class="form-control" id="age" name="age" placeholder="请输入年龄"></div><div class="form-group"><label for="address">籍贯:</label><select name="address" class="form-control" id="address"><option value="河南">河南</option><option value="广东">广东</option><option value="广西">广西</option><option value="湖南">湖南</option></select></div><div class="form-group"><label for="qq">QQ:</label><input type="text" class="form-control" name="qq" id="qq" placeholder="请输入QQ号码"/></div><div class="form-group"><label for="email">Email:</label><input type="text" class="form-control" name="email" id="email" placeholder="请输入邮箱地址"/></div><div class="form-group" style="text-align: center"><input class="btn btn-primary" type="submit" value="提交"/><input class="btn btn-default" type="reset" value="重置"/><input class="btn btn-default" type="button" onclick="back()" value="返回"/></div></form>
</div>
</body>
</html>
web\index.jsp
<%@ page import="com.demo.entity.User" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html><head><meta charset="utf-8"/><meta http-equiv="X-UA-Compatible" content="IE=edge"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>首页</title><!-- 1. 导入CSS的全局样式 --><link href="css/bootstrap.min.css" rel="stylesheet"><!-- 2. jQuery导入,建议使用1.9以上的版本 --><script src="js/jquery-2.1.0.min.js"></script><!-- 3. 导入bootstrap的js文件 --><script src="js/bootstrap.min.js"></script><script type="text/javascript"></script></head><body><span style="font-size: 20px">${user.username},欢迎您
<%--    <%--%>
<%--      User login =(User) request.getSession().getAttribute("user");--%>
<%--      out.print(login.getUsername());--%>
<%--    %>--%>
<%--    <%=login.getUsername()%>,再次欢迎您--%>
<%--  </span>--%><div align="center"><ahref="${pageContext.request.contextPath}/findCustomerByPageServlet" style="text-decoration:none;font-size:33px">查询所有客户信息</a></div></body>
</html>
web\list.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><!-- 指定字符集 --><meta charset="utf-8"><!-- 使用Edge最新的浏览器的渲染方式 --><meta http-equiv="X-UA-Compatible" content="IE=edge"><!-- viewport视口:网页可以根据设置的宽度自动进行适配,在浏览器的内部虚拟一个容器,容器的宽度与设备的宽度相同。width: 默认宽度与设备的宽度相同initial-scale: 初始的缩放比,为1:1 --><meta name="viewport" content="width=device-width, initial-scale=1"><!-- 上述3个meta标签*必须*放在最前面,任何其他内容都*必须*跟随其后! --><title>用户信息管理系统</title><!-- 1. 导入CSS的全局样式 --><link href="css/bootstrap.min.css" rel="stylesheet"><!-- 2. jQuery导入,建议使用1.9以上的版本 --><script src="js/jquery-2.1.0.min.js"></script><!-- 3. 导入bootstrap的js文件 --><script src="js/bootstrap.min.js"></script><style type="text/css">td, th {text-align: center;}</style><script>function delCustomer(id) {if (confirm("确定要删除吗?")) {location.href = "${pageContext.request.contextPath}/delCustomerServlet?id=" + id;}}window.onload = function () {//为删除选中按钮添加点击事件document.getElementById("delSelected").onclick = function () {if (confirm("您确定要删除选中的条目吗")) {//标志位,表示是否有选中的条目var flag = false;//是否有选中的条目//2.获取下面的所有多选框的元素var ids = document.getElementsByName("cid");//遍历数据for (var i = 0; i < ids.length; i++) {//如果有一个被选中的条目if (ids[i].checked) {flag = true;break;}//根据firstCb的checked状态修改ids[i]的checked状态ids[i].checked = this.checked;}
//如果有选中在提交if (flag) {//提交form表单document.getElementById("form").submit();}}}
//1.获取firstCb元素,绑定单击事件document.getElementById("firstCb").onclick = function () {
//2.获取下面的所有多选框的元素var ids = document.getElementsByName("cid");//遍历数据for (var i = 0; i < ids.length; i++) {//根据firstCb的checked状态修改ids[i]的checked状态ids[i].checked = this.checked;}}}</script></head>
<body>
<div class="container">
<%-- 让jsp刚加载完就跳转到 findCustomerByPageServlet  --%>
<%--    <jsp:forward page="/findCustomerByPageServlet"></jsp:forward>--%><h3 style="text-align: center">用户信息列表</h3><div style="float:left;"><%--    或者删除  findCustomerByPageServlet?问号后面的  --%><form class="form-inline"action="${pageContext.request.contextPath}/findCustomerByPageServlet?currentPage=${pb.currentPage-1}&rows=5&name=${params.name[0]}&address=${params.address[0]}&email=${params.email[0]}"method="post"><div class="form-group"><label for="exampleInputName2">姓名</label><input type="text" class="form-control" name="name" id="exampleInputName2" value="${params.name[0]}"placeholder=""></div><div class="form-group"><label for="exampleInputName3">籍贯</label><input type="text" name="address" class="form-control" id="exampleInputName3"value="${params.address[0]}" placeholder=""></div><div class="form-group"><label for="exampleInputEmail2">邮箱</label><%--        方式改了。email   text        --%><input type="text" name="email" class="form-control" id="exampleInputEmail2" value="${params.email[0]}"placeholder=""></div><button type="submit" class="btn btn-default">查询</button></form></div><div style="float: right;margin: 5px"><a class="btn btn-primary" href="${pageContext.request.contextPath}/add.jsp">添加客户信息</a><a class="btn btn-primary" href="javascript:void(0)" id="delSelected">删除选中</a></div><form id="form" action="${pageContext.request.contextPath}/delSelectedServlet" method="post"><table border="1" class="table table-bordered table-hover"><tr class="success"><th><input type="checkbox" id="firstCb"></th><th>编号</th><th>姓名</th><th>性别</th><th>年龄</th><th>籍贯</th><th>QQ</th><th>邮箱</th><th>操作</th></tr><c:forEach items="${pb.list}" var="list"><tr><td><input type="checkbox" name="cid" value="${list.id}"></td><td>${list.id}</td><td>${list.name}</td><td>${list.gender}</td><td>${list.age}</td><td>${list.address}</td><td>${list.qq}</td><td>${list.email}</td><td><a class="btn btn-default btn-sm"href="${pageContext.request.contextPath}/findCustomerServlet?id=${list.id}">修改</a>&nbsp;<a class="btn btn-default btn-sm" href="javascript:delCustomer(${list.id})">删除</a></td><%--                        <a class="btn btn-default btn-sm" href="${pageContext.request.contextPath}/delCustomerServlet?id=${list.id}">删除</a></td>--%></tr></c:forEach></table></form><div><nav aria-label="Page navigation"><ul class="pagination"><c:if test="${pb.currentPage==1}"><li class="disabled"></c:if><c:if test="${pb.currentPage!=1}"><li></c:if><a href="${pageContext.request.contextPath}/findCustomerByPageServlet?currentPage=${pb.currentPage-1}&rows=5&name=${params.name[0]}&address=${params.address[0]}&email=${params.email[0]}"aria-label="Previous"><span aria-hidden="true">&laquo;</span></a></li><c:forEach begin="1" end="${pb.totalPage}" var="i"><c:if test="${pb.currentPage==i}"><li class="active"><a href="${pageContext.request.contextPath}/findCustomerByPageServlet?currentPage=${i}&rows=5&name=${params.name[0]}&address=${params.address[0]}&email=${params.email[0]}">${i}</a></li></c:if><c:if test="${pb.currentPage!=i}"><li><a href="${pageContext.request.contextPath}/findCustomerByPageServlet?currentPage=${i}&rows=5&name=${params.name[0]}&address=${params.address[0]}&email=${params.email[0]}">${i}</a></li></c:if></c:forEach><%--作业最后一页之后不让其再往后--%><c:if test="${pb.currentPage==pb.totalPage}"><li class="disabled"></c:if><c:if test="${pb.currentPage!=pb.totalPage}"><li></c:if><a href="${pageContext.request.contextPath}/findCustomerByPageServlet?currentPage=${pb.currentPage+1}&rows=5&name=${params.name[0]}&address=${params.address[0]}&email=${params.email[0]}"aria-label="Next"><span aria-hidden="true">&raquo;</span></a></li><span style="font-size: 25px">共${pb.totalCount}条记录,共${pb.totalPage}页</span></ul></nav></div>
</div>
</body>
</html>
web\login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html lang="zh-CN">
<head><meta charset="utf-8"/><meta http-equiv="X-UA-Compatible" content="IE=edge"/><meta name="viewport" content="width=device-width, initial-scale=1"/><title>管理员登录</title><!-- 1. 导入CSS的全局样式 --><link href="css/bootstrap.min.css" rel="stylesheet"><!-- 2. jQuery导入,建议使用1.9以上的版本 --><script src="js/jquery-2.1.0.min.js"></script><!-- 3. 导入bootstrap的js文件 --><script src="js/bootstrap.min.js"></script><script type="text/javascript">function refreshCode(){//获取验证码的元素对象var vcode = document.getElementById("vcode");//设置验证码的src属性  时间戳vcode.src = "${pageContext.request.contextPath}/checkCodeServlet?time=" + new Date().getTime();}</script>
</head>
<body>
<div class="container" style="width: 400px;"><h3 style="text-align: center;">管理员登录</h3><form action="${pageContext.request.contextPath}/loginServlet" method="post"><div class="form-group"><label for="user">用户名:</label><input type="text" name="username" class="form-control" id="user" placeholder="请输入用户名"/></div><div class="form-group"><label for="password">密码:</label><input type="password" name="password" class="form-control" id="password" placeholder="请输入密码"/></div><div class="form-inline"><label for="vcode">验证码:</label><input type="text" name="verifycode" class="form-control" id="verifycode" placeholder="请输入验证码" style="width: 120px;"/><a href="javascript:refreshCode()"><img src="${pageContext.request.contextPath}/checkCodeServlet" title="看不清点击刷新" id="vcode"/></a></div><hr/><div class="form-group" style="text-align: center;"><input class="btn btn btn-primary" type="submit" value="登录"></div></form><!-- 出错显示的信息框 --><div class="alert alert-warning alert-dismissible" role="alert"><button type="button" class="close" data-dismiss="alert" ><span>X</span></button><strong>${msg_error}</strong></div>
</div>
</body>
</html>
web\update.jsp
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html><head><%--<base href="<%=basePath%>"/>--%><!-- 指定字符集 --><meta charset="utf-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1"><title>修改用户</title><link href="css/bootstrap.min.css" rel="stylesheet"><script src="js/jquery-2.1.0.min.js"></script><script src="js/bootstrap.min.js"></script></head><body><div class="container" style="width: 400px;"><h3 style="text-align: center;">修改联系人</h3><form action="${pageContext.request.contextPath}/updateCustomerServlet" itmes="customer" var="customer" method="post"><%--        <form action="#" method="post">--%><input type="hidden" name="id" value="${customer.id}"><div class="form-group"><label for="name">姓名:</label><input type="text" class="form-control" id="name" name="name" value="${customer.name}" readonly="readonly" placeholder="请输入姓名" /></div><div class="form-group"><label>性别:</label><c:if test="${customer.gender =='男'}" ><input type="radio" name="gender"  value="${customer.gender}" checked="checked" /><input type="radio" name="gender" id="${customer.gender}" value="${customer.gender}"  /></c:if><c:if test="${customer.gender =='女'}"><input type="radio" name="gender" id="gender" value="${customer.gender}"  /><input type="radio" name="gender"  value="${customer.gender}" checked /></c:if></div><div class="form-group"><label for="age">年龄:</label><input type="text" class="form-control" id="age"  name="age" value="${customer.age}" placeholder="请输入年龄" /></div><div class="form-group"><label for="address">籍贯:</label><select name="address" id="address" class="form-control" ><c:if test="${customer.address =='河南'}" ><option value="河南" selected>河南</option><option value="上海">上海</option><option value="安徽">安徽</option></c:if><c:if test="${customer.address =='上海'}" ><option value="河南">河南</option><option value="上海" selected="selected">上海</option><option value="安徽">安徽</option></c:if><c:if test="${customer.address =='安徽'}"><option value="河南">河南</option><option value="上海">上海</option><option value="安徽" selected>安徽</option></c:if></select></div><div class="form-group"><label for="qq">QQ:</label><input type="text" class="form-control" id="qq" name="qq" value="${customer.qq}" placeholder="请输入QQ号码"/></div><div class="form-group"><label for="email">Email:</label><input type="text" class="form-control" id="email" name="email" value="${customer.email}" placeholder="请输入邮箱地址"/></div><div class="form-group" style="text-align: center"><input class="btn btn-primary" type="submit" value="提交" /><input class="btn btn-default" type="reset" value="重置" /><input class="btn btn-default" type="button" value="返回"/></div></form></div></body>
</html>


三、前端代码

无前端代码

四、资源文件

前端库文件

  • 📄 web\js\bootstrap.js
  • 📄 web\js\bootstrap.min.js
  • 📄 web\js\jquery-2.1.0.min.js

依赖JAR包

  • 📄 lib\javax.annotation.jar
  • 📄 lib\javax.ejb.jar
  • 📄 lib\javax.jms.jar
  • 📄 lib\javax.persistence.jar
  • 📄 lib\javax.resource.jar
  • 📄 lib\javax.servlet.jar
  • 📄 lib\javax.servlet.jsp.jar
  • 📄 lib\javax.transaction.jar
  • 📄 web\WEB-INF\lib\c3p0-0.9.1.2.jar
  • 📄 web\WEB-INF\lib\commons-beanutils-1.8.3.jar
  • 📄 web\WEB-INF\lib\commons-dbutils-1.4.jar
  • 📄 web\WEB-INF\lib\commons-logging-1.1.1.jar
  • 📄 web\WEB-INF\lib\druid-1.0.9.jar
  • 📄 web\WEB-INF\lib\hamcrest-core-1.3.jar
  • 📄 web\WEB-INF\lib\javax.servlet.jsp.jstl.jar
  • 📄 web\WEB-INF\lib\jstl-impl.jar
  • 📄 web\WEB-INF\lib\junit-4.12.jar
  • 📄 web\WEB-INF\lib\mysql-connector-j-8.0.33.jar
  • 📄 web\WEB-INF\lib\mysql-connector-java-5.1.18-bin.jar
  • 📄 web\WEB-INF\lib\spring-beans-4.2.4.RELEASE.jar
  • 📄 web\WEB-INF\lib\spring-core-4.2.4.RELEASE.jar
  • 📄 web\WEB-INF\lib\spring-jdbc-4.2.4.RELEASE.jar
  • 📄 web\WEB-INF\lib\spring-tx-4.2.4.RELEASE.jar

http://www.dtcms.com/a/362204.html

相关文章:

  • (Mysql)MVCC、Redo Log 与 Undo Log
  • C#知识学习-012(修饰符)
  • Python OpenCV图像处理与深度学习:Python OpenCV边缘检测入门
  • FastLED库完全指南:打造炫酷LED灯光效果
  • 【Excel】将一个单元格内​​的多行文本,​​拆分成多个单元格,每个单元格一行​​
  • 【设计模式】--重点知识点总结
  • C++ Bellman-Ford算法
  • Linux并发与竞争实验
  • 软件使用教程(四):Jupyter Notebook 终极使用指南
  • 数据分析编程第八步:文本处理
  • 设计模式-状态模式 Java
  • 华清远见25072班I/O学习day2
  • PostgreSQL备份指南:逻辑与物理备份详解
  • 椭圆曲线群运算与困难问题
  • 【数据分享】多份土地利用矢量shp数据分享-澳门
  • AI产品经理面试宝典第81天:RAG系统架构演进与面试核心要点解析
  • Qt中的信号与槽机制的主要优点
  • 自动化测试时,chrome浏览器启动后闪退的问题
  • 【趣味阅读】Python 文件头的秘密:从编码声明到 Shebang
  • VisionProC#联合编程相机实战开发
  • 【云存储桶安全】怎么满足业务需求,又最大程度上满足信息安全要求呢?
  • 1792. 最大平均通过率
  • 学习:uniapp全栈微信小程序vue3后台-暂时停更
  • 本地没有公网ip?用cloudflare部署内网穿透服务器,随时随地用自定义域名访问自己应用端口资源
  • 液态神经网络:智能制造的新引擎
  • 【跨境电商】上中下游解释,以宠物行业为例
  • 洛谷 c++ P1177 【模板】排序 题解
  • AutoSar RTE介绍
  • 特征增强方法【特征构建】
  • MVC、三层架构