跟着狂神学java---javabean的作用,学习MVC了解Servlet,sevice,dao的关系,smbms项目练习加强理解

一、JavaBean

实体类

JavaBean有特定的写法:

  • 必须要有一个无参构造
  • 属性必须私有化
  • 必须有对应的get/set方法

一般用来和数据库的字段做映射
ORM:对应关系映射

  • 表–>类
  • 字段–>属性
  • 行记录–>对象
idnameageaddress
1
2
class People{
	private int id;
	private String name;
	private int age;
	private String address;
}
class A{


}

实体类

javaBean有特定的写法

二、MVC三层架构

什么是MVC:Model view Controller 模型、视图、控制器

1、早些年

请添加图片描述

用户直接访问控制层,控制层就可以直接造作数据库:

servlet---CRUD--->数据库
弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求、相应、试图跳转、处理JDBC、处理业务代码、处理逻辑代码

架构:没有什么是加一层解决不了的!
程序员调用
|  |
|  |
JDBC
|  |
|  |
mysql Oracle sqlServet....


2、三层架构

请添加图片描述

Model

  • 业务处理:业务逻辑(Service)
  • 数据持久层:CRUD (Dao)数据持久化对象

View

  • 展示数据
  • 提供链接发起Servlet请求(a,form,img······)

Controller

  • 接受用户的请求:(req:请求参数、session信息······)
  • 交给业务层处理对应的代码
  • 控制视图的跳转
登录---->接受用户的登录请求---->处理用户的请求(获取用户登录的参数:username,password)--->交给业务层
处理登录业务(判断用户密码是否正确:事物)---->Dao层查询用户名和密码是否正确--->数据库

三、SMBMS项目分析

请添加图片描述

数据库:

请添加图片描述

项目如何搭建?

考虑使用不使用Maven?依赖,jar

项目搭建准备

  1. 搭建一个mavenweb项目

  2. 配置tomcat

  3. 测试项目是否可以跑起来

  4. 导入向目中会用到的jar包

    jsp,Servlet,mysql驱动,jstl,standered

  5. 创建项目包结构

请添加图片描述

  1. 编写实体类(javabean)

请添加图片描述

ORM映射:表-类映射
  1. 编写基础公共类

    1. 数据库配置文件

      driver=com.mysql.cj.jdbc.Driver
      url=jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf-8
      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 conn = null;
              try {
                  Class.forName(driver);
                  conn = DriverManager.getConnection(url,username,password);
              } catch (ClassNotFoundException e) {
                  e.printStackTrace();
              } catch (SQLException throwables) {
                  throwables.printStackTrace();
              }
              return conn;
          }
      
          //编写查询公共类
          public static ResultSet execute(Connection conn,PreparedStatement pstat,ResultSet set,String sql,Object[] params){
              try {
                  pstat = conn.prepareStatement(sql);
      
                  for (int i = 0;i<params.length;i++){
                      pstat.setObject(i+1,params[i]);
                  }
                  set = pstat.executeQuery();
      
              } catch (SQLException throwables) {
                  throwables.printStackTrace();
              }
              return set;
          }
          //编写增删改公共方法
          public static int execute(Connection conn,PreparedStatement pstat,String sql,Object[] params){
              int updateRows = 0;
              try {
                  pstat = conn.prepareStatement(sql);
                  for (int i = 0;i<params.length;i++){
                      pstat.setObject(i+1,params[i]);
                  }
                  updateRows = pstat.executeUpdate();
              } catch (SQLException throwables) {
                  throwables.printStackTrace();
              }
              return updateRows;
          }
      
          //关闭连接
          public static boolean close(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;
          }
          //复写关闭方法
          public static boolean close(PreparedStatement preparedStatement,Connection connection){
              Boolean flag = true;
              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. 字符编码过滤器

  2. 导入静态资源

    链接:

    百度网盘smbms静态资源

    提取码:hzak

登录功能实现

请添加图片描述

  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 UserDaoImp1 implements UserDao {
        public User getLoginUser(Connection connection, String userCode) throws SQLException {
            PreparedStatement pstat = null;
            ResultSet resultSet = null;
            User user = null;
            if (connection!=null){
                String sql = "select * from smbms_user where userCode=?";
                Object[] params = {userCode};
    
                resultSet = BaseDao.execute(connection,pstat,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.close(resultSet,pstat,null);
            }
            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 UserDaoImp1();
        }
        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.close(null,null,connection);
            }
            return user;
        }
    }
    
  7. 编写Servlet

    public class LoginServlet extends HttpServlet {
    
        //Servlet:控制层,调用业务层
        @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");
    
            //和数据库中的密码进行对比,调用业务层
            UserService 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 {
            super.doPost(req, resp);
        }
    }
    
  8. 注册Servlet

    <servlet>
            <servlet-name>LoginServlet</servlet-name>
            <servlet-class>com.zhao.servlet.user.LoginServlet</servlet-class>
        </servlet>
        <servlet-mapping>
            <servlet-name>LoginServlet</servlet-name>
            <url-pattern>/login.do</url-pattern>
        </servlet-mapping>
    
  9. 测试访问以上功能访问成功

