JaveWeb实战项目-超市管理系统

j超市订单管理系统SMBMS

登录功能实现

注意:本项目考察对数据库的增删改查的运用,这里只完成了用户管理功能,也是 前端-service-servlet-dao-数据库 最复杂的一块,其他功能较为相似。

  1. 编写前端页面
  2. 设置首页
 <!--这是欢迎界面-->
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>
  1. 编写dao层登录用户登录的接口
public interface UserDao {
    //得到要登录的用户
    public User getLoginUser(Connection connection, String userCode) throws SQLException;
}
  1. 编写dao接口的实现类
public class UerDaoImpl implements UserDao{
    @Override
    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.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("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;
    }
}
  1. 业务层接口
public interface UserService {
    //用户登录
    public User login(String userCode,String password);
}
  1. 业务层实现类
public class UserServiceImpl implements UserService{

    //业务层都会调用dao层,所以我们要引入Dao层
    private UserDao userDao;
    public UserServiceImpl(){
        userDao = new UerDaoImpl();
    }

    @Override
    public User login(String userCode, String password) {
        Connection connection =null;
        User user = null;

        try {
            connection = BaseDao.getConnection();
            //通过业务层调用对应的具体的数据库操作
            user = userDao.getLoginUser(connection,userCode);

        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(connection,null,null);
        }
        return user;
    }
}
  1. 编写Servlet
   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");

        //和数据库中的用户名和密码对比,调用业务层
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.login(userCode, userPassword);//这里已经把登录的人给查出来了
        if (user!=null){
            //将用户的信息放到Session中
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            //跳转到主页 29。46
            resp.sendRedirect("jsp/frame.jsp");
        }else{//无法登录
            //转发回登录页面,顺带提示他,用户名或者密码错误
            req.setAttribute("error","用户名或者密码不正确");
            req.getRequestDispatcher("login.jsp").forward(req,resp);

        }
    }
  1. 注册Servlet
    <!--Servlet-->
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.vekzjj.servlet.user.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/login.do</url-pattern>
    </servlet-mapping>
  1. 测试访问,确保以上功能能够成功

登录功能优化

注销功能:

思路:移除Session,返回登陆页面

    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //移除用户的Constants.USER_SESSION
        req.getSession().removeAttribute(Constants.USER_SESSION);
        resp.sendRedirect(req.getContextPath()+"/login.jsp");//返回登录的页面
    }
   <servlet>
        <servlet-name>LogoutServlet</servlet-name>
        <servlet-class>com.vekzjj.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("/smbms/error.jsp");
        }else {
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }
<!--    //用户登录过滤器-->
    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.vekzjj.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></li><!--密码修改-->
  1. UserDao接口
    //修改当前用户密码
    public int updatePwd(Connection connection,int id,int password) throws SQLException;
  1. UserDao 实现类
    @Override
    public int updatePwd(Connection connection, int id, int password) throws SQLException {
        //修改当前用户密码
        PreparedStatement pstm= null;
        int execute = 0;
        if (connection!=null){
            String sql = "update smbms_user set userPassword = ? where id = ?";
            Object params[] = {password,id};
            execute = BaseDao.execute(connection, sql, params, pstm);
            BaseDao.closeResource(null,pstm,null);
        }

        return execute;
    }
    <servlet>
        <servlet-name>UserServlet</servlet-name>
        <servlet-class>com.vekzjj.servlet.user.UserServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/jsp/user.do</url-pattern>
    </servlet-mapping>
  1. UserService层
    //修改当前用户密码
    public boolean updatePwd(int id, int pwd) throws SQLException;
  1. UserService实现类
    public boolean updatePwd(int id, int pwd){
        Connection connection = null;
        boolean flag = false;
        connection = BaseDao.getConnection();
        //修改密码
        try {
            if (userDao.updatePwd(connection,id,pwd) > 0){
                flag = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResource(connection,null,null);
        }
        return flag;
    }
  1. 实现复用,需要提取出方法
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if (method != null && method.equals("savepwd")){
            this.updatePwd(req,resp);
        }
    }
   public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
            //从Session里面拿ID;
            Object o = req.getSession().getAttribute(Constants.USER_SESSION);

            boolean flag = false;
            try {
                String newpassword = req.getParameter("newpassword");
                if (o != null && newpassword != null){
                    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","新密码有问题");
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }
        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

优化密码修改使用Ajax

  1. 阿里巴巴的fastjson
<!-- https://mvnrepository.com/artifact/com.alibaba/fastjson -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.79</version>
</dependency>
 //验证旧密码,session中有用户的旧密码
    public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
        //从Session里面拿ID;
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        //万能的Map:结果集
        Map<String, String> resultMap = new HashMap<String, String>();
        if(o==null){
            //Session失效了,或者session过期了

            resultMap.put("result","sessionerror");
        }else if (StringUtils.isNullOrEmpty(oldpassword)){
            //输入的密码为空
            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();
            //JSONArray阿里巴巴的工具类,转换格式的

            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

用户管理实现

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-oU4RlQfd-1648634539460)(C:\Users\周俊杰\Desktop\新建文本文档 (2)]\image-20220327164420424.png)

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

