本站消息

站长简介/公众号


站长简介:高级软件工程师,曾在阿里云,每日优鲜从事全栈开发工作,利用周末时间开发出本站,欢迎关注我的微信公众号:程序员总部,程序员的家,探索程序员的人生之路!分享IT最新技术,关注行业最新动向,让你永不落伍。了解同行们的工资,生活工作中的酸甜苦辣,谋求程序员的最终出路!

 价值13000svip视频教程,前端大神匠心打造,零基础前端开发工程师视频教程全套,基础+进阶+项目实战,包含课件和源码

  出租广告位,需要合作请联系站长


+关注
已关注

分类  

暂无分类

标签  

暂无标签

日期归档  

2021-05(13)

2021-06(81)

2021-07(13)

2021-08(62)

2021-09(66)

超市订单管理系统

发布于2021-05-30 12:24     阅读(809)     评论(0)     点赞(9)     收藏(1)


超市订单管理系统源码

1.项目搭建准备工作

  1. 搭建一个maven web项目

  2. 配置Tomcat

  3. 测试项目环境是否能跑起来

  4. 导入jar包(jsp、servlet、mysql驱动、jstl、standard…)

  5. 创建项目包结构

  6. 编写实体类(ORM映射)

  7. 编写基础公共类

    1. 数据库配置文件

      driver=com.mysql.jdbc.Driver
      url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf-8&useSSL=true
      username=root
      password=123456
      
    2. 编写数据库的公共类

      //操作数据库的公共类
      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 (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 connection = null;
              try {
                  Class.forName(driver);
                  connection = DriverManager.getConnection(url, username, password);
              } catch (Exception e) {
                  e.printStackTrace();
              }
              return connection;
          }
      
          //编写查询公共方法
          public static ResultSet execute(Connection connection, PreparedStatement preparedStatement, ResultSet resultSet, String sql, Object[] params) throws SQLException {
              preparedStatement = connection.prepareStatement(sql);
      
              for (int i = 0; i < params.length; i++) {
                  //setObject占位符从1开始,但是数据从0开始
                  preparedStatement.setObject(i+1,params[i]);
              }
      
              resultSet = preparedStatement.executeQuery();
              return resultSet;
          }
      
          //编写增、删、改公共方法
          public static int execute(Connection connection, PreparedStatement preparedStatement, String sql, Object[] params) throws SQLException {
              preparedStatement = connection.prepareStatement(sql);
      
              for (int i = 0; i < params.length; i++) {
                  //setObject占位符从1开始,但是数据从0开始
                  preparedStatement.setObject(i+1,params[i]);
              }
      
              int updateRows = preparedStatement.executeUpdate();
              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 (SQLException e) {
                      e.printStackTrace();
                      flag = false;
                  }
              }
              if (preparedStatement != null){
                  try {
                      preparedStatement.close();
                      //gc回收
                      preparedStatement = null;
                  } catch (SQLException e) {
                      e.printStackTrace();
                      flag = false;
                  }
              }
              if (connection != null){
                  try {
                      connection.close();
                      //gc回收
                      connection = null;
                  } catch (SQLException e) {
                      e.printStackTrace();
                      flag = false;
                  }
              }
              return flag;
          }
      }
      
    3. 编写字符编码过滤器

      public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
          servletRequest.setCharacterEncoding("utf-8");
          servletResponse.setCharacterEncoding("utf-8");
          filterChain.doFilter(servletRequest,servletResponse);
      }
      
  8. 导入静态资源(css,js,image…)

2.登录功能实现

  • 流程分析:

