1. 程式人生 > 實用技巧 >JavaWe搭建超市管理系統

JavaWe搭建超市管理系統

目錄

SMBMS

準備工作

  1. 搭建一個Maven專案、

  2. 配置Tomcat

  3. 測試專案能否跑起來

  4. 匯入專案所需的jar包(servlet,jsp,mysql,jstl,standard.....)

  5. 建立專案包結構

  6. 編寫實體類(ORM對映:表---類對映)

  7. 編寫基礎公共類(資料庫配置檔案)

    driver=com.mysql.jdbc.driver
    url=jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf-8
    user=root
    password=123456
    

    編寫操作資料庫的公共類

    //操作資料庫的公共類
    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,String sql,PreparedStatement ps,Object[] params,ResultSet resultSet) throws SQLException {
            //預編譯的sql在後面直接執行就可以了
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i+1,params[i]);
            }
            resultSet = ps.executeQuery();
            return resultSet;
        }
        //編寫增刪改公共方法
        public static int execute(Connection connection,String sql,PreparedStatement ps,Object[] params) throws SQLException {
            ps = connection.prepareStatement(sql);
            for (int i = 0; i < params.length; i++) {
                ps.setObject(i+1,params[i]);
            }
            int updaterows = ps.executeUpdate();
            return updaterows;
        }
        //釋放連線
        public static boolean close(Connection connection,PreparedStatement ps,ResultSet resultSet){
            boolean flag=true;
            if (resultSet!=null){
                try {
                    resultSet.close();
                    //GC回收
                    resultSet = null;
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                    flag = false;
                }
            }
            if (ps!=null){
                try {
                    ps.close();
                    //GC回收
                    ps = null;
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                    flag = false;
                }
            }
            if (connection!=null){
                try {
                    connection.close();
                    //GC回收
                    connection = null;
                } catch (SQLException throwables) {
                    throwables.printStackTrace();
                    flag = false;
                }java
            }
            return flag;
        }
    }
    

    編寫字元編碼過濾器

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

    配置web.xml

    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>com.zr.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    
  8. 匯入靜態資源

登入功能實現

  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 ps = null;
            ResultSet rs = null;
            User user = null;
    
            if (connection!=null){
                String sql = "select * from smbms_user where userCode=?";
                Object[] params={userCode};
    
                rs = BaseDao.execute(connection, ps, 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,ps,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;
    
            connection = BaseDao.getConnection();
            try {
                //通過業務層呼叫具體的業務操作
                user = userDao.getLoginUser(connection,userCode);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                BaseDao.closeResource(connection,null,null);
            }
            return user;
        }
        //單元測試
        @Test
        public void Test(){
            UserServiceImpl userService = new UserServiceImpl();
            User admin = userService.login("admin", "1234567");
            System.out.println(admin.getUserPassword());
        }
    }
    
  7. 編寫Servlet

    public class LoginServlet extends HttpServlet {
        //Serclet控制層,呼叫業務層程式碼
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
            System.out.println("LoginServlet.start");
    
            //獲取使用者名稱和密碼
            String username = req.getParameter("userCode");
            String password = req.getParameter("userPassword");
    
            //和資料庫中的密碼進行對比,呼叫業務層
            UserServiceImpl userService = new UserServiceImpl();
            User user = userService.login(username, password); //把登入的人查出來
            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 {
            doGet(req, resp);
        }
    }
    
  8. 註冊Servlet

    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.zr.servlet.user.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login.do</url-pattern>
    </servlet-mapping>
    
  9. 測試訪問

登入功能優化

登出功能:移除session,返回登入頁面

登出Servlet

public class LoginoutServlet 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);
    }
}

web.xml

<servlet>
    <servlet-name>LoginoutServlet</servlet-name>
    <servlet-class>com.zr.servlet.user.LoginoutServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LoginoutServlet</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 filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse respone = (HttpServletResponse) resp;
        //從Session中獲取使用者
        User user = (User)request.getSession().getAttribute(Constants.USER_SESSION);
        if(user==null){
            respone.sendRedirect(request.getContextPath()+"/error.jsp");
        }else {
         filterChain.doFilter(req,resp);
        }
    }

    public void destroy() {

    }
}

web.xml

