javaweb超市管理系统demo

image-20200531213054908

学习资源来自于哔哩哔哩UP遇见狂神说,一个宝藏UP大家快去关注吧!记得三连加分享,不要做白嫖党.

SMBMS

image-20200519184047576

数据库:

image-20200519184151064

项目搭建准备工作

  1. 搭建一个maven web项目

  2. 配置tomcat

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

  4. 导入项目中可能会遇到的Jar包
    jsp,Servlet,mysql驱动,jstl,stander......

      <dependency>
                <groupId>javax.servlet</groupId>
                <artifactId>servlet-api</artifactId>
                <version>2.5</version>
            </dependency>
            <dependency>
                <groupId>javax.servlet.jsp</groupId>
                <artifactId>javax.servlet.jsp-api</artifactId>
                <version>2.3.3</version>
            </dependency>
            <dependency>
                <groupId>mysql</groupId>
                <artifactId>mysql-connector-java</artifactId>
                <version>5.1.47</version>
            </dependency>
      <dependency>
                <groupId>javax.servlet.jsp.jstl</groupId>
                <artifactId>jstl-api</artifactId>
                <version>1.2</version>
            </dependency>
            <dependency>
                <groupId>taglibs</groupId>
                <artifactId>standard</artifactId>
                <version>1.1.2</version>
            </dependency>
    
  5. 创建项目包结构

    image-20200519190430237

  6. 编写实体类
    ORM映射: 表-类映射