​ userlist.jsp

​ rollpage.jsp

1、获取用户数量

  1. UserDao
    //根据用户名或者角色查询用户总数
    public int getUserCount(Connection connection,String username,int userRole);
  1. UserDaolmpl
    public int getUserCount(Connection connection, String username, int userRole) {
        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<>();//存放我们的参数

            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[] params = list.toArray();

            System.out.println("userDaoImpl->getUserCount"+ sql.toString());

            try {

                rs = BaseDao.execute(connection, pstm, rs, sql.toString(), params);

                if (rs.next()){
                    count = rs.getInt("count");//从结果集中获取数量
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                BaseDao.closeResource(null,pstm,rs);
            }
            }
        return count;

        }
  1. UserService
//查询记录数
public int getUserCount(String username,int userRole);
  1. UserServiceImpl
public int getUserCount(String username, int userRole) {
    Connection connection = null;
    int count = 0;

    connection = BaseDao.getConnection();
    count = userDao.getUserCount(connection, username, userRole);

    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.userdaolmpl

public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws SQLException {

        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);
            }
            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.execute(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、获取角色操作

RoleDao

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

RoleDaoImpl

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

RoleService

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

RoleServiceImpl

public class RoleServiceImpl implements RoleService{

    //引入Dao
    private RoleDao roleDao;

    public RoleServiceImpl() {
        roleDao = new RoleDaoImpl();
    }
    @Override
    public List<Role> getRoleList() {

        List<Role> roleList = null;
        Connection connection = null;

        try {
            connection = BaseDao.getConnection();
            roleList = roleDao.getRoleList(connection);
        } catch (SQLException 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) throws IOException {

        //查询用户列表
        //从前端获取数据
        String queryUserName = req.getParameter("queryname");
        String UserRole = 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 (UserRole!=null && !UserRole.equals("")){
            queryUserRole = Integer.parseInt(UserRole);//给查询出来的赋值 0,1,2,3
        }
        if (pageIndex != null){
            //解析页面
            try {
                currentPageNo = Integer.parseInt(pageIndex);
            }catch (Exception e){
                resp.sendRedirect("error.jsp");
            }
        }
        //获取用户的总数(分页:上一页,下一页的情况)31.04
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);

        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalPageCount(totalCount);

        int totalPageCount = ((int) (totalCount/pageSize))+1;

        //控制首页和尾页,当前是第一页就不能往前,是最后一页就不能往后了
        if (currentPageNo < 1){
            currentPageNo = 1;//如果页面小于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();//37.16
        }
    }

主页面
用户管理
添加用户
密码修改
登录

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值