狂神超市订单管理系统smbms

134 阅读7分钟

超市订单管理系统**(smbms)

素材:gitee.com/git_baboben…

前端页面:

image-20230212114223777

数据库

image-20230212114354473

项目搭建准备:

1、搭建一个maven web项目

2、配置Tomcat

3、测试项目是否能够跑起来

4、导入项目依赖的jar包

jsp、Servlet、mysql驱动、jstl、stand

5、创建项目包结构

image-20230212120828873

6、编写实体类

ORM映射:表--类结构

7、编写基础公共类

  • 数据库配置文件

     driver=com.mysql.cj.jdbc.Driver
     url=jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf8
     username=root
     password=root编写数据库的公共类
    
  • 编写操作数据库公共类

     //操作数据库的公共类
     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");
     ​
             try {
                 properties.load(is);
             }catch (Exception e){
                 e.printStackTrace();
             }
             driver = properties.getProperty("driver");
             url = properties.getProperty("url");
             username = properties.getProperty("username");
             password = properties.getProperty("password");
         }
         //获取数据库的链接
         public static Connection getConnection(){
             Connection connection = null;
             try{
                 Class.forName(driver);
                 connection = DriverManager.getConnection(url, username, password);
             }catch (Exception e){
                 e.printStackTrace();
             }
             return connection;
         }
         //编写检查公共类
         public static ResultSet excute(Connection connection,String sql,Object[] params,ResultSet resultSet,PreparedStatement preparedStatement) throws SQLException {
             //预编译的sql在后面直接执行
             preparedStatement = connection.prepareStatement(sql);
             for (int i = 0; i < params.length; i++) {
                 //setObject占位符从一开始,数组从0开始所以加1
                 preparedStatement.setObject(i+1,params[i]);
             }
             resultSet = preparedStatement.executeQuery();
             return resultSet;
         }
         //编写增删改公共方法
         public static int excute(Connection connection,String sql,Object[] params,PreparedStatement preparedStatement) throws SQLException {
             preparedStatement = connection.prepareStatement(sql);
             for (int i = 0; i < params.length; i++) {
                 //setObject占位符从一开始,数组从0开始所以加1
                 preparedStatement.setObject(i+1,params[i]);
             }
             int updateRows = preparedStatement.executeUpdate(sql);
             return updateRows;
         }
         //释放资源
         public static boolean closeResource(Connection connection, PreparedStatement preparedStatement,ResultSet resultSet){
             boolean flag = true;
             if (resultSet != null){
                 try {
                     resultSet.close();
                     //GC回收
                     resultSet = null;
                 }catch (Exception e){
                     e.printStackTrace();
                     flag = false;
                 }
             }
             if (preparedStatement != null){
                 try {
                     preparedStatement.close();
                     //GC回收
                     preparedStatement= null;
                 }catch (Exception e){
                     e.printStackTrace();
                     flag = false;
                 }
             }
             if (connection != null){
                 try {
                     connection.close();
                     //GC回收
                     connection = null;
                 }catch (Exception e){
                     e.printStackTrace();
                     flag = false;
                 }
             }
             return flag;
         }
     }
    
  • 编写字符编码过滤器

     public class CharacterEncodingFilter implements Filter {
         public void init(FilterConfig filterConfig) throws ServletException {}
         public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
             request.setCharacterEncoding("utf-8");
             response.setCharacterEncoding("utf-8");
             chain.doFilter(request,response);
         }
         public void destroy() {}
     }
    

8、导入静态资源

登录功能的实现:

image-20230212154430723

1、编写前端页面

2、设置首页

 <!--    设置首页-->
     <welcome-file-list>
         <welcome-file>login.jsp</welcome-file>
     </welcome-file-list>

3、编写dao层登录用户的接口

 public interface UserDao {
     //得到登录的用户
     public User getLoginUser(Connection connection,String userCode) throws SQLException;
 }

