irpas技术客

JSP+Servlet+MySql超市管理系统项目源码_若晨℡_jsp超市管理系统代码

网络投稿 6048

一、 开发背景

软件名称:超市管理系统(servlet+jsp)

使用对象:学习或了解过 java 基础课程,开始接触 javaWeb 的学生和软件爱好者

源码链接https://pan.baidu.com/s/1ry4obes-WWmR-v9v20SOnw?pwd=2580

提取码 2580

二、 需求分析

该超市管理系统,设置了登录权限验证,所有用户除了访问首页浏览商品外,均需输入账号、密码登录进入系统;

三、开发环境 系统环境:Windows10开发工具:IDEAJava版本:JDK 11服务器:tomcat 9.0数据库:MySQL 8.0.15系统采用技术:Servlet+Jsp+Jdbc+jQuery+Ajax+面向接口编程 四、运行效果

五、开发流程

新建工程目录结构

?BillDaodao层 package com.chen.dao.Bill;/* * 操作数据库的 */ import com.chen.pojo.Bill; import java.sql.Connection; import java.sql.SQLException; import java.util.List; public interface BillDao { //根据 商品名称、供应商id、是否付款 查询订单总数 public abstract int getBillCount(Connection conn,String queryProductName,int queryProviderId,int queryIsPayment)throws SQLException; //根据 商品名称、供应商id、是否付款 查询订单列表 public abstract List<Bill> getBillList(Connection conn,String queryProductName,int queryProviderId,int queryIsPayment, int currentPageNo, int pageSize) throws SQLException; //添加订单 public abstract boolean addBill(Connection conn,Bill bill)throws SQLException; //删除订单 public abstract boolean deleteBill(Connection conn,int billId)throws SQLException; //根据订单id 获取订单信息 public abstract Bill findByBillId(Connection conn,int billId)throws SQLException; //修改订单信息 public abstract boolean modifyBill(Connection conn,int billId,Bill bill)throws SQLException; } dao层BillDaoImpl? package com.chen.dao.Bill;/* */ import com.chen.dao.BaseDao; import com.chen.pojo.Bill; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class BillDaoImpl implements BillDao{ //根据 商品名称、供应商id、是否付款 查询订单总数 @Override public int getBillCount(Connection conn, String queryProductName, int queryProviderId, int queryIsPayment) throws SQLException { PreparedStatement pstm = null; ResultSet rs = null; int count = 0; if(conn != null){ StringBuffer sql = new StringBuffer(); sql.append("select count(1) as count from smbms_bill b,smbms_provider p where b.providerId = p.id"); List<Object> paramsList = new ArrayList<>(); if(queryProductName != "") { sql.append(" and productName like ?"); paramsList.add("%"+queryProductName+"%"); } if(queryProviderId != 0){ sql.append(" and providerId = ?"); paramsList.add(queryProviderId); } if(queryIsPayment != 0){ sql.append(" and isPayment = ?"); paramsList.add(queryIsPayment); } Object[] params = paramsList.toArray(); rs = BaseDao.executeQuery(conn, sql.toString(), pstm, params, rs); //遍历结果集 从结果集中取出数量count if (rs.next()){ count = rs.getInt("count"); } //关闭资源 BaseDao.closeResource(null,pstm,rs); } return count; } //根据 商品名称、供应商id、是否付款 查询订单列表 @Override public List<Bill> getBillList(Connection conn, String queryProductName, int queryProviderId, int queryIsPayment, int currentPageNo, int pageSize) throws SQLException { PreparedStatement pstm = null; ResultSet rs = null; List<Bill> bills = new ArrayList<>(); if(conn != null){ System.out.println("enter BillDaoImpl..."); //动态拼接字符串 StringBuffer sql = new StringBuffer(); //参数列表 ArrayList<Object> paramsList = new ArrayList<>(); sql.append("select b.*,p.proName as proName from smbms_bill b,smbms_provider p where b.providerId = p.id"); if(queryProductName != "" && queryProviderId != 0 && queryIsPayment != 0){ //说明三个参数都不为空 sql.append(" and productName like ? and providerId = ? and isPayment = ?"); paramsList.add("%"+queryProductName+"%"); try { paramsList.add(queryProviderId); paramsList.add(queryIsPayment); }catch (Exception e){ e.printStackTrace(); } }else if(queryProductName != "" || queryProviderId != 0 || queryIsPayment != 0){ //说明三个参数有些不为空 if(queryProductName != ""){ sql.append(" and productName like ?"); paramsList.add("%"+queryProductName+"%"); } if(queryProviderId != 0){ sql.append(" and providerId = ?"); paramsList.add(queryProviderId); } if(queryIsPayment != 0){ sql.append(" and isPayment = ?"); paramsList.add(queryIsPayment); } } //在数据库中 分页使用limit startIndex,pageSize 总数 //当前页 = (当前页-1)*页面大小 sql.append(" order by b.creationDate DESC limit ?,?"); currentPageNo = (currentPageNo-1)*pageSize; paramsList.add(currentPageNo); paramsList.add(pageSize); //sql拼接完成 参数列表也正确 System.out.println("Test SQL --> "+sql.toString()); //将参数列表进行转换 Object[] params = paramsList.toArray(); //执行sql rs = BaseDao.executeQuery(conn, sql.toString(), pstm, params, rs); //遍历结果集 封装对象 添加到列表 while (rs.next()){ Bill bill = new Bill(); bill.setId(rs.getInt("id")); bill.setBillCode(rs.getString("billCode")); bill.setProductName(rs.getString("productName")); bill.setProductDesc(rs.getString("productDesc")); bill.setProductUnit(rs.getString("productUnit")); bill.setProductCount(rs.getBigDecimal("productCount")); bill.setTotalPrice(rs.getBigDecimal("totalPrice")); bill.setIsPayment(rs.getInt("isPayment")); bill.setCreatedBy(rs.getInt("createdBy")); bill.setCreationDate(rs.getTimestamp("creationDate")); bill.setModifyBy(rs.getInt("modifyBy")); bill.setModifyDate(rs.getTimestamp("modifyDate")); bill.setProviderId(rs.getInt("providerId")); bill.setProviderName(rs.getString("proName")); bills.add(bill); } //关闭资源 BaseDao.closeResource(null,pstm,rs); } //返回列表 return bills; } //添加订单 @Override public boolean addBill(Connection conn, Bill bill) throws SQLException { PreparedStatement pstm = null; boolean flag = false; if (conn != null){ String sql = "insert into smbms_bill (billCode,productName,productDesc,productUnit,productCount,totalPrice,isPayment,createdBy,creationDate,modifyBy,modifyDate,providerId)values(?,?,?,?,?,?,?,?,?,?,?,?)" ; Object[] params = {bill.getBillCode(),bill.getProductName(),bill.getProductDesc(),bill.getProductUnit(),bill.getProductCount(),bill.getTotalPrice(),bill.getIsPayment(),bill.getCreatedBy(),bill.getCreationDate(),bill.getModifyBy(),bill.getModifyDate(),bill.getProviderId()}; int updateRows = BaseDao.execute(conn, sql, pstm, params); if(updateRows > 0){ flag = true; } BaseDao.closeResource(null,pstm,null); } return flag; } //删除订单 @Override public boolean deleteBill(Connection conn, int billId) throws SQLException { PreparedStatement pstm = null; boolean flag = false; if(conn != null){ String sql = "delete from smbms_bill where id = ?"; Object[] params = {billId}; int updateRows = BaseDao.execute(conn, sql, pstm, params); if(updateRows > 0){ flag = true; } BaseDao.closeResource(null,pstm,null); } return flag; } //根据订单id 获取订单信息 @Override public Bill findByBillId(Connection conn, int billId) throws SQLException { PreparedStatement pstm = null; ResultSet rs = null; Bill bill = new Bill(); if(conn != null){ String sql = "select b.*,p.proName as providerName from smbms_bill b,smbms_provider p where b.id = ? and b.providerId = p.id"; Object[] params = {billId}; rs = BaseDao.executeQuery(conn, sql, pstm, params, rs); //遍历此结果集 并存入bill对象 if(rs.next()){ bill.setBillCode(rs.getString("billCode")); bill.setProductName(rs.getString("productName")); bill.setProductDesc(rs.getString("productDesc")); bill.setProductUnit(rs.getString("productUnit")); bill.setProductCount(rs.getBigDecimal("productCount")); bill.setTotalPrice(rs.getBigDecimal("totalPrice")); bill.setIsPayment(rs.getInt("isPayment")); bill.setCreatedBy(rs.getInt("createdBy")); bill.setCreationDate(rs.getTimestamp("creationDate")); bill.setModifyBy(rs.getInt("modifyBy")); bill.setModifyDate(rs.getTimestamp("modifyDate")); bill.setProviderId(rs.getInt("providerId")); bill.setProviderName(rs.getString("providerName")); } BaseDao.closeResource(null,pstm,rs); } return bill; } //修改订单信息 @Override public boolean modifyBill(Connection conn, int billId, Bill bill) throws SQLException { PreparedStatement pstm = null; boolean flag = false; if(conn != null){ String sql = "update smbms_bill set billCode = ?,productName =?,productDesc = ?,productUnit = ?,productCount = ? ,totalPrice = ?,isPayment = ?,createdBy = ?,creationDate = ?,modifyBy = ?,modifyDate = ?,providerId = ? where id = ?"; Object[] params = {bill.getBillCode(),bill.getProductName(),bill.getProductDesc(),bill.getProductUnit(),bill.getProductCount(),bill.getTotalPrice(),bill.getIsPayment(),bill.getCreatedBy(),bill.getCreationDate(),bill.getModifyBy(),bill.getModifyDate(),bill.getProviderId(),billId}; int updateRows = BaseDao.execute(conn, sql, pstm, params); if (updateRows > 0) { flag = true; } BaseDao.closeResource(null,pstm,null); } return flag; } } dao.Provider.ProviderDao? package com.chen.dao.Provider;/* */ import com.chen.pojo.Provider; import java.sql.Connection; import java.sql.SQLException; import java.util.List; public interface ProviderDao { //根据供应商编码 或 供应商名称 查询供应商总数 public abstract int getProviderCounts(Connection conn,String queryProCode,String queryProName)throws SQLException; //查询供应商数据列表 public abstract List<Provider> getProviderList(Connection conn,String ProCode,String ProName,int currentPageNo, int pageSize)throws SQLException; //添加供应商的方法 public abstract boolean addProvider(Connection conn,Provider provider)throws SQLException; //删除供应商的方法 public abstract boolean deleteProvider(Connection conn,int providerId)throws SQLException; //根据供应商id查询供应商信息的方法 public abstract Provider findById(Connection conn,int providerId)throws SQLException; //修改供应商信息方法 public abstract boolean modifyProvider(Connection conn,int id,Provider provider)throws SQLException; }

com.chen.dao.Role.RoleDao

package com.chen.dao.Role;/* */ import com.chen.pojo.Role; import java.sql.Connection; import java.sql.SQLException; import java.util.List; public interface RoleDao { //获取角色列表 public abstract List<Role> getRoleList(Connection conn)throws SQLException; }

com.chen.dao.Role.RoleDaoImpl

package com.chen.dao.Role;/* */ import com.chen.dao.BaseDao; import com.chen.pojo.Role; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class RoleDaoImpl implements RoleDao { //获取角色列表 @Override public List<Role> getRoleList(Connection conn) throws SQLException { PreparedStatement pstm = null; ResultSet rs = null; ArrayList<Role> roles = new ArrayList<>(); if(conn != null){ String sql = "select * from smbms_role"; Object[] params = {}; rs = BaseDao.executeQuery(conn, sql, pstm, params, rs); while(rs.next()){ Role role = new Role(); role.setId(rs.getInt("id")); role.setRoleName(rs.getString("roleName")); role.setRoleCode(rs.getString("roleCode")); roles.add(role); } } BaseDao.closeResource(null,pstm,rs); return roles; } }

?com.chen.dao.User.UserDao

package com.chen.dao.User;/* */ import com.chen.pojo.User; import java.sql.Connection; import java.sql.SQLException; import java.util.List; //登录 判断 的接口 public interface UserDao { //得到要登录的用户信息 public abstract User getLoginInfo(Connection conn,String userCode) throws SQLException; //修改密码 public abstract int updatePassword(Connection conn,int id,String newPsd)throws SQLException; //根据用户名 或 角色 查询用户总数 public abstract int getUserCounts(Connection conn,String username,int userRole)throws SQLException; //根据条件 查询 获取用户列表 userList public abstract List<User> getUserList(Connection conn,String username,int userRole,int currentPageNo,int pageSize)throws SQLException; //用户管理模块中的 子模块—— 添加用户 public abstract int addUser(Connection conn,User user)throws SQLException; //用户管理模块中的子模块 —— 删除用户 public abstract boolean deleteUser(Connection conn,int userId)throws SQLException; //根据用户id 查询用户信息 public abstract User findById(Connection conn,int userId)throws SQLException; //用户管理模块中的子模块 —— 更改用户信息 public abstract boolean modify(Connection conn,int id,User user)throws SQLException; }

com.chen.dao.User.UserDaoImpl

package com.chen.dao.User;/* */ import com.chen.dao.BaseDao; import com.chen.pojo.User; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; //登录 判断 的实现类 public class UserDaoImpl implements UserDao { @Override //得到要登录的用户信息 public User getLoginInfo(Connection conn, String userCode) throws SQLException { PreparedStatement preparedStatement = null; ResultSet rs = null; User user = null; //如果连数据库都没连接就无需判断了 if(conn!=null){ //编写sql语句预编译sql String sql = "select * from smbms_user where userCode = ?"; //存放参数 Object[] params = {userCode}; //使用预处理对象调用 操作数据库的公共类 的执行 sql查询语句 rs = BaseDao.executeQuery(conn, sql, preparedStatement, params,rs); //遍历结果集 封装到一个用户中 if(rs.next()){ user = new User(); user.setId(rs.getInt("id")); user.setUserCode(rs.getString("userCode")); user.setUserName(rs.getString("userName")); user.setUserPassword(rs.getString("userPassword")); user.setGender(rs.getInt("gender")); user.setBirthday(rs.getDate("birthday")); user.setPhone(rs.getString("phone")); user.setAddress(rs.getString("address")); user.setUserRole(rs.getInt("userRole")); user.setCreatedBy(rs.getInt("createdBy")); user.setCreateDate(rs.getTimestamp("creationDate")); user.setModifyBy(rs.getInt("modifyBy")); user.setModifyDate(rs.getTimestamp("modifyDate")); } //调用 操作数据库的公共类 的执行 释放资源 BaseDao.closeResource(null,preparedStatement,rs); } //返回一个用户 return user; } //修改当前用户密码 @Override public int updatePassword(Connection conn, int id, String newPsd) throws SQLException { PreparedStatement pstm = null; int result = 0; if (conn != null) { String sql = "update smbms_user set userPassword = ? where id = ?"; Object params[] = {newPsd,id}; result = BaseDao.execute(conn, sql, pstm, params); BaseDao.closeResource(null,pstm,null); } return result; } //根据用户名 或 角色 查询用户总数 @Override public int getUserCounts(Connection conn, String username, int userRole) throws SQLException { PreparedStatement pstm = null; ResultSet rs = null; int count = 0; if(conn!=null){ //SQL语句因为联合多表查询 所以需要拼接 StringBuffer sql = new StringBuffer(); //默认两表联合 查询总条数 sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id"); //建一个集合来存储参数 ArrayList<Object> list = new ArrayList<>(); if(username!=null){ sql.append(" and u.userName like ?"); list.add("%"+username+"%");//默认下标为0 } if(userRole>0 & userRole<4){ sql.append(" and u.userRole = ?"); list.add(userRole);//默认下标为1 } //把list转换为数组 Object[] arrays = list.toArray(); System.out.println("拼接的sql语句:"+sql.toString()); //执行sql语句 rs = BaseDao.executeQuery(conn, sql.toString(), pstm, arrays, rs); //遍历结果集 if(rs.next()){ //从结果集中获取数量 count = rs.getInt("count"); } //最终关闭资源连接 BaseDao.closeResource(null,pstm,rs); } return count; } //根据条件 查询 获取用户列表 userlist @Override public List<User> getUserList(Connection conn, String username, int userRole, int currentPageNo, int pageSize) throws SQLException { PreparedStatement pstm = null; ResultSet rs = null; List<User> userList = new ArrayList<User>(); if(conn!=null){ //SQL语句因为联合多表查询 所以需要拼接 StringBuffer sql = new StringBuffer(); //默认两表联合 查询总条数 sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id"); //建一个集合来存储参数 List<Object> list = new ArrayList<>(); if(username!=null){ sql.append(" and u.userName like ?"); list.add("%"+username+"%");//默认下标为0 } if(userRole>0 & userRole<4){ sql.append(" and u.userRole = ?"); list.add(userRole);//默认下标为1 } //在数据库中 分页使用limit startIndex,pageSize 总数 //当前页 = (当前页-1)*页面大小 sql.append(" order by u.creationDate DESC limit ?,?"); currentPageNo = (currentPageNo-1)*pageSize; list.add(currentPageNo); list.add(pageSize); Object[] params = list.toArray(); System.out.println("getUserList的语句"+sql.toString()); //执行sql rs = BaseDao.executeQuery(conn, sql.toString(), pstm, params, rs); while (rs.next()){ User user = new User(); user.setId(rs.getInt("id")); user.setUserCode(rs.getString("userCode")); user.setUserName(rs.getString("userName")); user.setGender(rs.getInt("gender")); user.setBirthday(rs.getDate("birthday")); user.setPhone(rs.getString("phone")); user.setUserRoleName(rs.getString("userRoleName")); user.setUserRole(rs.getInt("userRole")); userList.add(user); } BaseDao.closeResource(null,pstm,rs); } return userList; } //用户管理模块中的 子模块—— 添加用户 public int addUser(Connection conn,User user)throws SQLException{ PreparedStatement pstm = null; int updateRows = 0; if(conn != null){ String sql = "insert into smbms_user (userCode,userName,userPassword,gender,birthday,phone,address,userRole,createdBy,creationDate)values(?,?,?,?,?,?,?,?,?,?)"; Object[] params ={user.getUserCode(),user.getUserName(),user.getUserPassword(),user.getGender(),user.getBirthday(),user.getPhone(),user.getAddress(),user.getUserRole(),user.getCreatedBy(),user.getCreateDate()}; //执行sql 返回执行结果(成功的语句数量) updateRows= BaseDao.execute(conn,sql,pstm,params); //释放资源 BaseDao.closeResource(null,pstm,null); } return updateRows; } //用户管理模块中的子模块 —— 删除用户 @Override public boolean deleteUser(Connection conn, int userCode)throws SQLException { PreparedStatement pstm = null; boolean flag = false; if(conn != null){ String sql = "delete from smbms_user where id = ?"; Object[] params = {userCode}; //执行sql 返回执行结果(成功的语句数量) int updateRows= BaseDao.execute(conn,sql,pstm,params); if(updateRows>0){ flag = true; } //释放资源 BaseDao.closeResource(null,pstm,null); } return flag; } //根据用户 id查询用户信息 @Override public User findById(Connection conn, int userId) throws SQLException { User user = null; PreparedStatement pstm = null; ResultSet rs = null; if(conn != null){ String sql = "select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.id = ? and u.userRole = r.id"; Object[] params ={userId}; rs = BaseDao.executeQuery(conn, sql, pstm, params, rs); if(rs.next()){ user = new User(); user.setId(rs.getInt("id")); user.setUserCode(rs.getString("userCode")); user.setUserName(rs.getString("userName")); user.setUserPassword(rs.getString("userPassword")); user.setGender(rs.getInt("gender")); user.setBirthday(rs.getDate("birthday")); user.setPhone(rs.getString("phone")); user.setAddress(rs.getString("address")); user.setUserRole(rs.getInt("userRole")); user.setCreatedBy(rs.getInt("createdBy")); user.setCreateDate(rs.getTimestamp("creationDate")); user.setModifyBy(rs.getInt("modifyBy")); user.setModifyDate(rs.getTimestamp("modifyDate")); user.setUserRoleName(rs.getString("userRoleName")); } //释放资源 BaseDao.closeResource(null,pstm,rs); } return user; } //用户管理模块中的子模块 —— 更改用户信息 @Override public boolean modify(Connection conn, int id,User user) throws SQLException { boolean flag = false; PreparedStatement pstm = null; if(conn != null){ //编写sql语句 String sql = "update smbms_user set userName = ?,gender = ?,birthday =?,phone = ?,address = ?,userRole = ?,modifyBy = ?,modifyDate = ? where id = ?"; Object[] params = {user.getUserName(),user.getGender(),user.getBirthday(),user.getPhone(),user.getAddress(),user.getUserRole(),user.getModifyBy(),user.getModifyDate(),id}; //执行sql语句 int updateRows = BaseDao.execute(conn, sql, pstm, params); if(updateRows>0){ flag = true; } //释放连接 BaseDao.closeResource(null,pstm,null); } return flag; } }

com.chen.dao.BaseDao

package com.chen.dao;/* * 操作数据库的公共类 */ import java.io.IOException; import java.io.InputStream; import java.sql.*; import java.util.Properties; public class BaseDao { private static String driver; private static String url; private static String username; private static String password; //静态代码块 类加载的时候初始化 static { Properties properties = new Properties(); //通过类加载器读取对应的资源 反射 InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties"); //properties读取文件内容 try { properties.load(is);//加载这个流 } catch (IOException e) { e.printStackTrace(); } driver = properties.getProperty("driver"); url = properties.getProperty("url"); username = properties.getProperty("username"); password = properties.getProperty("password"); } //获取数据库的连接 public static Connection getConnection(){ Connection conn = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, username, password); } catch (Exception e) { e.printStackTrace(); } return conn; } //编写查询公共方法 public static ResultSet executeQuery(Connection conn,String sql,PreparedStatement preparedStatement,Object[] params,ResultSet resultSet) throws SQLException { //预编译的sql在后面直接执行即可 preparedStatement = conn.prepareStatement(sql); for (int i = 0; i < params.length; i++) { //setObject 占位符从1开始 而数字从0开始 preparedStatement.setObject(i+1,params[i]); } resultSet = preparedStatement.executeQuery();//ResultSet,数据库结果集的数据表,通常通过执行查询数据库的语句生成。g return resultSet; } //编写增删改查公共方法 public static int execute(Connection conn,String sql,PreparedStatement preparedStatement,Object[] params) throws SQLException { //预编译的sql在后面直接执行即可 int updateRow; preparedStatement = conn.prepareStatement(sql); for (int i = 0; i < params.length; i++) { //setObject 占位符从1开始 而数字从0开始 preparedStatement.setObject(i+1,params[i]); } updateRow = preparedStatement.executeUpdate(); return updateRow; } //释放资源 public static boolean closeResource(Connection conn,PreparedStatement preparedStatement,ResultSet resultSet){ boolean flag = true; if(conn!=null){ try { conn.close(); //GC回收 conn = null; } catch (SQLException e) { e.printStackTrace(); flag = false; } } if(preparedStatement!=null){ try { preparedStatement.close(); //GC回收 preparedStatement = null; } catch (SQLException e) { e.printStackTrace(); flag = false; } } if(resultSet!=null){ try { resultSet.close(); //GC回收 resultSet = null; } catch (SQLException e) { e.printStackTrace(); flag = false; } } return flag; } }

com.chen.filter.CharacterEncodingFilter

package com.chen.filter;/* * */ import javax.servlet.*; import java.io.IOException; public class CharacterEncodingFilter implements Filter { @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { servletRequest.setCharacterEncoding("utf-8"); servletResponse.setCharacterEncoding("utf-8"); filterChain.doFilter(servletRequest,servletResponse); } @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void destroy() { } }

package com.chen.filter. LoginFilter

package com.chen.filter;/* * */ import com.chen.pojo.User; import com.chen.util.Constants; import javax.servlet.*; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class LoginFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest request = (HttpServletRequest) servletRequest; HttpServletResponse response = (HttpServletResponse) servletResponse; User user = (User) request.getSession().getAttribute(Constants.USER_SESSION); //过滤器 从session中获取用户 判断是否登录 if (user == null) { //证明未登录 或 已注销 response.sendRedirect(request.getContextPath()+"/error.jsp"); }else{ filterChain.doFilter(request,response); } } @Override public void destroy() { } }

com.chen.pojo.Bill

public class Bill { private Integer id; //id private String billCode; //账单编码 private String productName; //商品名称 private String productDesc; //商品描述 private String productUnit; //商品单位 private BigDecimal productCount; //商品数量 private BigDecimal totalPrice; //总金额 private Integer isPayment; //是否支付 private Integer providerId; //供应商ID private Integer createdBy; //创建者 private Date creationDate; //创建时间 private Integer modifyBy; //更新者 private Date modifyDate;//更新时间 private String providerName;//供应商名称 public String getProviderName() { return providerName; } public void setProviderName(String providerName) { this.providerName = providerName; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getBillCode() { return billCode; } public void setBillCode(String billCode) { this.billCode = billCode; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } public String getProductDesc() { return productDesc; } public void setProductDesc(String productDesc) { this.productDesc = productDesc; } public String getProductUnit() { return productUnit; } public void setProductUnit(String productUnit) { this.productUnit = productUnit; } public BigDecimal getProductCount() { return productCount; } public void setProductCount(BigDecimal productCount) { this.productCount = productCount; } public BigDecimal getTotalPrice() { return totalPrice; } public void setTotalPrice(BigDecimal totalPrice) { this.totalPrice = totalPrice; } public Integer getIsPayment() { return isPayment; } public void setIsPayment(Integer isPayment) { this.isPayment = isPayment; } public Integer getProviderId() { return providerId; } public void setProviderId(Integer providerId) { this.providerId = providerId; } public Integer getCreatedBy() { return createdBy; } public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Integer getModifyBy() { return modifyBy; } public void setModifyBy(Integer modifyBy) { this.modifyBy = modifyBy; } public Date getModifyDate() { return modifyDate; } public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } }

com.chen.pojo.Provider

package com.chen.pojo;/* * */ import java.util.Date; public class Provider { private Integer id; //id private String proCode; //供应商编码 private String proName; //供应商名称 private String proDesc; //供应商描述 private String proContact; //供应商联系人 private String proPhone; //供应商电话 private String proAddress; //供应商地址 private String proFax; //供应商传真 private Integer createdBy; //创建者 private Date creationDate; //创建时间 private Integer modifyBy; //更新者 private Date modifyDate;//更新时间 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getProCode() { return proCode; } public void setProCode(String proCode) { this.proCode = proCode; } public String getProName() { return proName; } public void setProName(String proName) { this.proName = proName; } public String getProDesc() { return proDesc; } public void setProDesc(String proDesc) { this.proDesc = proDesc; } public String getProContact() { return proContact; } public void setProContact(String proContact) { this.proContact = proContact; } public String getProPhone() { return proPhone; } public void setProPhone(String proPhone) { this.proPhone = proPhone; } public String getProAddress() { return proAddress; } public void setProAddress(String proAddress) { this.proAddress = proAddress; } public String getProFax() { return proFax; } public void setProFax(String proFax) { this.proFax = proFax; } public Integer getCreatedBy() { return createdBy; } public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Integer getModifyBy() { return modifyBy; } public void setModifyBy(Integer modifyBy) { this.modifyBy = modifyBy; } public Date getModifyDate() { return modifyDate; } public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } }

com.chen.pojo.Role

package com.chen.pojo; import java.util.Date; public class Role { private Integer id; //id private String roleCode; //角色编码 private String roleName; //角色名称 private Integer createdBy; //创建者 private Date creationDate; //创建时间 private Integer modifyBy; //更新者 private Date modifyDate;//更新时间 public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getRoleCode() { return roleCode; } public void setRoleCode(String roleCode) { this.roleCode = roleCode; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public Integer getCreatedBy() { return createdBy; } public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } public Date getCreationDate() { return creationDate; } public void setCreationDate(Date creationDate) { this.creationDate = creationDate; } public Integer getModifyBy() { return modifyBy; } public void setModifyBy(Integer modifyBy) { this.modifyBy = modifyBy; } public Date getModifyDate() { return modifyDate; } public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } }

com.chen.pojo.User

package com.chen.pojo;/* */ import java.util.Date; public class User { private Integer id; private String userCode; //用户编码 private String userName; private String userPassword; private Integer gender; private Date birthday; private String phone; private String address; private Integer userRole; private Integer createdBy; //创建者 private Date createDate; private Integer modifyBy; //更新者 private Date modifyDate; //更新时间 private Integer age; //年龄 private String userRoleName; //用户角色名称 public Integer getAge() { Date date = new Date(); Integer age = date.getYear()-birthday.getYear(); return age; } public void setAge(Integer age) { this.age = age; } public String getUserRoleName() { return userRoleName; } public void setUserRoleName(String userRoleName) { this.userRoleName = userRoleName; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public Integer getGender() { return gender; } public void setGender(Integer gender) { this.gender = gender; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public Integer getUserRole() { return userRole; } public void setUserRole(Integer userRole) { this.userRole = userRole; } public Integer getCreatedBy() { return createdBy; } public void setCreatedBy(Integer createdBy) { this.createdBy = createdBy; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Integer getModifyBy() { return modifyBy; } public void setModifyBy(Integer modifyBy) { this.modifyBy = modifyBy; } public Date getModifyDate() { return modifyDate; } public void setModifyDate(Date modifyDate) { this.modifyDate = modifyDate; } }

com.chen.service.Bill. BillService

package com.chen.service.Bill;/* * 业务层 */ import com.chen.pojo.Bill; import java.sql.SQLException; import java.util.List; public interface BillService { //根据 商品名称、供应商id、是否付款 查询订单总数 public abstract int getBillCount(String queryProductName, int queryProviderId, int queryIsPayment) throws SQLException; //根据 商品名称、供应商id、是否付款 查询订单列表 public abstract List<Bill> getBillList(String queryProductName, int queryProviderId, int queryIsPayment, int currentPageNo, int pageSize) throws SQLException; //添加订单 public abstract boolean addBill(Bill bill); //删除订单 public abstract boolean deleteBill(int billId); //根据订单id 获取订单信息 public abstract Bill findByBillId(int billId)throws SQLException; //修改订单信息 public abstract boolean modifyBill(int billId, Bill bill)throws SQLException; }

com.chen.service.Bill.BillServiceImpl

package com.chen.service.Bill;/* * */ import com.chen.dao.BaseDao; import com.chen.dao.Bill.BillDaoImpl; import com.chen.pojo.Bill; import java.sql.Connection; import java.sql.SQLException; import java.util.List; public class BillServiceImpl implements BillService { private BillDaoImpl billDao; public BillServiceImpl(){ this.billDao = new BillDaoImpl(); } //根据 商品名称、供应商id、是否付款 查询订单总数 @Override public int getBillCount(String queryProductName, int queryProviderId, int queryIsPayment) { Connection conn = null; int billCount = 0; try { conn = BaseDao.getConnection(); conn.setAutoCommit(false); billCount = billDao.getBillCount(conn, queryProductName, queryProviderId, queryIsPayment); conn.commit(); }catch (Exception e){ e.printStackTrace(); conn.rollback(); }finally { BaseDao.closeResource(conn,null,null); return billCount; } } //根据 商品名称、供应商id、是否付款 查询订单列表 @Override public List<Bill> getBillList(String queryProductName, int queryProviderId, int queryIsPayment, int currentPageNo, int pageSize) { Connection conn = null; List<Bill> billList = null; try { conn = BaseDao.getConnection(); conn.setAutoCommit(false); System.out.println("enter BillServiceImpl..."); billList = billDao.getBillList(conn, queryProductName, queryProviderId, queryIsPayment,currentPageNo,pageSize); conn.commit(); }catch (Exception e){ e.printStackTrace(); conn.rollback(); }finally { BaseDao.closeResource(conn,null,null); return billList; } } //添加订单 @Override public boolean addBill(Bill bill) { boolean flag = false; Connection conn = null; try { conn = BaseDao.getConnection(); conn.setAutoCommit(false); flag = billDao.addBill(conn, bill); conn.commit(); }catch (Exception e){ e.printStackTrace(); conn.rollback(); }finally { BaseDao.closeResource(conn,null,null); return flag; } } //删除订单 @Override public boolean deleteBill(int billId) { boolean flag = false; Connection conn = null; try { conn = BaseDao.getConnection(); conn.setAutoCommit(false); flag = billDao.deleteBill(conn, billId); conn.commit(); } catch (SQLException e) { e.printStackTrace(); conn.rollback(); }finally { BaseDao.closeResource(conn,null,null); return flag; } } //根据订单id 获取订单信息 @Override public Bill findByBillId(int billId){ Connection conn = null; Bill bill = null; try { conn = BaseDao.getConnection(); conn.setAutoCommit(false); bill = billDao.findByBillId(conn, billId); }catch (Exception e){ e.printStackTrace(); conn.rollback(); }finally { BaseDao.closeResource(conn,null,null); return bill; } } //修改订单信息 @Override public boolean modifyBill(int billId, Bill bill) { boolean flag = false; Connection conn = null; try { conn = BaseDao.getConnection(); conn.setAutoCommit(false); flag = billDao.modifyBill(conn, billId, bill); conn.commit(); }catch (Exception e){ e.printStackTrace(); conn.rollback(); }finally { BaseDao.closeResource(conn,null,null); return flag; } } }

com.chen.service.Provider.ProviderService

package com.chen.service.Provider;/* */ import com.chen.pojo.Provider; import java.sql.SQLException; import java.util.List; public interface ProviderService { //根据供应商编码 或 供应商名称 查询供应商总数 public abstract int getProviderCounts(String queryProCode,String queryProName)throws SQLException; //查询供应商数据列表 public abstract List<Provider> getProviderList(String ProCode, String ProName, int currentPageNo, int pageSize)throws SQLException; //添加供应商的方法 public abstract boolean addProvider(Provider provider)throws SQLException; //删除供应商的方法 public abstract boolean deleteProvider(int providerId)throws SQLException; //根据供应商id查询供应商信息的方法 public abstract Provider findById(int providerId)throws SQLException; //修改供应商信息方法 public abstract boolean modifyProvider(int id,Provider provider)throws SQLException; }

?com.chen.service.Provider. ProviderServiceImpl

package com.chen.service.Provider;/* */ import com.chen.dao.BaseDao; import com.chen.dao.Provider.ProviderDao; import com.chen.dao.Provider.ProviderDaoImpl; import com.chen.pojo.Provider; import java.sql.Connection; import java.util.List; public class ProviderServiceImpl implements ProviderService { //Service层调用dao层 private ProviderDao providerDao; public ProviderServiceImpl(){ providerDao = new ProviderDaoImpl(); } //根据供应商编码 或 供应商名称 查询供应商总数 @Override public int getProviderCounts(String queryProCode, String queryProName) { Connection conn = null; int providerCounts = 0; try { conn = BaseDao.getConnection(); conn.setAutoCommit(false); providerCounts = providerDao.getProviderCounts(conn, queryProCode, queryProName); conn.commit(); }catch (Exception e){ e.printStackTrace(); conn.rollback(); }finally { BaseDao.closeResource(conn,null,null); return providerCounts; } } @Override public List<Provider> getProviderList(String ProCode, String ProName, int currentPageNo, int pageSize) { List<Provider> providerList = null; Connection conn = null; try { conn = BaseDao.getConnection(); conn.setAutoCommit(false); providerList = providerDao.getProviderList(conn, ProCode, ProName, currentPageNo, pageSize); conn.commit(); }catch (Exception e){ e.printStackTrace(); conn.rollback(); }finally { BaseDao.closeResource(conn,null,null); return providerList; } } //添加供应商的方法 @Override public boolean addProvider(Provider provider) { Connection conn = null; boolean flag = false; try { //获取数据库连接 conn = BaseDao.getConnection(); //开启事务 conn.setAutoCommit(false); //执行方法 flag = providerDao.addProvider(conn, provider); //提交事务 conn.commit(); }catch (Exception e){ e.printStackTrace(); //事务回滚 conn.rollback(); }finally { //释放资源 BaseDao.closeResource(conn,null,null); return flag; } } //删除供应商的方法 @Override public boolean deleteProvider(int providerId) { Connection conn = null; boolean flag = false; try { conn = BaseDao.getConnection(); conn.setAutoCommit(false); flag = providerDao.deleteProvider(conn, providerId); conn.commit(); }catch (Exception e){ e.printStackTrace(); conn.rollback(); }finally { BaseDao.closeResource(conn,null,null); return flag; } } //根据供应商id查询供应商信息的方法 @Override public Provider findById(int providerId) { Connection conn = null; Provider provider = null; try { conn = BaseDao.getConnection(); conn.setAutoCommit(false); provider = providerDao.findById(conn, providerId); conn.commit(); }catch (Exception e){ e.printStackTrace(); conn.rollback(); }finally { BaseDao.closeResource(conn,null,null); return provider; } } //修改供应商信息方法 @Override public boolean modifyProvider(int id, Provider provider) { Connection conn = null; boolean flag = false; try { conn = BaseDao.getConnection(); conn.setAutoCommit(false); flag = providerDao.modifyProvider(conn, id, provider); conn.commit(); }catch (Exception e){ e.printStackTrace(); conn.rollback(); }finally { BaseDao.closeResource(conn,null,null); return flag; } } }

com.chen.service.Role.RoleService

package com.chen.service.Role;/* * *@create 2021-05-03-23:33 */ import com.chen.pojo.Role; import java.util.List; public interface RoleService { //获取角色列表 public abstract List<Role> getRoleList(); }

com.chen.service.Role.RoleServiceImpl

package com.chen.service.Role;/* */ import com.chen.dao.BaseDao; import com.chen.dao.Role.RoleDao; import com.chen.dao.Role.RoleDaoImpl; import com.chen.pojo.Role; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.List; public class RoleServiceImpl implements RoleService { //业务层调用持久层 private RoleDao roleDao = null; public RoleServiceImpl(){ this.roleDao =new RoleDaoImpl(); } @Override public List<Role> getRoleList() { Connection conn = null; List<Role> roleList = null; try { //获取数据库连接 conn = BaseDao.getConnection(); roleList = roleDao.getRoleList(conn); } catch (SQLException e) { e.printStackTrace(); }finally { BaseDao.closeResource(conn,null,null); return roleList; } } @Test public void testGetRoleList(){ RoleServiceImpl roleService = new RoleServiceImpl(); List<Role> roleList = roleService.getRoleList(); for (Role role : roleList) { System.out.println(role.getRoleName()); } } }

com.chen.service.User.UserService

package com.chen.service.User;/* * */ import com.chen.pojo.User; import java.util.List; public interface UserService { //用户登录 public abstract User login(String userCode,String passWord); //根据用户ID修改密码 public abstract boolean updatePassword(int id,String passWord); //用户管理——查询记录数 public abstract int getUserCounts(String username,int userRole); //根据条件 查询用户列表 public abstract List<User> getUserList(String QueryUserName,int QueryUserRole,int currentPageNo,int pageSize); //用户管理模块中的 子模块—— 添加用户 public abstract boolean addUser(User user); //用户管理模块中的子模块 —— 删除用户 public abstract boolean deleteUser(int userId); //根据id查询用户信息 public abstract User findById(int userId); //用户管理模块中的子模块 —— 更改用户信息 public abstract boolean modify(int id,User user); }

com.chen.service.User.UserserviceImpl

package com.chen.service.User; import com.chen.dao.BaseDao; import com.chen.dao.User.UserDao; import com.chen.dao.User.UserDaoImpl; import com.chen.pojo.User; import org.junit.Test; import java.sql.Connection; import java.sql.SQLException; import java.util.List; //用户登录的业务层实现类 public class UserServiceImpl implements UserService { //业务层肯定是调用dao层的 private UserDao userDao; public UserServiceImpl(){ userDao =new UserDaoImpl(); } @Override //(String userCode, String passWord)两个参数对应是的首页传来的值 //用户登录 public User login(String userCode, String passWord) { Connection conn = null; User user = null; try { //调用 dao层操作数据库的公共类方法 获取数据库的连接 conn = BaseDao.getConnection(); //得到连接后 开始查询 通过业务层调用具体的数据库操作 user = userDao.getLoginInfo(conn, userCode); } catch (SQLException e) { e.printStackTrace(); }finally { //关闭资源 BaseDao.closeResource(conn,null,null); } return user; } //修改密码 @Override public boolean updatePassword(int id, String passWord) { boolean flag = false; Connection conn = null; try { //获取连接 conn = BaseDao.getConnection(); //调用dao层 执行更新操作 int i = userDao.updatePassword(conn, id, passWord); if (i > 0) { flag = true; } }catch (Exception e){ e.printStackTrace(); }finally { BaseDao.closeResource(conn,null,null); return flag; } } //用户管理——查询记录数 @Override public int getUserCounts(String username, int userRole) { Connection conn = null; int userCounts = 0; try { //获取连接 conn = BaseDao.getConnection(); //执行sql语句 userCounts = userDao.getUserCounts(conn, username, userRole); }catch (SQLException e){ e.printStackTrace(); }finally { BaseDao.closeResource(conn,null,null); return userCounts; } } //根据条件 查询用户列表 @Override public List<User> getUserList(String QueryUserName, int QueryUserRole, int currentPageNo, int pageSize) { Connection conn = null; List<User> userList = null; try { //获取数据库连接 conn = BaseDao.getConnection(); //调dao层的到userList userList = userDao.getUserList(conn, QueryUserName, QueryUserRole, currentPageNo, pageSize); }catch (SQLException e){ e.printStackTrace(); }finally { BaseDao.closeResource(conn,null,null); //返回查询的用户 return userList; } } //用户管理模块中的 子模块—— 添加用户 @Override public boolean addUser(User user) { Connection conn = null; boolean flag = false; try { //获取数据库连接 conn = BaseDao.getConnection(); //开启JDBC事务管理 conn.setAutoCommit(false); //Service层调用dao层的方法添加用户 int updateRows = userDao.addUser(conn, user); conn.commit(); if(updateRows > 0){ flag = true; } } catch (SQLException e) { e.printStackTrace(); conn.rollback(); }finally { //释放连接 BaseDao.closeResource(conn,null,null); return flag; } } //用户管理模块中的子模块 —— 删除用户 @Override public boolean deleteUser(int userId) { boolean flag = false; Connection conn = null; try { //获取数据库连接 conn = BaseDao.getConnection(); //开启事务 conn.setAutoCommit(false); flag = userDao.deleteUser(conn, userId); //提交事务 conn.commit(); }catch (Exception e){ e.printStackTrace(); //事务回滚 conn.rollback(); }finally { //释放连接 BaseDao.closeResource(conn,null,null); return flag; } } //根据id查询用户信息 @Override public User findById(int userId) { User user = null; Connection conn = null; try { conn = BaseDao.getConnection(); conn.setAutoCommit(false); user = userDao.findById(conn, userId); conn.commit(); } catch (SQLException e) { e.printStackTrace(); try { conn.rollback(); } catch (SQLException ex) { ex.printStackTrace(); } }finally { BaseDao.closeResource(conn,null,null); return user; } } //用户管理模块中的子模块 —— 更改用户信息 @Override public boolean modify(int id,User user) { Connection conn = null; boolean flag = false; try { conn = BaseDao.getConnection(); //开启事务 conn.setAutoCommit(false); flag = userDao.modify(conn, id,user); //提交事务 conn.commit(); } catch (SQLException e) { e.printStackTrace(); //事务回滚 try { conn.rollback(); } catch (SQLException ex) { ex.printStackTrace(); } }finally { //释放资源 BaseDao.closeResource(conn,null,null); return flag; } } @Test public void Test(){ UserServiceImpl us = new UserServiceImpl(); User admin = us.login("CSNZ", "1"); System.out.println("管理员admin的密码:"+admin!=null?true:false); } @Test public void TestUserCounts(){ UserServiceImpl us = new UserServiceImpl(); int counts = us.getUserCounts(null, 0); System.out.println(counts); } @Test public void TestGetUserList(){ UserServiceImpl userService = new UserServiceImpl(); List<User> userList = userService.getUserList("", 1, 1, 5); for (User user : userList) { System.out.println(user); } } }

com.chen.servlet.Bill.BillServlet

package com.chen.servlet.Bill;/* * */ import com.alibaba.fastjson.JSONArray; import com.chen.pojo.Bill; import com.chen.pojo.Provider; import com.chen.pojo.User; import com.chen.service.Bill.BillServiceImpl; import com.chen.service.Provider.ProviderServiceImpl; import com.chen.util.Constants; import com.chen.util.PageSupport; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.math.BigDecimal; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; public class BillServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getParameter("method"); if(method.equals("query")){ this.query(req,resp); }else if(method.equals("getproviderlist")){ this.getproviderlist(req,resp); }else if(method.equals("add")){ this.add(req,resp); }else if(method.equals("delbill")){ this.deleteBill(req,resp); }else if(method.equals("modify")){ this.modify(req,resp); }else if(method.equals("modifysave")){ this.modifysave(req,resp); }else if(method.equals("view")){ this.viewBill(req,resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } //查询订单管理列表 public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { System.out.println("enter BillList query method..."); //从前端获取搜素信息 String queryProductName = req.getParameter("queryProductName"); String queryProviderId = req.getParameter("queryProviderId"); String queryIsPayment = req.getParameter("queryIsPayment"); int proId = 0; int isPayment = 0; //此属性在搜素按钮那 String pageIndex = req.getParameter("pageIndex"); //设置当前页 以及 每页显示的数目 int currentPageNo = 1; int pageSize = 5; /*测试*/ System.out.println("queryProductName - > "+queryProductName); System.out.println("queryProviderId - > "+queryProviderId); System.out.println("queryIsPayment - > "+queryIsPayment); //对前端传来的属性进行判断 如果为空(没输入) 则将值赋空字符串 dao层实现类判断的时候 也得根据空字符串判断 if (queryProductName == null){ queryProductName = ""; } if(queryProviderId != null ){ proId = Integer.parseInt(queryProviderId); } if(queryIsPayment != null ){ isPayment = Integer.parseInt(queryIsPayment); } if(pageIndex!=null){ currentPageNo = Integer.parseInt(pageIndex); } //Servlet层调用service层 BillServiceImpl billService = new BillServiceImpl(); //获取订单总数 分页:上一页 下一页 int totalCount = billService.getBillCount(queryProductName,proId,isPayment); //总页数支持 PageSupport pageSupport = new PageSupport(); System.out.println("当前页:"+currentPageNo); pageSupport.setCurrentPageNo(currentPageNo); pageSupport.setPageSize(pageSize); System.out.println("获取订单总数"+totalCount); pageSupport.setTotalCount(totalCount); //总共的页数 int totalPageCount = pageSupport.getTotalPageCount(); //控制首页和尾页 //如果页数小于1,就显示第一页 页数大于 最后一页就 显示最后一页 if(currentPageNo<1){ currentPageNo =1; }else if(currentPageNo>totalPageCount){ currentPageNo = totalPageCount; } //根据前端搜索框信息 查询订单列表 List<Bill> billList = billService.getBillList(queryProductName, proId, isPayment,currentPageNo,pageSize); System.out.println("Test billList -> "+billList); //将此列表存入req中 供前端展示 req.setAttribute("billList",billList); //查询供应商列表 ProviderServiceImpl providerService = new ProviderServiceImpl(); int totalNum = providerService.getProviderCounts("",""); List<Provider> providerList = providerService.getProviderList("", "", 1, totalNum); //将此供应商列表存入req中 为了使我们搜索框搜素内容不清空 req.setAttribute("providerList",providerList); req.setAttribute("queryProductName",queryProductName); req.setAttribute("queryProviderId",proId); req.setAttribute("queryIsPayment",isPayment); //分页显示数据 req.setAttribute("totalCount",totalCount); req.setAttribute("currentPageNo",currentPageNo); req.setAttribute("totalPageCount",totalPageCount); //返回前端页面查看 req.getRequestDispatcher("billlist.jsp").forward(req,resp); } //查询供应商 billadd.jsp页面中的下拉框调用 public void getproviderlist(HttpServletRequest req, HttpServletResponse resp) throws IOException { ProviderServiceImpl providerService = new ProviderServiceImpl(); int providerCounts = providerService.getProviderCounts("", ""); List<Provider> providerList = providerService.getProviderList("", "", 1, providerCounts); //将信息 发送给ajax 将此集合转换为json格式传递 resp.setContentType("application/json"); PrintWriter out = resp.getWriter(); //JSONArray 阿里巴巴的JSON工具类 用途就是:转换格式 out.write(JSONArray.toJSONString(providerList)); out.flush(); out.close(); } //添加订单 public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //从前端获取数据 并封装 Bill bill = new Bill(); bill.setBillCode(req.getParameter("billCode")); bill.setProductName(req.getParameter("productName")); bill.setProductUnit(req.getParameter("productUnit")); bill.setProductCount(BigDecimal.valueOf(Double.parseDouble(req.getParameter("productCount")))); bill.setTotalPrice(BigDecimal.valueOf(Double.parseDouble(req.getParameter("totalPrice")))); bill.setProviderId(Integer.parseInt(req.getParameter("providerId"))); bill.setIsPayment(Integer.parseInt(req.getParameter("isPayment"))); //下面是表单没有的 bill.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId()); bill.setCreationDate(new Date()); bill.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId()); bill.setModifyDate(new Date()); BillServiceImpl billService = new BillServiceImpl(); if(billService.addBill(bill)){ //如果添加成功 重定向跳转到展示订单页面 resp.sendRedirect(req.getContextPath()+"/jsp/bill.do?method=query"); }else{ //添加失败 转发到此添加页面 req.getRequestDispatcher("billadd.jsp").forward(req,resp); } } //删除订单 public void deleteBill(HttpServletRequest req, HttpServletResponse resp) throws IOException { //从前端获取要删除的订单id String billid = req.getParameter("billid"); int id = 0; //转换 try { id = Integer.parseInt(billid); }catch (Exception e){ e.printStackTrace(); id = 0; } BillServiceImpl billService = new BillServiceImpl(); //创建一个map集合 存储 删除成功和失败的信息 传递给ajax Map<Object, Object> resultMap = new HashMap<>(); if(id <= 0){ resultMap.put("delResult","notexist"); }else{ if(billService.deleteBill(id)){ System.out.println("删除订单成功..."); //删除订单成功 resultMap.put("delResult","true"); }else{ System.out.println("删除订单失败..."); resultMap.put("delResult","false"); } } //将此map集合 转换为json格式 resp.setContentType("application/json"); PrintWriter out = resp.getWriter(); //JSONArray 阿里巴巴的JSON工具类 用途就是:转换格式 out.write(JSONArray.toJSONString(resultMap)); out.flush(); out.close(); } // 要修改的订单信息 展示 public void modify(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //从前端获取要修改的订单id String billid = req.getParameter("billid"); int id = 0; try { id = Integer.parseInt(billid); }catch (Exception e){ e.printStackTrace(); id = 0; } //根据此id查询订单的信息并在修改页面展示 BillServiceImpl billService = new BillServiceImpl(); Bill bill = billService.findByBillId(id); bill.setId(id); //将此bill存入req 并转发到 billmodify.jsp页面 req.setAttribute("bill",bill); req.getRequestDispatcher("billmodify.jsp").forward(req,resp); } //修改订单信息方法 public void modifysave(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { //从前端获取要修改的订单id String billid = req.getParameter("billid"); System.out.println("从前端获取的订单id:"+billid); int id = 0; try { id = Integer.parseInt(billid); }catch (Exception e){ e.printStackTrace(); id = 0; } //根据id查询旧订单信息 BillServiceImpl billService = new BillServiceImpl(); Bill bill = billService.findByBillId(id); //根据修改的信息 修改对应的订单 bill.setBillCode(req.getParameter("billCode")); bill.setProductName(req.getParameter("productName")); bill.setProductUnit(req.getParameter("productUnit")); bill.setProductCount(BigDecimal.valueOf(Double.parseDouble(req.getParameter("productCount")))); bill.setTotalPrice(BigDecimal.valueOf(Double.parseDouble(req.getParameter("totalPrice")))); bill.setProviderId(Integer.parseInt(req.getParameter("providerId"))); bill.setIsPayment(Integer.parseInt(req.getParameter("isPayment"))); //下面是表单未显示的 bill.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId()); bill.setModifyDate(new Date()); //执行修改语句 boolean flag = billService.modifyBill(id, bill); if(flag){ //如果修改成功 重定向到订单展示页面 resp.sendRedirect(req.getContextPath()+"/jsp/bill.do?method=query"); }else{ //修改失败 转发到此修改页面 req.getRequestDispatcher("billmodify.jsp").forward(req,resp); } } //查看 订单信息 public void viewBill(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //从前端获取要查看订单信息的id String BillId = req.getParameter("billid"); int id = 0; try { id = Integer.parseInt(BillId); }catch (ClassCastException e){ e.printStackTrace(); id = 0; } //根据id查询订单信息 BillServiceImpl billService = new BillServiceImpl(); Bill bill = billService.findByBillId(id); //将信息存入req req.setAttribute("bill",bill); //转发到billview.jsp页面 req.getRequestDispatcher("billview.jsp").forward(req,resp); } }

com.chen.servlet.Provider.ProviderServlet

package com.chen.servlet.Provider;/* * */ import com.alibaba.fastjson.JSONArray; import com.chen.pojo.Provider; import com.chen.pojo.User; import com.chen.service.Provider.ProviderServiceImpl; import com.chen.util.Constants; import com.chen.util.PageSupport; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.util.Date; import java.util.HashMap; import java.util.List; public class ProviderServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getParameter("method"); if(method.equals("query")){ this.query(req,resp); }else if(method.equals("add")){ this.add(req,resp); }else if(method.equals("delprovider")){ this.deleteProvider(req,resp); }else if(method.equals("modify")){ this.findById(req,resp); }else if(method.equals("modifyexe")){ this.modify(req,resp); }else if(method.equals("view")){ this.view(req,resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } //查询 供应商 列表的方法 public void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //从providerlist.jsp中获取传来的数据 String queryProCode = req.getParameter("queryProCode"); String queryProName = req.getParameter("queryProName"); String pageIndex = req.getParameter("pageIndex"); List<Provider> providerList = null; int currentPageNo = 1; int pageSize = 5; //还需判断前端传来的数据是否为空 if (queryProCode == null) { queryProCode = ""; } if (queryProName == null ){ queryProName = ""; } if(pageIndex!=null){ currentPageNo = Integer.parseInt(pageIndex); } ProviderServiceImpl providerService = new ProviderServiceImpl(); //获取符合条件的 信息数量 int providerCounts = providerService.getProviderCounts(queryProCode, queryProName); //总页数支持 PageSupport pageSupport = new PageSupport(); System.out.println("currentPageNo:"+currentPageNo); pageSupport.setCurrentPageNo(currentPageNo); pageSupport.setPageSize(pageSize); System.out.println("providerCounts:"+providerCounts); pageSupport.setTotalCount(providerCounts); //总共的页数 int totalPageCount = pageSupport.getTotalPageCount(); //总记录数 int totalCount = pageSupport.getTotalCount(); //获取符合条件的 信息 providerList= providerService.getProviderList(queryProCode, queryProName, currentPageNo, pageSize); //将信息存入requset 使得在前端展示 req.setAttribute("providerList",providerList); req.setAttribute("totalCount",totalCount); req.setAttribute("currentPageNo",currentPageNo); req.setAttribute("totalPageCount",totalPageCount); req.setAttribute("queryProCode",queryProCode); req.setAttribute("queryProName",queryProName); //返回前端页面展示 req.getRequestDispatcher("providerlist.jsp").forward(req,resp); } //添加 供应商方法 public void add(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { //从前端 获取供应商的信息 String proCode = req.getParameter("proCode"); String proName = req.getParameter("proName"); String proContact = req.getParameter("proContact"); String proPhone = req.getParameter("proPhone"); String proAddress = req.getParameter("proAddress"); String proFax = req.getParameter("proFax"); String proDesc = req.getParameter("proDesc"); //下面的参数自己获取 int createdBy = ((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId(); //将信息封装成一个供应商对象 Provider provider = new Provider(); provider.setProCode(proCode); provider.setProName(proName); provider.setProContact(proContact); provider.setProPhone(proPhone); provider.setProAddress(proAddress); provider.setProFax(proFax); provider.setProDesc(proDesc); provider.setCreatedBy(createdBy); provider.setCreationDate(new Date()); //调用service层方法 ProviderServiceImpl providerService = new ProviderServiceImpl(); boolean flag = providerService.addProvider(provider); //如果成功 则重定向到providerlist.jsp页面 if(flag){ resp.sendRedirect(req.getContextPath()+"/jsp/provider.do?method=query"); }else{ //失败 跳转到添加页面 req.getRequestDispatcher("provideradd.jsp").forward(req,resp); } } //删除供应商的方法 public void deleteProvider(HttpServletRequest req, HttpServletResponse resp) throws IOException { //从前端获取 要删除的供应商 的id String proid = req.getParameter("proid"); int id = 0; try { id = Integer.parseInt(proid); }catch (Exception e){ e.printStackTrace(); id = 0; } //将信息存入一个map集合中 传给ajax HashMap<Object, Object> resultMap = new HashMap<>(); if(id<=0){ resultMap.put("delResult","notexist"); }else{ ProviderServiceImpl providerService = new ProviderServiceImpl(); if(providerService.deleteProvider(id)){ //如果删除成功 resultMap.put("delResult","true"); }else{ resultMap.put("delResult","false"); } } //将此map集合转换成json格式传递 resp.setContentType("application/json"); PrintWriter out = resp.getWriter(); //JSONArray 阿里巴巴的JSON工具类 用途就是:转换格式 out.write(JSONArray.toJSONString(resultMap)); out.flush(); out.close(); } //根据id查询供应商信息的方法 public void findById(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException { //从前端获取id String proid = req.getParameter("proid"); int id = 0; try { id = Integer.parseInt(proid); }catch (Exception e){ e.printStackTrace(); id = 0; } if(id>0){ ProviderServiceImpl providerService = new ProviderServiceImpl(); Provider provider = providerService.findById(id); //设置id 让修改提交时可获取 provider.setId(id); //将供应商信息存至 req req.setAttribute("provider",provider); //返回至前端展示页面 req.getRequestDispatcher("providermodify.jsp").forward(req,resp); } } //修改供应商信息方法 public void modify(HttpServletRequest req,HttpServletResponse resp) throws IOException, ServletException { System.out.println("enter modify ..."); //从前端获取 要修改的供应商的id信息 String proId = req.getParameter("proid"); System.out.println("proId : ->"+proId.toString()); int id = 0; try { id = Integer.parseInt(proId); }catch (Exception e){ e.printStackTrace(); id = 0; } //从前端获取供应商信息 String proCode = req.getParameter("proCode"); String proName = req.getParameter("proName"); String proContact = req.getParameter("proContact"); String proPhone = req.getParameter("proPhone"); String proAddress = req.getParameter("proAddress"); String proFax = req.getParameter("proFax"); String proDesc = req.getParameter("proDesc"); //封装成一个对象 Provider provider = new Provider(); provider.setProCode(proCode); provider.setProName(proName); provider.setProContact(proContact); provider.setProPhone(proPhone); provider.setProAddress(proAddress); provider.setProFax(proFax); provider.setProDesc(proDesc); //下面的参数不是由前端传来的 provider.setModifyDate(new Date()); provider.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId()); if(id>0){ //执行更改 ProviderServiceImpl providerService = new ProviderServiceImpl(); if(providerService.modifyProvider(id, provider)){ //如果修改成功 重定向到展示供应商列表页面 resp.sendRedirect(req.getContextPath()+"/jsp/provider.do?method=query"); }else{ //修改失败 转发到此修改页面 req.getRequestDispatcher("providermodify.jsp").forward(req,resp); } } } //查看 供应商信息方法 public void view(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException { //从前端获取供应商的id String proid = req.getParameter("proid"); int id = 0; try { id = Integer.parseInt(proid); }catch (Exception e){ e.printStackTrace(); id = 0 ; } //根据id查询 if(id >0){ ProviderServiceImpl providerService = new ProviderServiceImpl(); Provider provider = providerService.findById(id); //将此对象传到providerview.jsp进行展示 req.setAttribute("provider",provider); //重定向到展示页 req.getRequestDispatcher("providerview.jsp").forward(req,resp); } } }

com.chen.servlet.User.LoginServlet

package com.chen.servlet.User;/* * */ import com.chen.pojo.User; import com.chen.service.User.UserService; import com.chen.service.User.UserServiceImpl; import com.chen.util.Constants; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; //处理登录请求的servlet public class LoginServlet extends HttpServlet { //控制层 调用业务层代码 进行判断 @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取登录页面传来的信息 String userCode = req.getParameter("userCode"); String userPassword = req.getParameter("userPassword"); //和数据库中的密码进行对比,调用业务层 UserService userService = new UserServiceImpl(); //把登录的人的信息查到 User user = userService.login(userCode, userPassword); //判断 if (user == null || !user.getUserPassword().equals(userPassword)) { //查无此人 //转发回登录页面 提示 用户名或密码错误 req.setAttribute("error","用户名或密码错误"); req.getRequestDispatcher("login.jsp").forward(req,resp); }else{ //查有此人 //将用户的信息放在session中 req.getSession().setAttribute(Constants.USER_SESSION,user); //跳转到主页 resp.sendRedirect("jsp/frame.jsp"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

com.chen.servlet.User.LogoutServlet

package com.chen.servlet.User;/* */ import com.chen.util.Constants; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; public class LogoutServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //移除用户的session req.getSession().removeAttribute(Constants.USER_SESSION); //返回登录页面 resp.sendRedirect(req.getContextPath()+"/login.jsp"); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

com.chen.servlet.User.UserServlet

package com.chen.servlet.User;/* */ import com.alibaba.fastjson.JSONArray; import com.chen.pojo.Role; import com.chen.pojo.User; import com.chen.service.Role.RoleServiceImpl; import com.chen.service.User.UserServiceImpl; import com.chen.util.Constants; import com.chen.util.PageSupport; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; //实现Servlet复用 public class UserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String method = req.getParameter("method"); if(method.equals("savePwd")){ this.savePwd(req,resp); }else if(method.equals("pwdmodify")){ this.verifyPwd(req,resp); }else if(method.equals("query")){ this.query(req,resp); }else if(method.equals("add")){ this.add(req,resp); }else if(method.equals("getRoleList")){ this.getRoleList(req,resp); }else if(method.equals("ifExist")){ this.ifExist(req,resp); }else if(method.equals("deluser")){ this.deleteUser(req,resp); }else if(method.equals("modify")){ this.findById(req,resp); }else if(method.equals("modifyexe")){ this.modify(req,resp); }else if(method.equals("view")){ this.viewUser(req,resp); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } //用户修改密码方法 public void savePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //从Session中获取ID Object obj = req.getSession().getAttribute(Constants.USER_SESSION); //获取前端页面传来的新密码 String newpassword = req.getParameter("newpassword"); //先判断不为空 再比较密码是否相等 if(obj != null && newpassword != null){ User user = (User) obj; UserServiceImpl userService = new UserServiceImpl(); //修改密码并返回结果 boolean flag = userService.updatePassword(user.getId(), newpassword); //如果密码修改成功 移除当前session if(flag){ req.setAttribute("message","修改密码成功,请使用新密码登录!"); req.getSession().removeAttribute(Constants.USER_SESSION); }else{ req.setAttribute("message","密码修改失败 新密码不符合规范"); } }else{ req.setAttribute("message","新密码不能为空!"); } //修改完了 重定向到此修改页面 req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp); } //验证密码的方法 public void verifyPwd(HttpServletRequest req, HttpServletResponse resp)throws IOException{ //依旧从session中取ID Object obj = req.getSession().getAttribute(Constants.USER_SESSION); //取 前端传来的旧密码 String oldpassword = req.getParameter("oldpassword"); //将结果存放在map集合中 让Ajax使用 Map<String, String> resultMap = new HashMap<>(); //下面开始判断 键都是用result 此处匹配js中的Ajax代码 if(obj == null){ //说明session被移除了 或未登录|已注销 resultMap.put("result","sessionerror"); }else if(oldpassword == null){ //前端输入的密码为空 resultMap.put("result","error"); }else { //如果旧密码与前端传来的密码相同 if(((User)obj).getUserPassword().equals(oldpassword)){ resultMap.put("result","true"); }else{ //前端输入的密码和真实密码不相同 resultMap.put("result","false"); } } //上面已经封装好 现在需要传给Ajax 格式为json 所以我们得转换格式 resp.setContentType("application/json");//将应用的类型变成json PrintWriter writer = resp.getWriter(); //JSONArray 阿里巴巴的JSON工具类 用途就是:转换格式 writer.write(JSONArray.toJSONString(resultMap)); writer.flush(); writer.close(); } //查询用户列表的方法 public void query(HttpServletRequest req, HttpServletResponse resp){ //查询用户列表 //从前端获取数据 String queryUserName = req.getParameter("queryName"); String temp = req.getParameter("queryUserRole");//值为0 、1、2、3 String pageIndex = req.getParameter("pageIndex"); int queryUserRole = 0; //获取用户列表 UserServiceImpl userService = new UserServiceImpl(); //第一次走这个请求,一定是第一页,页面大小固定的 List<User> userList = null; int currentPageNo = 1;//当前页码 int pageSize = 5;//页数 可以把这个写到配置文件中,方便后期修改 if(queryUserName == null){ queryUserName = ""; } if(temp!=null && !temp.equals("")){ queryUserRole = Integer.parseInt(temp);//给查询赋值!0,1,2,3 } if(pageIndex!=null){ currentPageNo = Integer.parseInt(pageIndex); } //获取用户总数 分页:上一页 下一页 int totalCount = userService.getUserCounts(queryUserName, queryUserRole); //总页数支持 PageSupport pageSupport = new PageSupport(); System.out.println("当前页:"+currentPageNo); pageSupport.setCurrentPageNo(currentPageNo); pageSupport.setPageSize(pageSize); System.out.println("获取用户总数"+totalCount); pageSupport.setTotalCount(totalCount); //总共的页数 int totalPageCount = pageSupport.getTotalPageCount(); //控制首页和尾页 //如果页数小于1,就显示第一页 页数大于 最后一页就 显示最后一页 if(currentPageNo<1){ currentPageNo =1; }else if(currentPageNo>totalPageCount){//当前页面大于了最后一页 currentPageNo = totalPageCount; } System.out.println("返回UserList的数据测试"+queryUserName+":"+queryUserRole+":"+currentPageNo+":"+pageSize); //获取用户列表展示 userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize); //将数据传给前端 System.out.println(userList); // for (User user : userList) { // System.out.println(user.toString()); // } req.setAttribute("userList",userList); RoleServiceImpl roleService = new RoleServiceImpl(); //所有角色 List<Role> roleList = roleService.getRoleList(); req.setAttribute("roleList",roleList); req.setAttribute("totalCount",totalCount); req.setAttribute("currentPageNo",currentPageNo); req.setAttribute("totalPageCount",totalPageCount); req.setAttribute("queryUserName",queryUserName); req.setAttribute("queryUserRole",queryUserRole); //返回至前端 try { req.getRequestDispatcher("userlist.jsp").forward(req,resp); } catch (ServletException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } //添加用户方法 public void add(HttpServletRequest req, HttpServletResponse resp)throws IOException,ServletException { System.out.println("进入add方法"); //从前端获取数据 String addUserCode = req.getParameter("userCode"); // System.out.println("\n前端输入的:"+addUserCode+"\n"); String addUserName = req.getParameter("userName"); String addUserPassword = req.getParameter("userPassword"); String addGender = req.getParameter("gender"); String addBirthday = req.getParameter("birthday"); String addPhone = req.getParameter("phone"); String addAddress = req.getParameter("address"); String addUserRole = req.getParameter("userRole"); //对数据进行封装 User user = new User(); user.setUserCode(addUserCode); user.setUserName(addUserName); user.setUserPassword(addUserPassword); user.setGender(Integer.parseInt(addGender)); try { user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(addBirthday)); }catch (ParseException e){ e.printStackTrace(); } user.setPhone(addPhone); user.setAddress(addAddress); user.setUserRole(Integer.parseInt(addUserRole)); //注意这两个参数不在表单的填写范围内 user.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId()); user.setCreateDate(new Date()); // System.out.println("封装好的:"+user.getUserCode()); //调用service执行添加方法 UserServiceImpl userService = new UserServiceImpl(); boolean flag = userService.addUser(user); if(flag){ //说明执行成功 网页重定向到 用户管理页面(即 查询全部用户列表) resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query"); }else{ //说明 添加失败 转发到此 添加页面 req.getRequestDispatcher("useradd.jsp").forward(req,resp); } } //用户管理模块中 子模块(添加用户——表单中的用户角色下拉框) public void getRoleList(HttpServletRequest req, HttpServletResponse resp) throws IOException { List<Role> roleList = null; RoleServiceImpl roleService = new RoleServiceImpl(); List<Role> roleList1 = roleService.getRoleList(); //把roleList1 转换为json对象输出 resp.setContentType("application/json"); PrintWriter out = resp.getWriter(); out.write(JSONArray.toJSONString(roleList1)); out.flush(); out.close(); } //用户管理模块 子模块(验证用户编码是否已经存在) public void ifExist(HttpServletRequest req, HttpServletResponse resp) throws IOException { //获取前端输入 的用户编码 String userCode = req.getParameter("userCode"); //将结果存放在map集合中 让Ajax使用 Map<String, String> resultMap = new HashMap<>(); if(userCode == null || userCode.equals("")){ System.out.println("前端未填写用户编码..."); resultMap.put("userCode","NoWrite"); }else{ System.out.println("前端填写了用户编码..."); UserServiceImpl userService = new UserServiceImpl(); User isNullUser = userService.login(userCode, ""); //判断是否已经存在这个用户编码 boolean flag = isNullUser != null ? true : false; if(flag){ //用户编码存在 //将信息存入map中 resultMap.put("userCode","exist"); } } //上面已经封装好 现在需要传给Ajax 格式为json 所以我们得转换格式 resp.setContentType("application/json");//将应用的类型变成json PrintWriter writer = resp.getWriter(); //JSONArray 阿里巴巴的JSON工具类 用途就是:转换格式 writer.write(JSONArray.toJSONString(resultMap)); writer.flush(); writer.close(); } //用户管理模块中的子模块 —— 删除用户 public void deleteUser(HttpServletRequest req, HttpServletResponse resp) throws IOException { //从前端获取 要删除的用户 的信息 String userid = req.getParameter("uid"); int delId = 0; //先转换 try { delId= Integer.parseInt(userid); }catch (Exception e){ e.printStackTrace(); delId = 0; } //将结果存放在map集合中 让Ajax使用 Map<String, String> resultMap = new HashMap<>(); if(delId<=0){ resultMap.put("delResult","notexist"); }else { UserServiceImpl userService = new UserServiceImpl(); if(userService.deleteUser(delId)){ resultMap.put("delResult","true"); }else { resultMap.put("delResult", "false"); } } //上面已经封装好 现在需要传给Ajax 格式为json 所以我们得转换格式 resp.setContentType("application/json");//将应用的类型变成json PrintWriter writer = resp.getWriter(); //JSONArray 阿里巴巴的JSON工具类 用途就是:转换格式 writer.write(JSONArray.toJSONString(resultMap)); writer.flush(); writer.close(); } //用户管理模块中的功能 —— 根据id查询用户信息 public void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //从前端获取 要修改的用户 的id String uId = req.getParameter("uid"); int userId = 0; try { userId = Integer.parseInt(uId); }catch (Exception e){ e.printStackTrace(); } UserServiceImpl userService = new UserServiceImpl(); //查询要更改的用户信息 User user = userService.findById(userId); //将用户信息保存至 request中 让usermodify.jsp显示 req.setAttribute("user",user); req.getRequestDispatcher("usermodify.jsp").forward(req,resp); } //用户管理模块中的子模块 —— 更改用户信息 public void modify(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { //从前端获取 要修改的用户 的id String uId = req.getParameter("uid"); int userId = 0; try { userId = Integer.parseInt(uId); }catch (Exception e){ e.printStackTrace(); } //从修改信息的表单中封装信息 User user = new User(); user.setUserName(req.getParameter("userName")); user.setGender(Integer.parseInt(req.getParameter("gender"))); try { user.setBirthday(new SimpleDateFormat("yyyy-MM-dd").parse(req.getParameter("birthday"))); }catch (ParseException e){ e.printStackTrace(); } user.setPhone(req.getParameter("phone")); user.setAddress(req.getParameter("address")); user.setUserRole(Integer.parseInt(req.getParameter("userRole"))); //注意这两个参数不在表单的填写范围内 user.setModifyBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId()); user.setModifyDate(new Date()); UserServiceImpl userService = new UserServiceImpl(); if(userService.modify(userId,user)){ //如果执行成功了 网页重定向到 用户管理页面(即 查询全部用户列表) resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query"); }else{ //说明 添加失败 转发到此 添加页面 req.getRequestDispatcher("usermodify.jsp").forward(req,resp); } } //用户管理模块中的子模块 —— 查询用户信息 public void viewUser(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //从前端获取 要查询用户 的id String id = req.getParameter("uid"); int userId = 0; try { userId = Integer.parseInt(id); }catch (Exception e){ e.printStackTrace(); userId = 0; } //调用 根据id查询用户信息的方法 UserServiceImpl userService = new UserServiceImpl(); User user = userService.findById(userId); //将此user发送到展示前端 的页面进行展示 req.setAttribute("user",user); //跳转到前端 的展示页面 req.getRequestDispatcher("userview.jsp").forward(req,resp); } }

com.chen.util.Constants

package com.chen.util;/* * */ //常量放置处 public class Constants { public final static String USER_SESSION = "userSession"; }

com.chen.util.PageSupport

package com.chen.util;/* */ public class PageSupport { //当前页面 来自于用户输入 private int currentPageNo = 1; //总数量(表) private int totalCount = 0; //页面容量 private int pageSize = 0; //总共显示的页数 为总表数量/单页容量 +1 private int totalPageCount =1; public int getCurrentPageNo() { return currentPageNo; } public void setCurrentPageNo(int currentPageNo) { if(currentPageNo>0){ this.currentPageNo = currentPageNo; } } public int getTotalCount() { return totalCount; } public void setTotalCount(int totalCount) { if(totalCount>0){ this.totalCount = totalCount; this.setTotalPageCountByRs(); } } public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { if(pageSize>0){ this.pageSize = pageSize; } } public int getTotalPageCount() { return totalPageCount; } public void setTotalPageCount(int totalPageCount) { this.totalPageCount = totalPageCount; } public void setTotalPageCountByRs(){ if(this.totalCount % this.pageSize == 0){ this.totalPageCount = this.totalCount / this.pageSize; }else if(this.totalCount % this.pageSize > 0){ this.totalPageCount = this.totalCount / this.pageSize +1; }else{ this.totalPageCount = 0; } } }

db.properties

driver = com.mysql.cj.jdbc.Driver url =jdbc:mysql://localhost:3306/smbms?\ useUnicode=true&characterEncoding=UTF8&useSSL=false&\ serverTimezone=UTC&rewriteBatchedStatements=true username = root password = password

web.xml

<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://·piler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> </properties> <dependencies> <!-- servlet--> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>4.0.1</version> <scope>provided</scope> </dependency> <!-- jsp--> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>javax.servlet.jsp-api</artifactId> <version>2.3.3</version> </dependency> <!-- mysql--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.24</version> </dependency> <!-- JSTL表达式--> <dependency> <groupId>javax.servlet.jsp.jstl</groupId> <artifactId>jstl-api</artifactId> <version>1.2</version> </dependency> <!-- standard--> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <!-- Junit单元测试--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <!-- 阿里巴巴的fastjson:用于转换json格式--> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.61</version> </dependency> </dependencies> <!-- <build> <plugins> <plugin> <groupId></groupId> <artifactId>maven</artifactId> <version></version> <configuration> &lt;!&ndash; 对丢失web.xml检测机制进行忽略, Dynamic Web Module 3.0 工程时代不需要web.xml文件注册相关内容的,所以工程默认不生成web.xml。&ndash;&gt; <failOnMissingWebXml>false</failOnMissingWebXml> </configuration> </plugin> &lt;!&ndash;maven-war-plugin&ndash;&gt; <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.2</version> <executions> <execution> <id>default-compile</id> <phase>compile</phase> <goals> <goal>compile</goal> </goals> </execution> </executions> <configuration> &lt;!&ndash; 使用jdk1版本时使用该配置,如果要使用jdk1.8,则下面2行要修改为1.8 &ndash;&gt; <source>1.8</source> <target>1.8</target> <encoding>UTF-8</encoding> </configuration> </plugin> </plugins> </build>--> </project>


1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,会注明原创字样,如未注明都非原创,如有侵权请联系删除!;3.作者投稿可能会经我们编辑修改或补充;4.本站不提供任何储存功能只提供收集或者投稿人的网盘链接。

标签: #jsp超市管理系统代码 # #JAVA #基础课程开始接触 #JavaWeb #的学生和软件爱好者二