登录功能优化

注销功能

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

public class LogoutServlet 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 {
        super.doPost(req, resp);
    }
}

注册xml

<servlet>
        <servlet-name>LogoutServlet</servlet-name>
        <servlet-class>com.zhao.servlet.user.LogoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LogoutServlet</servlet-name>
        <url-pattern>/jsp/logout.do</url-pattern>
    </servlet-mapping>

登录拦截器优化

编写一个过滤器,并注册xml

public class SysFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

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

    }

    public void destroy() {

    }
}
<!--系统拦截:用户登录过滤器-->
    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.zhao.filter.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/jsp/*</url-pattern>
    </filter-mapping>

测试,登录,注销,权限。

密码修改

  1. 导入前端素材

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

请添加图片描述

  1. UserDao接口

    public interface UserDao {
        //得到要登录的用户
        public User getLoginUser(Connection connection, String userCode) throws SQLException;
    
        //修改当前密码
        public int updatePwd(Connection connection,int id,int password) throws SQLException;
    }
    
  2.  public class UserDaoImp1 implements UserDao {
         public User getLoginUser(Connection connection, String userCode) throws SQLException {
             PreparedStatement preparedStatement = null;
             ResultSet resultSet = null;
             User user = null;
             if (connection!=null){
                 String sql = "select * from smbms_user where userCode=?";
                 Object[] params = {userCode};
                 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.close(resultSet,preparedStatement,null);
             }
             return user;
    
         }
    
     //    修改当前密码
         public int updatePwd(Connection connection, int id, int password) throws SQLException {
             PreparedStatement pstat = null;
             int update = 0;
             if (connection!=null){
                 String sql = "update smbms_user set userPassword = ? where id = ?";
                 Object[] params = {password,id};
                 update = BaseDao.execute(connection,pstat,sql,params);
                 BaseDao.close(null,pstat,null);
             }
             return update;
         }
     }
    
  3. UserService层

    public boolean updatePwd(int id,String pwd);
    
  4. UserService实现类

     //修改密码
        public boolean updatePwd(int id, String pwd) {
            Connection conn  = null;
            boolean flag = false;
            conn = BaseDao.getConnection();
            UserDao userDao = new UserDaoImp1();
            //修改密码
            try {
                if (userDao.updatePwd(conn,id,pwd)>0){
                    flag = true;
                }
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                BaseDao.close(null,null,conn);
            }
            return flag;
        }
    
  5. Servlet记得实现复用,需要提出取方法!

    //实现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);
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            super.doPost(req, resp);
        }
    
        public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
            //从Session里面拿id
            Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
            String newpassword = req.getParameter("newpassword");
            System.out.println("UserPassword = "+newpassword);
            boolean flag = false;
    
            System.out.println(attribute!=null);
            System.out.println(!StringUtils.isNullOrEmpty(newpassword));
    
            if (attribute!=null && newpassword!=null && newpassword.length()!=0){
                UserService userService = new UserServiceImpl();
                flag = userService.updatePwd(((User)attribute).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();
            }
        }
    }
    
  6. 测试

优化密码修改使用Ajax

  1. 阿里巴巴的fastjson

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

    //验证旧密码,Seesion中有旧密码
        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();//Session中的用户密码
                if (oldpassword.equals(userPassword)){
                    resultMap.put("result","true");
                }else {
                    resultMap.put("result","false");
                }
            }
        
            try {
                resp.setContentType("application/json");
                Writer writer = resp.getWriter();
                //JSONArray 阿里巴巴的JSON工具类,转换格式
                /*
                * resultMap = ["result","sessionerror","result","false"]
                * */
                writer.write(JSONArray.toJSONString(resultMap));
                writer.flush();
                writer.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
  3. 测试

用户管理实现

思路:

请添加图片描述

  1. 导入分页的工具类

  2. 用户列表页面导入

    1. userlist.jsp
    2. rollpage.jsp