4、编写dao接口的实现类

 public class UserDaoImpl implements UserDao {
     public User getLoginUser(Connection connection, String userCode) throws SQLException {
         PreparedStatement pstm = null;
         ResultSet rs = null;
         User user = null;
         
         if (connection != null) {
             String sql = "select * from smbms_user where userCode=?";
             Object[] params = {userCode};
             rs = BaseDao.excute(connection, pstm, rs, sql, params);
             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.setCreationDate(rs.getTimestamp("creationDate"));
                 user.setModifyBy(rs.getInt("modifyBy"));
                 user.setModifyDate(rs.getTimestamp("modifyDate"));
             }
             BaseDao.closeResource(null, pstm, rs);
         }
         return user;
     }
 }

5、业务层接口

 public interface UserService {
     //用户登录
     public User login(String userCode,String password);
 }

6、业务层实现类

 public class UserServiceImpl implements UserService{
     //业务层都会调用dao层,所以需要引入Dao层
     private UserDao userDao;
     public  UserServiceImpl(){
         userDao = new UserDaoImpl();
     }
     public User login(String userCode, String password) {
         Connection connection = null;
         User user = null;
         try {
             connection = BaseDao.getConnection();
             //通过业务调用Dao层
             user = userDao.getLoginUser(connection, userCode);
         }catch (Exception e){
             e.printStackTrace();
         }finally {
             BaseDao.closeResource(connection,null,null);
         }
         return user;
     }
 }

7、编写servlet

public class LoginServlet extends HttpServlet {
    //servlet:控制层    调用业务层代码
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        System.out.println("loginservlet...");
        //获取用户账号密码
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");
        //和数据库中的密码进行对比,调用业务层
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.login(userCode, userPassword);
        if (user!=null){//查到此人,通过登录
            //将用户信息放到session中
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            //跳转到主页
            resp.sendRedirect("jsp/frame.jsp");
        }else {//没有该用户
            //转发到登录页面
            req.setAttribute("error","用户名或者密码不正确");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }
}

8、注册servlet

    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.hwt.servlet.user.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login.do</url-pattern>
    </servlet-mapping>

9、测试访问

登录功能优化

注销功能:

移除Session,返回登录页面

public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //移除用户session(Constants.USER_SESSION)
        req.getSession().removeAttribute(Constants.USER_SESSION);
        //req.getContextPath()当前项目路径
        resp.sendRedirect(req.getContextPath()+"/login.jsp");//返回登录页面
    }
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}

注册xml

<servlet>
    <servlet-name>LogoutServlet</servlet-name>
    <servlet-class>com.hwt.servlet.user.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LogoutServlet</servlet-name>
    <url-pattern>/jsp/logout.do</url-pattern>
</servlet-mapping>

登录拦截优化:

public class SysFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {}

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) resp;
        //过滤器,从Session中获取用户
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
        if (user == null){//当前用户被移除,注销,或者当前用户未登录
            response.sendRedirect("/smbms/error.jsp");
        }else {
            chain.doFilter(req,resp);
        }
    }
    public void destroy() {}
}

web.xml