登录流程

  1. 编写前端页面

  2. 设置主页

    <!--设置首页-->
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
    
  3. 编写dao层用户登录接口(UserDao)

    //得到要登录的用户
    public User getLoginUser(Connection connection,String userCode,String userPassword) throws SQLException;
    
  4. 编写dao接口的实现类(UserDaoImpl)

    //得到要登录的用户
    public User getLoginUser(Connection connection, String userCode, String userPassword) throws SQLException {
    
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        User user = null;
    
        if (connection != null){
            String sql = "select * from smbms_user where userCode=? and userPassword=?";
            Object[] params = {userCode,userPassword};
    
            resultSet = BaseDao.execute(connection, preparedStatement, resultSet, sql, params);
            if (resultSet.next()){
                user = new User();
                user.setId(resultSet.getInt("id"));
                user.setUserCode(resultSet.getString("userCode"));
                user.setUserName(resultSet.getString("userName"));
                user.setUserPassword(resultSet.getString("userPassword"));
                user.setGender(resultSet.getInt("gender"));
                user.setBirthday(resultSet.getDate("birthday"));
                user.setPhone(resultSet.getString("phone"));
                user.setAddress(resultSet.getString("address"));
                user.setUserRole(resultSet.getInt("userRole"));
                user.setCreatedBy(resultSet.getInt("createdBy"));
                user.setCreationDate(resultSet.getDate("creationDate"));
                user.setModifyBy(resultSet.getInt("modifyBy"));
                user.setModifyDate(resultSet.getDate("modifyDate"));
            }
            BaseDao.closeResource(null,preparedStatement,resultSet);
        }
        return user;
    }
    
  5. 业务层接口(UserService)

    //用户登录
    public User login(String userCode,String userPassword);
    
  6. 业务层实现类(UserServiceImpl)

    //业务层都会调用dao层
    private UserDao userDao;
    public UserServiceImpl(){
        userDao = new UserDaoImpl();
    }
    
    public User login(String userCode, String userPassword) {
        Connection connection = null;
        User user = null;
    
        try {
            connection = BaseDao.getConnection();
            //通过业务层调用对应的具体的数据库操作层
            user = userDao.getLoginUser(connection,userCode,userPassword);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(connection,null,null);
        }
        return user;
    }
    
  7. 编写Servlet

    //控制层调用业务层
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取用户名和密码
        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);
        }
    
  8. 注册登录Servlet

    <!--登录-->
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.java.servlet.user.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login.do</url-pattern>
    </servlet-mapping>
    
  9. 测试访问

3.登录功能优化

  • 注销功能:移除Session,返回登录页面

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //移除用户的Session
        req.getSession().removeAttribute(Constants.USER_SESSION);
        resp.sendRedirect(req.getContextPath()+"/login.jsp");
    }
    
  • 注册登出Servlet

    <!--登出-->
    <servlet>
        <servlet-name>LogoutServlet</servlet-name>
        <servlet-class>com.java.servlet.user.LogoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LogoutServlet</servlet-name>
        <url-pattern>/jsp/logout.do</url-pattern>
    </servlet-mapping>
    
  • 登录拦截优化(过滤器)

    编写过滤器

    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
    
        //过滤器,从Session中获取用户
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);
        if (user == null){//被移除或者已经注销了,或者未登录
            response.sendRedirect(request.getContextPath()+"/error.jsp");
        }else{
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }
    

    注册过滤器

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

