JavaWeb搭建超市管理系统

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;
        }
    }
    
  • 1
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 5
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值