<!--    用户登录多滤器-->
    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.hwt.filter.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/jsp/*</url-pattern>
    </filter-mapping>

密码修改

  1. 导入前端素材

    <li><a href="${pageContext.request.contextPath }/jsp/pwdmodify.jsp">密码修改</a></l
    
  2. 写项目,从底层开始

  3. UserDao接口

    //修改当前用户密码
    public int updatePwd(Connection connection,int id,int password) throws SQLException;
    
  4. UserDao接口实现类

    //修改当前用户密码
    public int updatePwd(Connection connection, int id, int password) throws SQLException {
        PreparedStatement pstm = null;
        int excute = 0;
        if (connection!=null){
            String sql = "update smbms_user set userPassword = ? where id=?";
            Object params[] = {password,id};
            excute = BaseDao.excute(connection, pstm, sql, params);
            boolean b = BaseDao.closeResource(null, pstm, null);
        }
        return excute;
    }
    
  5. UserSession层

    //根据用户id修改当前用户密码
    public boolean updatePwd(int id, int pwd);
    
  6. UserSession层实现类

        public boolean updatePwd(int id, int pwd) {
            Connection connection = null;
            boolean flag = false;
            try {
                connection = BaseDao.getConnection();
                if(userDao.updatePwd(connection,id,pwd)>0){
                    flag = true;
                }
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                BaseDao.closeResource(connection,null,null);
            }
            return flag;
        }
    
  7. servlet实现复用

    @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String method = req.getParameter("method");
            if (method.equals("savepwd") && method!=null){
                this.updatePwd(req,resp);
            }
        }
        public void updatePwd(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
            //从session里面拿id
            Object o = req.getSession().getAttribute(Constants.USER_SESSION);
            String newpassword = req.getParameter("newpassword");
            boolean flag = false;
            if (o!=null && newpassword!=null && newpassword.length()!=0){
                UserService userService = new UserServiceImpl();
                flag = userService.updatePwd(((User) o).getId(), newpassword);
                if (flag){
                    req.setAttribute("message","修改密码成功,请退出并且使用新密码登录");
                    //修改密码之后,移除当前session
                    req.getSession().removeAttribute(Constants.USER_SESSION);
                }else {
                    req.setAttribute("message","修改密码失败");
                }
            }else {
                req.setAttribute("message","新密码不能使用");
            }
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        }
    

使用ajax优化密码修改:

//  验证旧密码
public void pwdModify(HttpServletRequest req,HttpServletResponse resp){
    //从session里面拿id
    Object o = req.getSession().getAttribute(Constants.USER_SESSION);
    String oldpassword = req.getParameter("oldpassword");

    //Map:存放结果集
    HashMap<String, String> resultMap = new HashMap<String, String>();

    if (o == null){//session失效、过期
        resultMap.put("result","sessionerror");
    }else if (StringUtils.isNullOrEmpty(oldpassword)){//输入密码为空
        resultMap.put("result","error");
    }else {
        String userPassword = ((User)o).getUserPassword();//session中用户的密码
        if (oldpassword.equals(userPassword)){
            resultMap.put("result","true");
        }else{
            resultMap.put("result","false");
        }
    }

    try {
        resp.setContentType("application/json");
        PrintWriter writer = resp.getWriter();
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    }catch (Exception e){
        e.printStackTrace();
    }
}

用户管理实现

实现方法:

image-20230213160933564

  1. 导入分页的工具类

  2. 用户列表页面导入

    userlist.jsp

1、获取用户数量

  1. UserDao

    //查询用户总数
        public int getUserCount(Connection connection,String username,int userRole)throws SQLException;
    
  2. UserDaoImpl

        //根据用户名或者角色查询用户总数
        public int getUserCount(Connection connection, String username, int userRole) throws SQLException {
            PreparedStatement pstm = null;
            ResultSet rs = null;
            int count = 0;
            if (connection != null){
                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<Object>();//存放参数
    
                if (!StringUtils.isNullOrEmpty(username)){
                    sql.append(" and u.userName like ?");
                    list.add("%"+username+"%");
                }
                if (userRole>0){
                    sql.append(" and u.userRole=?");
                    list.add(userRole);
                }
                //把list转换为数组
                Object[] params = list.toArray();
                System.out.println("userdaoimpl"+sql.toString());
    
                rs = BaseDao.excute(connection, pstm, rs, sql.toString(), params);
                if (rs.next()){
                    count = rs.getInt("count");
                }
                BaseDao.closeResource(null,pstm,rs);
            }
            return count;
        }
    
  3. UserService

    //查询用户总数
        public int getUserCount(String username,int userRole);
    
  4. UserServiceImpl

     //查询记录数
        public int getUserCount(String username, int userRole) {
            Connection connection = null;
            int count = 0;
            try {
                connection = BaseDao.getConnection();
                count = userDao.getUserCount(connection,username,userRole);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                BaseDao.closeResource(connection,null,null);
            }
            return count;
        }
    

2、获取用户列表

  1. UserDao

        //通过条件查询-userList
        public List<User> getUserList(Connection connection,String username,int userRole,int currentPageNo,int pageSize)throws SQLException;
    
  2. UserDaoImpl

    public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize)
                throws SQLException {
            // TODO Auto-generated method stub
            PreparedStatement pstm = null;
            ResultSet rs = null;
            List<User> userList = new ArrayList<User>();
            if(connection != null){
                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<Object>();
                if(!StringUtils.isNullOrEmpty(userName)){
                    sql.append(" and u.userName like ?");
                    list.add("%"+userName+"%");
                }
                if(userRole > 0){
                    sql.append(" and u.userRole = ?");
                    list.add(userRole);
                }
                /*
                    在数据库中分页使用   limit startIndex,pageSize   总数
                    当前页     (当前页-1)*页面容量
                    05         1  0            0 1234
                    55         2  5            2 6789
                   105         3  10
                */
                sql.append(" order by creationDate DESC limit ?,?");
                currentPageNo = (currentPageNo-1)*pageSize;
                list.add(currentPageNo);
                list.add(pageSize);
    
                Object[] params = list.toArray();
                System.out.println("sql ----> " + sql.toString());
                rs = BaseDao.excute(connection, pstm, rs, sql.toString(), params);
                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.setUserRole(rs.getInt("userRole"));
                    _user.setUserRoleName(rs.getString("userRoleName"));
                    userList.add(_user);
                }
                BaseDao.closeResource(null, pstm, rs);
            }
            return userList;
        }
    
  3. UserService

    //根据条件查询用户列表
        public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize);
    
  4. UserServiceImpl

     //根据条件查询用户列表
        public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) {
            // TODO Auto-generated method stub
            Connection connection = null;
            List<User> userList = null;
            System.out.println("queryUserName ---- > " + queryUserName);
            System.out.println("queryUserRole ---- > " + queryUserRole);
            System.out.println("currentPageNo ---- > " + currentPageNo);
            System.out.println("pageSize ---- > " + pageSize);
            try {
                connection = BaseDao.getConnection();
                userList = userDao.getUserList(connection, queryUserName,queryUserRole,currentPageNo,pageSize);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }finally{
                BaseDao.closeResource(connection, null, null);
            }
            return userList;
        }
    