4.密码修改

  1. 导入前端素材

  2. 编写UserDao接口

    public int updatePwd(Connection connection, int id, String userPassword)throws SQLException;
    
  3. 编写UserDao接口实现类

    //修改当前用户密码
    public int updatePwd(Connection connection, int id, String userPassword) throws SQLException {
        PreparedStatement preparedStatement = null;
        int i = 0;
        if (connection != null) {
            String sql = "update smbms_user set userPassword=? where id=?";
            Object[] params = {userPassword, id};
            i = BaseDao.execute(connection, preparedStatement, sql, params);
            BaseDao.closeResource(connection, preparedStatement, null);
        }
        return i;
    }
    
  4. 编写UserService接口

    public boolean updatePwd(int id, String userPassword);
    
  5. 编写UserService接口实现类

    public boolean updatePwd(int id, String userPassword) {
        Connection connection = null;
        boolean flag = false;
        try {
            connection = BaseDao.getConnection();
            if (userDao.updatePwd(connection,id,userPassword)>0){
                flag = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(connection,null,null);
        }
        return flag;
    }
    
  6. 实现复用,需要提取出方法

    //实现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")&&method != null){
                this.updatePwd(req,resp);
            }else if(method.equals("pwdmodify")&&method != null){
                this.pwdModify(req,resp);
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
        
        public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
            //从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","新密码有问题");
            }
            try {
                req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
  7. Ajax验证旧密码是否正确

    oldpassword.on("blur",function(){
    		$.ajax({
    			type:"GET",
    			url:path+"/jsp/user.do",
    			data:{method:"pwdmodify",oldpassword:oldpassword.val()},
    			dataType:"json",
    			success:function(data){
    				if(data.result == "true"){//旧密码正确
    					validateTip(oldpassword.next(),{"color":"green"},imgYes,true);
    				}else if(data.result == "false"){//旧密码输入不正确
    					validateTip(oldpassword.next(),{"color":"red"},imgNo + " 原密码输入不正确",false);
    				}else if(data.result == "sessionerror"){//当前用户session过期,请重新登录
    					validateTip(oldpassword.next(),{"color":"red"},imgNo + " 当前用户session过期,请重新登录",false);
    				}else if(data.result == "error"){//旧密码输入为空
    					validateTip(oldpassword.next(),{"color":"red"},imgNo + " 请输入旧密码",false);
    				}
    			},
                error:function(data){
                    //请求出错
                    validateTip(oldpassword.next(),{"color":"red"},imgNo + " 请求错误",false);
                }
            });
    
  8. 导入阿里巴巴的fastjson:Json工具,转换格式

    <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.76</version>
    </dependency>
    
  9. 编写后端代码

    //验证旧密码,Session中
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");
    
        //结果集
        Map<String,String> resultMap = new HashMap<String, String>();
    
        if (o == null){ //Session过期
            resultMap.put("result","sessionerror");
        }else if (oldpassword == null || oldpassword.length()==0){
            resultMap.put("result","error");
        }else{
            String userPassword = ((User) o).getUserPassword();
            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 (IOException e) {
            e.printStackTrace();
        }
    }
    

5.用户管理实现

思路:

用户管理

5.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 preparedStatement = null;
        ResultSet resultSet = 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+"%"); //index 0
            }
    
            if (userRole>0){
                sql.append(" and u.userRole = ?");
                list.add(userRole); //index 1
            }
    
            //将list转换为数组
            Object[] objects = list.toArray();
    
            resultSet = BaseDao.execute(connection, preparedStatement,resultSet, sql.toString(), objects);
            if (resultSet.next()){
                count = resultSet.getInt("count");//从结果中获取最终的数量
            }
            BaseDao.closeResource(null, preparedStatement, resultSet);
        }
        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 (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(connection,null,null);
        }
        return count;
    }
    

5.2 获取用户列表

  1. UserDao

    //获取用户列表
    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 {
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        int count = 0;
        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");
            ArrayList<Object> list = new ArrayList<Object>(); //存放参数
    
            if (!StringUtils.isNullOrEmpty(username)){
                sql.append(" and u.userName like ?");
                list.add("%"+username+"%"); //index 0
            }
    
            if (userRole>0){
                sql.append(" and u.userRole = ?");
                list.add(userRole); //index 1
            }
            sql.append(" order by creationDate DESC limit ?,?");
            currentPageNo = (currentPageNo-1)*pageSize;
            list.add(currentPageNo);
            list.add(pageSize);
    
            //将list转换为数组
            Object[] objects = list.toArray();
    
            resultSet = BaseDao.execute(connection, preparedStatement,resultSet, sql.toString(), objects);
            if (resultSet.next()){
                User _user = new User();
                _user.setId(resultSet.getInt("id"));
                _user.setUserCode(resultSet.getString("userCode"));
                _user.setUserName(resultSet.getString("userName"));
                _user.setGender(resultSet.getInt("gender"));
                _user.setBirthday(resultSet.getDate("birthday"));
                _user.setPhone(resultSet.getString("phone"));
                _user.setUserRole(resultSet.getInt("userRole"));
                _user.setUserRoleName(resultSet.getString("userRoleName"));
                userList.add(_user);
            }
            BaseDao.closeResource(null, preparedStatement, resultSet);
        }
        return userList;
    }
    
  3. UserService

    //获取用户列表
    public List<User> getUserList(String username, int userRole, int currentPageNo, int pageSize);
    
  4. UserServiceImpl

    //获取用户列表
    public List<User> getUserList(String username, int userRole, int currentPageNo, int pageSize) {
        Connection connection = null;
        List<User> userList = null;
        try {
            connection = BaseDao.getConnection();
            userList = userDao.getUserList(connection, username,userRole,currentPageNo,pageSize);
        } catch (Exception e) {
            e.printStackTrace();
        }finally{
            BaseDao.closeResource(connection, null, null);
        }
        return userList;
    }
    