ORM映射: 表-类映射

  1. 编写基础公共类

    1. 数据库配置文件
      db.properties

      driver=com.mysql.jdbc.Driver
      url=jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf8&useSSL=true
      username=root
      password=123456
      
    2. 编写数据库的公共类(工具类)

      package com.tan.dao;
      
      import java.sql.ResultSet;
      import java.sql.*;
      
      import java.io.IOException;
      import java.io.InputStream;
      import java.sql.Connection;
      import java.util.Properties;
      
      /**
       * @author null
       * @date 2020/5/19
       */
      
      //操作数据类的公共类
      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 {
              //预编译的sql,在后面直接执行就可以了
              preparedStatement = connection.prepareStatement(sql);
      
              for (int i = 0; i < params.length; i++) {
                  //setObject,占位符从1开始,但是我们的数据是从0开始!
                  preparedStatement.setObject(i + 1, params[i]);
      
              }
              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(ResultSet resultSet, PreparedStatement preparedStatement, Connection connection) {
              boolean flag = true;
      
              if (resultSet != null) {
                  try {
                      resultSet.close();
                      //GC回收
                      resultSet = null;
                  } catch (SQLException throwables) {
                      throwables.printStackTrace();
                      flag = false; //相当于没有释放成功
                  }
              }
      
              if (preparedStatement != null) {
                  try {
                      preparedStatement.close();
                      //GC回收
                      preparedStatement = null;
                  } catch (SQLException throwables) {
                      throwables.printStackTrace();
                      flag = false; //相当于没有释放成功
                  }
              }
      
              if (connection != null) {
                  try {
                      connection.close();
                      //GC回收
                      connection = null;
                  } catch (SQLException throwables) {
                      throwables.printStackTrace();
                      flag = false; //相当于没有释放成功
                  }
              }
              return flag;
          }
      }
      
    3. 编写字符编码过滤器

      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");
              response.setContentType("text/html; charset=UTF-8");
      
              chain.doFilter(request, response);
          }
      
          public void destroy() {
      
          }
      }
      

      配置字符编码过滤器的web.xml

          <!--字符编码过滤器-->
          <filter>
              <filter-name>CharacterEncodingFilter</filter-name>
              <filter-class>com.tan.filter.CharacterEncodingFilter</filter-class>
          </filter>
          <filter-mapping>
              <filter-name>CharacterEncodingFilter</filter-name>
              <url-pattern>/*</url-pattern>
          </filter-mapping>
      
  2. 导入静态资源
    image-20200519215225350

登录功能实现

image-20200519215736719

  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 {
    
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user = null;
    
        public User getLoginUser(Connection connection, String userCode) throws SQLException {
    
            if (connection != null) {
                String sql = "select from smbms_user where userCode=?";
                Object[] params = {userCode};
    
                    rs = BaseDao.execute(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("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(connection, 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();
            //通过业务层调用对应的具体的数据库操作
            user = userDao.getLoginUser(connection, userCode);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            BaseDao.closeResource(connection, null, null);
        }
        return user;
    }

}
  1. 编写Servlet

    public class LoginServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            System.out.println("LoginServlet----start.....");
    
            //获取用户的账号密码
            String userCode = req.getParameter("userCode");
            String userPassword = req.getParameter("userPassword");
    
            //和数据库的密码进行对比,调用业务层
            UserService userService = new UserServiceImpl();
            User user = userService.login(userCode, userPassword);
            if (user != null && userPassword.equals(user.getUserPassword())) {//查到有人可以登录,与数据库的密码进行对比
                //将用户的信息放到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 {
            doGet(req, resp);
        }
    }
    
  2. 注册Servlet

    <!--Servlet-->
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.tan.servlet.user.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login.do</url-pattern>
    </servlet-mapping>
    
  3. 测试访问,确保以上功能成功!

登录功能优化

注销功能:

思路: 移除session,返回登陆界面

public class LogoutServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //移除用户的Constants.USER_SESSION
        req.getSession().removeAttribute(Constants.USER_SESSION);
        resp.sendRedirect("/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.tan.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 {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    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);
        }
    }

    @Override
    public void destroy() {

    }
}

配置xml

    <!--登录优化过滤器-->
    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.tan.filter.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/jsp/*</url-pattern>
    </filter-mapping>

测试,登录,注销,权限,都要保证OK!

密码修改

  1. 导入前端素材

    <li><a href="${pageContext.request.contextPath }/jsp/pwdmodify.jsp">密码修改</a></li>
    
  2. 写项目,建议从底层向上写
    image-20200524102826903

  3. UserDao 接口

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

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

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

        @Override
        public boolean updatePwd(int id, String pwd) {
            Connection connection = null;
            boolean flag = false;
    
            connection = BaseDao.getConnection();
            //修改密码
            try {
                if (userDao.updatePwd(connection, id, pwd)>0) {
                    flag = true;
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                BaseDao.closeResource(connection, null, null);
            }
            return flag;
        }
    
  7. 记得实现复用,需要提取出方法

    String method = req.getParameter("method");
    if (method.equals("savepwd") && method != null) {
        this.updatePwd(req,resp);
    }
    

    提取出的方法:

        //写成方法实现Servlet的复用
        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) {
                UserServiceImpl 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 | IOException e) {
                e.printStackTrace();
            }
        }
    }
    

    记配置web.xml

  8. 测试

优化密码修改使用Ajax

  1. 阿里巴巴fastjson

      <!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
            <dependency>
                <groupId>com.alibaba</groupId>
                <artifactId>fastjson</artifactId>
                <version>1.2.62</version>
            </dependency>
    
  2. 后台代码修改

//验证旧密码
public void pwdModify(HttpServletRequest req, HttpServletResponse resp) {
    //从Session里面拿ID
    Object o = req.getSession().getAttribute(Constants.USER_SESSION);
    String oldpassword = req.getParameter("oldpassword");//获取从pwdmodify.js里Ajax的参数,连接前端

    //万能的Map : 结果集
    HashMap<String, String> resultMap = new HashMap<>();

    if (o == null) {//Session过期或者失效了
        resultMap.put("result", "sessionerror");
    } else if (StringUtils.isNullOrEmpty(oldpassword)) {//输入的密码为空
        resultMap.put("result", "false");
    } else {
        String userPassword = ((User) o).getUserPassword();//Session中获取用户的老密码
        if (oldpassword.equals(userPassword)) {
            resultMap.put("result", "true");//输入密码正确
        } else {
            resultMap.put("result", "true");//输入密码输入不正确
        }
    }

    try {
        resp.setContentType("application/json");//限定为json格式
        PrintWriter writer = resp.getWriter();//给个流
        //使用阿里巴巴JSON工具类
        /*
        将Map格式转化为JSON格式
        */
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
  1. 调试

用户管理实现(实在是太多,放弃做笔记了)

思路:

image-20200524190411220

  1. 导入分页的工具类
  2. 用户列表页面导入

1.获取用户数量

  1. UserDao
  2. UserDaoImpl
  3. UserService
  4. UserServiceImpl
posted @ 2020-06-02 10:07  Vlats  阅读(2842)  评论(7编辑  收藏  举报