<!--    使用者登入過濾器-->
    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.zr.filter.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/jsp/*</url-pattern>
    </filter-mapping>

密碼修改

  1. 編寫dao層介面

    //修改當前使用者的密碼
    public int updatePwd(Connection connection,int id,String password) throws SQLException;
    
  2. 編寫dao介面的實現類

    //修改當前使用者的密碼
    public int updatePwd(Connection connection, int id, String password) throws SQLException {
    
        PreparedStatement ps = null;
        int count = 0;
    
        if (connection!=null){
            String sql = "update smbms_user set userPassword = ? where id = ?";
            Object[] param = {password,id};
            count = BaseDao.execute(connection, ps, sql, param);
            BaseDao.closeResource(null,ps,null);
        }
        return count;
    }
    
  3. 業務層

    //修改密碼
    public boolean updatePwd(int id, String password);
    
  4. 業務層介面

    public boolean updatePwd(int id, String password) {
        Connection connection = null;
        boolean flag = false;
    
        try {
            connection = BaseDao.getConnection();
            //修改密碼
            if (userDao.updatePwd(connection, id, password)>0){
                flag = true;
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            BaseDao.closeResource(connection,null,null);
        }
        return flag;
    }
    
  5. Servlet層

    public class UserServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //獲取Session(用Session獲取當前使用者的id)
            Object o = req.getSession().getAttribute(Constants.USER_SESSION);
            //獲取前端輸入的密碼
            String newPassword = req.getParameter("newpassword");
            boolean flag = false;
            System.out.println("==============");
            System.out.println(((User)o).getId());
            System.out.println(((User)o).getUserPassword());
            System.out.println(newPassword);
    
            if (o!=null && !StringUtils.isNullOrEmpty(newPassword)){
                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);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
  6. web.xml

    <servlet>
        <servlet-name>UserServlet</servlet-name>
        <servlet-class>com.zr.servlet.user.UserServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/jsp/user.do</url-pattern>
    </servlet-mapping>
    

密碼驗證Ajax

在Servlet層驗證(將驗證和修改密碼提取成方法,在Servlet中呼叫)匯入阿里巴巴fastjson的jar包

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(用Session獲取當前使用者的id)
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        //獲取前端輸入的密碼
        String newPassword = req.getParameter("newpassword");
        boolean flag = false;
        System.out.println("==============");
        System.out.println(((User)o).getId());
        System.out.println(((User)o).getUserPassword());
        System.out.println(newPassword);

        if (o!=null && !StringUtils.isNullOrEmpty(newPassword)){
            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();
        }
    }

    //驗證舊密碼 Session中有使用者的密碼
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");
        System.out.println(oldpassword);
        System.out.println("+++++++++++++++++++");
        //萬能的Map:結果集
        Map<String, String> resultMap = new HashMap<String,String>();
        //Session失效
        if (o==null){
            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("aplication/json");
            PrintWriter writer = resp.getWriter();
            //格式轉換
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

使用者管理實現

匯入分頁的工具類,使用者列表頁面匯入

使用者數量

  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 ps = 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);
            }
            System.out.println(list+"=======");
            Object[] params = list.toArray(); //轉化為陣列
            System.out.println("UserDaoImpl--->getUserCount"+sql.toString());
            System.out.println(params);
    
            rs = BaseDao.execute(connection, ps, rs, sql.toString(), params);
            if (rs.next()){
                count = rs.getInt("count");
            }
            BaseDao.closeResource(null,ps,rs);
        }
        return count;
    }
    
  3. UserService

    //查詢使用者的人數
    public int getCountUser(String username,int userRole);
    
  4. UserServiceImpl

    //使用者總數
    public int getCountUser(String username, int userRole) {
    
        Connection connection = null;
        int count = 0;
    
        try {
            connection = BaseDao.getConnection();
            count = userDao.getUserCount(connection, username, userRole);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            BaseDao.closeResource(connection,null,null);
        }
        return count;
    }
    

使用者列表

  1. UserDao

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

    //通過條件查詢userList
    public List<User> getUserList(Connection connection, String username, int userRole, int currentPageNo, int pageSize) throws SQLException {
        PreparedStatement ps = null;
        ResultSet rs = null;
        //返回的使用者列表
        ArrayList<User> userList = new ArrayList<User>();
    
        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);
            }
    
            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("sql-->"+sql.toString());
            rs = BaseDao.execute(null, ps, rs, sql.toString(), params);
            while (rs.next()){
                User user2 = new User();
                user2.setId(rs.getInt("id"));
                user2.setUserCode(rs.getString("userCode"));
                user2.setUserName(rs.getString("userName"));
                user2.setGender(rs.getInt("gender"));
                user2.setBirthday(rs.getDate("birthday"));
                user2.setPhone(rs.getString("phone"));
                user2.setUserRole(rs.getInt("userRole"));
                user2.setUserRoleName(rs.getString("userRoleName"));
                userList.add(user2);
            }
            BaseDao.closeResource(null,ps,rs);
    
        }
    
        return userList;
    }
    
  3. UserService

    //通過條件查詢userList
    public List<User> getUserList(String queryUsername,int queryUserRole,int currentPageNo,int pageSize);
    
  4. UserServiceImpl

    //通過條件查詢userList
    public List<User> getUserList(String queryUsername, int queryUserRole, int currentPageNo, int pageSize) {
        Connection connection = null;
        List<User> userList = null;
        try {
            connection = BaseDao.getConnection();
            userList = userDao.getUserList(connection, queryUsername, queryUserRole, currentPageNo, pageSize);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }finally {
            BaseDao.closeResource(connection,null,null);
        }
        return userList;
    }
    

角色列表

  1. RoleDao

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

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

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

    public class RoleServiceImpl implements RoleService{
        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 (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                BaseDao.closeResource(connection,null,null);
            }
            return roleList;
        }
    }