5.3 获取角色列表

为了职责统一,可以把角色的操作单独放在一个包中,和pojo对应

  1. RoleDao

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

    //获取角色列表
    public List<Role> getRoleList(Connection connection) throws SQLException {
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<Role> roleList = new ArrayList<Role>();
    
        if(connection != null){
            String sql = "select * from smbms_role";
            Object[] params = {};
            resultSet = BaseDao.execute(connection, preparedStatement, resultSet, sql, params);
            while (resultSet.next()){
                Role _role = new Role();
                _role.setId(resultSet.getInt("id"));
                _role.setRoleCode(resultSet.getString("roleCode"));
                _role.setRoleName(resultSet.getString("roleName"));
                roleList.add(_role);
            }
            BaseDao.closeResource(null, preparedStatement, resultSet);
        }
        return roleList;
    }
    
  3. RoleService

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

    public List<Role> getRoleList() {
        Connection connection = null;
        List<Role> roleList = null;
        try {
            connection = BaseDao.getConnection();
            roleList = roleDao.getRoleList(connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(connection,null,null);
        }
        return roleList;
    }
    

5.4 用户显示Servlet

  1. 获取用户前端的数据

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

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

  4. 用户列表展示

  5. 返回前端

    //代码复用
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            String method = req.getParameter("method");
        	....
    		else if (method.equals("query")&&method != null){
                this.query(req,resp);
            }
    }
    //用户列表
    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  currentPageNo = 1;
    
        if (queryUserName == null){
            queryUserName = "";
        }
        if (temp != null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp);
        }
        if (pageIndex != null){
            currentPageNo = Integer.parseInt(pageIndex);
        }
    
        //获取用户的总数(分页)
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);
    
        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(Constants.pageSize);
        pageSupport.setTotalCount(totalCount);
    
        int totalPageCount = pageSupport.getTotalPageCount();
    
        //控制首页和尾页
        //如果页面要小于1,就显示第一页的内容
        if (totalPageCount < 1){
            currentPageNo = 1;
        }else if (currentPageNo > totalPageCount){ //当前页大于最后一页
            currentPageNo = totalPageCount;
        }
    
        //获取用户列表展示
        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, Constants.pageSize);
        req.setAttribute("userList",userList);
    
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        req.setAttribute("roleList",roleList);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
    
        //返回前端
        try {
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    

6.其他功能

  • 其他功能类似查询功能,基本都是数据库的操作,参考项目源代码

原文链接:https://blog.csdn.net/TvTToT/article/details/117261032




所属网站分类: 技术文章 > 博客

作者:西小口到了吗

链接:http://www.qianduanheidong.com/blog/article/116075/0e7d4ffed3fb16ed58a4/

来源:前端黑洞网

任何形式的转载都请注明出处,如有侵权 一经发现 必将追究其法律责任

9 0
收藏该文
已收藏

评论内容:(最多支持255个字符)