3、获取角色操作

把角色的操作单独放在一个包中,和pojo对应

  1. RoleDao

    public interface RoleDao {
        //获取角色列表
        public List<Role> getRoleList(Connection connection) throws SQLException;
    }
    
  2. RoleDaoImpl

    public class RoleServiceImpl implements RoleService{
        //引入dao
        private RoleDao roleDao;
        public RoleServiceImpl(){
            roleDao = new RoleDaoImpl();
        }
        public List<Role> getRoleList() {
            Connection connection = null;
            List<Role> roleList = null;
            try {
                connection = BaseDao.getConnection();
                roleList = roleDao.getRoleList(connection);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                BaseDao.closeResource(connection,null,null);
            }
            return roleList;
        }
    }
    
  3. RoleService

    public interface RoleService {
        //获取角色列表
        public List<Role> getRoleList();
    }
    
  4. RoleServiceImpl

    public class RoleServiceImpl implements RoleService{
        //引入dao
        private RoleDao roleDao;
        public RoleServiceImpl(){
            roleDao = new RoleDaoImpl();
        }
        public List<Role> getRoleList() {
            Connection connection = null;
            List<Role> roleList = null;
            try {
                connection = BaseDao.getConnection();
                roleList = roleDao.getRoleList(connection);
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                BaseDao.closeResource(connection,null,null);
            }
            return roleList;
        }
    }
    

4、用户显示的Servlet

  1. 获取用户前端数据(查询)

  2. 判断请求是否需要执行,看参数的值判断

  3. 为了实现分页,需要计算出当前页面和总页面,页面大小

  4. 用户列表展示

  5. 返回前端

    //重点//查询用户列表
    public void query(HttpServletRequest req,HttpServletResponse resp){
        //从前端获取数据
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");//临时
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;
    
        //获取用户列表
        UserServiceImpl userService = new UserServiceImpl();
        List<User> userList = null;
        //第一次走这个请求,一定是第一页,页面大小是固定的
        int pageSize = 5;//可以吧这个配置到配置文件中,方便后期修改
        int currentPageNo = 1;
    
        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.getUserCount(queryUserName,queryUserRole);
        //总页数支持
        PageSupport pageSupport  = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);
    
        int totalPageCount = totalCount/pageSize+1;//页数
    
        //控制首页和尾页
        //如果页面小于一了,就显示第一页的东西
        if (totalCount<1){
            currentPageNo = 1;
        }else if (currentPageNo>totalPageCount){//当前页面大于了最后一页
            currentPageNo = totalPageCount;
        }
        
        //获取用户列表展示
        userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo,pageSize);
        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();
        }
    }