1. 获取用户数量

  1. UserDao

    //查询用户总数
        public int getUserCount(Connection connection,String userName,int userRole)throws SQLException;
    
  2. UserDaoImp1

    //查询用户名或者角色查询用户总量
        public int getUserCount(Connection connection, String userName, int userRole) throws SQLException {
            PreparedStatement pstat = 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+"%");//index:0
                }
    
                if (userRole>0){
                    sql.append("and u.userRole = ? ");
                    list.add(userRole);//index:1
                }
    
                //怎么把list转换为数组
                Object[] objects = list.toArray();
    
                System.out.println(sql.toString());
    
                rs = BaseDao.execute(connection,pstat,rs,sql.toString(),objects);
                if (rs.next()){
                    count = rs.getInt("count");//从结果集中获取最终的数量
                }
                BaseDao.close(rs,pstat,null);
            }
            return count;
        }
    
  3. UserService

    //查询记录数
        public int getUserCount(String userName,int userRole);
    
  4. UserServiceLmpI

    public int getUserCount(String userName, int userRole) {
            Connection conn = null;
            int count = 0;
            try {
                conn = BaseDao.getConnection();
                count = userDao.getUserCount(conn,userName,userRole);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                BaseDao.close(null,null,conn);
            }
            return count;
        }
    

2.获取用户列表

  1. UserDao

    //获取用户列表
        public List<User> getUserList(Connection connection,String userName,int userRole,int currentPageNo,int pageSize)throws Exception;
    
  2. UserDaoImp1

    //获取用户列表
        public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception {
            PreparedStatement pstat = null;
            ResultSet rs = null;
            List<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 + "%");//index:0
                }
    
                if (userRole > 0) {
                    sql.append("and u.userRole = ? ");
                    list.add(userRole);//index:1
                }
                //在数据库分页中,分页使用limit startIndex,pageSize;总数
                //当前页 (当前页-1)*页面大小
                //0,5   1   0 01234
                //5,5   2   5 56789
                //10,5  3   10 1112131415
    
    
    
                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,pstat,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);
                }
            }
            return userList;
        }
    
  3. UserService

    public List<User> getUserList(String queryUserName,int queryUserRole,int currentPageNo,int pageSize);
    
  4. UserServiceLmpI

    public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) {
            Connection conn = 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 {
                conn = BaseDao.getConnection();
                userList = userDao.getUserList(conn,queryUserName,queryUserRole,currentPageNo,pageSize);
            } catch (Exception e) {
                e.printStackTrace();
            }finally {
                BaseDao.close(null,null,conn);
            }
            return userList;
        }
    

3.获取角色列表

  1. RoleDao

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

    //获取角色列表
        public List<Role> getRoleList(Connection connection) throws SQLException {
            PreparedStatement pstat = 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,pstat,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.close(rs,pstat,null);
            }
            return roleList;
        }
    
  3. RoleService

    public List<Role> getRoleList();
    
  4. RoleServicelmpI

    //获取角色列表
        public List<Role> getRoleList(){
            Connection conn = null;
            List<Role> roleList = null;
            try {
                conn = BaseDao.getConnection();
                roleList = roleDao.getRoleList(conn);
            } catch (SQLException throwables) {
                throwables.printStackTrace();
            }finally {
                BaseDao.close(null,null,conn);
            }
            return roleList;
        }
    

4.用户显示的Servlet

  1. 获取用户前端的数据(查询)

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

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

  4. 用户列表展示

  5. 返回前端

    //重点和难点
        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 pageSize = 5;//可以吧这个写到配置文件中,方便后期修改
            int currentPageNo = 1;
    
            if (queryusername==null){
                queryusername = "";
            }
            if (temp!=null && !temp.equals("")){
                queryUserRole = Integer.parseInt(temp); //给查询赋值! 0,1,2,3
            }
            if (pageIndex!=null){
                currentPageNo = Integer.parseInt(pageIndex);
            }
            //获取用户的总数(分页:上一页 下一页)
            int totalCount = userService.getUserCount(queryusername,queryUserRole);
            //总页数支持
            PageSupport pageSupport = new PageSupport();
            pageSupport.setCurrentPageNo(currentPageNo);
            pageSupport.setPageSize(pageSize);
            pageSupport.setTotalCount(totalCount);
    
            int totalPageCount  = ((int)(totalCount/pageSize))+1;
    
            //控制首页和尾页
            //如果页面小于1,就显示第一页的东西
            if (currentPageNo<1){
                currentPageNo = 1;
            }else if (currentPageNo>totalPageCount){//当前页大于了最后一页
                currentPageNo = totalPageCount;
            }
    
            //获取用户列表前端展示
            userList = userService.getUserList(queryusername,queryUserRole,currentPageNo,pageSize);
            if (userList==null){
                System.out.println("你的程序出错啦!");
            }
            req.setAttribute("userList",userList);
    
            RoleServicelmpI roleService = new RoleServicelmpI();
            List<Role> roleList = roleService.getRoleList();
            req.setAttribute("roleList",roleList);
            req.setAttribute("totalCount",totalCount);
            req.setAttribute("currentPageNo",currentPageNo);
            req.setAttribute("totalPageCount",totalPageCount);
    
            //返回前端
            try {
                req.getRequestDispatcher("userlist.jsp").forward(req,resp);
            } catch (ServletException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
    
        }
    

架构分析

请添加图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值