超市管理统SMBMS笔记

SMBMS

原理图

数据库:

项目如何搭建?

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

项目搭建准备工作

  1. 搭建一个maven web项目

  2. 配置Tomcat

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

  4. 导入项目中会遇到的jar包

    sevlet-api,jsp-api,jstl,jstl-api,mysql-connector-java

  5. 构建项目框架

  6. 编写实体类

    ORM:表-类映射

  7. 编写基础公共类

    1. 数据库配置文件 

      diver=com.mysql.jdbc.Driver
       url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8
       username=root
       password=123456
    2. 编写数据库的公共类

       
        1 package com.study.dao;
        2   3  import java.io.IOException;
        4  import java.io.InputStream;
        5  import java.sql.*;
        6  import java.util.Properties;
        7  //操作数据库的公共类
        8  public class BaseDao {
        9      private static String driver;
       10      private static String url;
       11      private static String username;
       12      private static String password;
       13  14      //静态代码块,类加载的时候就初始化了
       15      static{
       16          Properties properties = new Properties();
       17          //通过类加载器获取对用的资源
       18          InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
       19  20          try {
       21              properties.load(is);
       22          } catch (IOException e) {
       23              e.printStackTrace();
       24          }
       25  26          driver = properties.getProperty("driver");
       27          url = properties.getProperty("url");
       28          username = properties.getProperty("username");
       29          password = properties.getProperty("password");
       30      }
       31      //获取数据库的连接
       32      public static Connection getConnection(){
       33          Connection connection = null;
       34          try {
       35              connection = DriverManager.getConnection(url, username, password);
       36          } catch (SQLException e) {
       37              e.printStackTrace();
       38          }
       39          return connection;
       40      }
       41      //编写查询公共类
       42      public static ResultSet excute(Connection connection, String sql, Object[] params, ResultSet resultSet, PreparedStatement preparedStatement) throws SQLException {
       43        //预编译的sql,在后面直接执行就可以了
       44          preparedStatement = connection.prepareStatement(sql);
       45  46          for (int i = 0; i < params.length; i++) {
       47              //setObject,占位符从1开始,但是我们的数组是从0开始!
       48              preparedStatement.setObject(i+1,params[i]);
       49          }
       50  51          resultSet = preparedStatement.executeQuery();
       52          return resultSet;
       53      }
       54  55      //编写增删改公共类
       56      public static int excute(Connection connection,String sql,Object[] params,PreparedStatement preparedStatement) throws SQLException {
       57          preparedStatement = connection.prepareStatement(sql);
       58  59          for (int i = 0; i < params.length; i++) {
       60              //setObject,占位符从1开始,但是我们的数组是从0开始!
       61              preparedStatement.setObject(i+1,params[i]);
       62          }
       63  64          int updateRows = preparedStatement.executeUpdate();
       65          return updateRows;
       66      }
       67  68      //释放资源
       69      public static boolean closeResourse(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){
       70          boolean flag = true;
       71  72          if (resultSet!=null){
       73              try {
       74                  resultSet.close();
       75                  //GC回收
       76                  resultSet = null;
       77              } catch (SQLException e) {
       78                  e.printStackTrace();
       79                  flag = false;
       80              }
       81          }
       82  83          if (preparedStatement!=null){
       84              try {
       85                  preparedStatement.close();
       86                  //GC回收
       87                  preparedStatement = null;
       88              } catch (SQLException e) {
       89                  e.printStackTrace();
       90                  flag = false;
       91              }
       92          }
       93  94          if (connection!=null){
       95              try {
       96                  connection.close();
       97                  //GC回收
       98                  connection = null;
       99              } catch (SQLException e) {
      100                  e.printStackTrace();
      101                  flag = false;
      102              }
      103          }
      104          return flag;
      105      }
      106  }
    3. 编写字符编码过滤器

  8. 导入静态资源

登录功能实现

  1. 设置首页

     <!-- 设置欢迎页面 -->
     <welcome-file-list>
         <welcome-file>login.jsp</welcome-file>
     </welcome-file-list>
  2. 编写dao层登录用户的接口

     public interface UserDao {
         //得到要登录的用户
         public User getLoginUser(Connection connection, String userCode) throws SQLException;
     }
  3. 编写dao层接口的实现类

     
     1 package com.study.dao.user;
     2  3  import com.study.dao.BaseDao;
     4  import com.study.pojo.User;
     5  6  import java.sql.Connection;
     7  import java.sql.PreparedStatement;
     8  import java.sql.ResultSet;
     9  import java.sql.SQLException;
    10 11  public class UserDaoImpl implements UserDao{
    12      //得到要登录的用户
    13      public User getLoginUser(Connection connection, String userCode) throws SQLException {
    14          PreparedStatement pstm = null;
    15          ResultSet rs = null;
    16          User user = null;
    17 18          if (connection!=null){
    19              String sql = "select * from smbms_user where userCode = ?";
    20              Object[] params = {userCode};
    21 22              rs = BaseDao.excute(connection, pstm, rs, sql, params);
    23 24              if(rs.next()){
    25                  user = new User();
    26                  user.setId(rs.getInt("id"));
    27                  user.setUserCode(rs.getString("userCode"));
    28                  user.setUserName(rs.getString("userName"));
    29                  user.setUserPassword(rs.getString("userPassword"));
    30                  user.setGender(rs.getInt("gender"));
    31                  user.setBirthday(rs.getDate("birthday"));
    32                  user.setPhone(rs.getString("phone"));
    33                  user.setAddress(rs.getString("address"));
    34                  user.setUserRole(rs.getInt("userRole"));
    35                  user.setCreateBy(rs.getInt("createdBy"));
    36                  user.setCreationDate(rs.getTimestamp("creationDate"));
    37                  user.setModifyBy(rs.getInt("modifyBy"));
    38                  user.setModifyDate(rs.getTimestamp("modifyDate"));
    39              }
    40              BaseDao.closeResourse(null,pstm,rs);//connection不关,业务层可能要用
    41          }
    42          return user;
    43      }
    44  }
  4. 业务层接口

     public interface UserService {
         //用户登录
         public User login(String userCode, String password);
     }
  5. 业务层实现类

     1  package com.study.service.user;
     2  3  import com.study.dao.BaseDao;
     4  import com.study.dao.user.UserDao;
     5  import com.study.dao.user.UserDaoImpl;
     6  import com.study.pojo.User;
     7  import org.junit.Test;
     8  9  import java.sql.Connection;
    10  import java.sql.SQLException;
    11 12  public class UserServiceImpl implements UserService{
    13 14      //业务层都会调用dao层,所以我们要引入Dao层
    15      private UserDao userDao;
    16      public UserServiceImpl(){
    17         userDao = new UserDaoImpl();
    18      }
    19      public User login(String userCode, String password) {
    20          Connection connection = null;
    21          User user = null;
    22          try {
    23              connection = BaseDao.getConnection();
    24              //业务层调用对应的具体数据库操作
    25              user = userDao.getLoginUser(connection, userCode);
    26          } catch (SQLException e) {
    27              e.printStackTrace();
    28          }finally {
    29              BaseDao.closeResourse(connection,null,null);
    30          }
    31          return user;
    32      }
    33 34      @Test 
    35      public void test(){
    36          UserServiceImpl userService = new UserServiceImpl();
    37          User admin = userService.login("admin", "dhewfghewe");
    38          System.out.println(admin.getUserPassword());
    39      }
    40  }
  6. 编写Servlet

     1 package com.study.servlet.user;
     2  3  import com.study.dao.user.UserDaoImpl;
     4  import com.study.pojo.User;
     5  import com.study.service.user.UserService;
     6  import com.study.service.user.UserServiceImpl;
     7  import com.study.util.Constants;
     8  import jakarta.servlet.ServletException;
     9  import jakarta.servlet.http.HttpServlet;
    10  import jakarta.servlet.http.HttpServletRequest;
    11  import jakarta.servlet.http.HttpServletResponse;
    12 13  import java.io.IOException;
    14 15  public class LoginServlet extends HttpServlet {
    16 17      //Servlet:控制层,调用业务层代码
    18      @Override
    19      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    20 21          System.out.println("LoginServlet--start....");
    22 23          //获取用户名和密码
    24          String userCode = req.getParameter("userCode");
    25          String userPassword = req.getParameter("userPassword");
    26          
    27          //和数据库中的密码进行对比,调用业务层;
    28          UserService userService = new UserServiceImpl();
    29          User user = userService.login(userCode, userPassword);
    30 31          if (user!=null){//查有此人,可以登录
    32              //将用户的信息放到Session中;
    33              req.getSession().setAttribute(Constants.USER_SESSION,user);
    34              //跳转到主页
    35              resp.sendRedirect("jsp/frame.jsp");
    36          }else{//查无此人,无法登录
    37              //转发会登录界面,顺带提示它,用户名或者密码错误;
    38              req.setAttribute("error","用户名或者密码不正确");
    39              req.getRequestDispatcher("login.jsp").forward(req,resp);
    40 41          }
    42 43      }
    44 45      @Override
    46      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    47          doGet(req, resp);
    48      }
    49  }
  7. 注册Servlet

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

登录功能优化

注销功能:

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

 
 1 package com.study.servlet.user;
 2  3  import com.study.util.Constants;
 4  import jakarta.servlet.ServletException;
 5  import jakarta.servlet.http.HttpServlet;
 6  import jakarta.servlet.http.HttpServletRequest;
 7  import jakarta.servlet.http.HttpServletResponse;
 8  9  import java.io.IOException;
10 11  public class LogoutServlet extends HttpServlet {
12      @Override
13      protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
14          //移除用户的Constants.USER_SESSION
15          req.getSession().removeAttribute(Constants.USER_SESSION);
16          resp.sendRedirect(req.getContextPath()+"/login.jsp");//返回登录界面
17      }
18 19      @Override
20      protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
21          doGet(req, resp);
22      }
23  }

注册

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

登录拦击优化

编写一个过滤器,并注册

 
package com.study.filter;
 ​
 import com.study.pojo.User;
 import com.study.util.Constants;
 import jakarta.servlet.*;
 import jakarta.servlet.http.HttpServlet;
 import jakarta.servlet.http.HttpServletRequest;
 import jakarta.servlet.http.HttpServletResponse;
 ​
 import java.io.IOException;
 ​
 public class SysFilter implements Filter {
     public void init(FilterConfig filterConfig) throws ServletException {
 ​
     }
 ​
     public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
         HttpServletRequest request = (HttpServletRequest) req;
         HttpServletResponse response = (HttpServletResponse) resp;
         //过滤器,从Session中获取用户
         User user = (User)request.getSession().getAttribute(Constants.USER_SESSION);
 ​
         if(user==null){//已经被一处或者注销了,或者未登录
             response.sendRedirect("/error.jsp");
         }else{
             chain.doFilter(req,resp);
         }
 ​
     }
 ​
     public void destroy() {
 ​
     }
 }
 <!-- 用户过滤器 -->
 <filter>
     <filter-name>SysFilter</filter-name>
     <filter-class>com.study.filter.SysFilter</filter-class>
 </filter>
 <filter-mapping>
     <filter-name>SysFilter</filter-name>
     <url-pattern>/jsp/*</url-pattern>
 </filter-mapping>

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

密码修改

  1. 导入前端素材

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

     

     

  3. UserDao接口

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

    public int updatePwd(Connection connection, int id, int password) throws SQLException {
         PreparedStatement pstm = null;
         int excute = 0;
     ​
     ​
         if (connection!=null){
             String sql = "update smbms_user set userPassword = ? where id = ?";
             Object[] params = {password,id};
             excute = BaseDao.excute(connection, pstm, sql, params);
             BaseDao.closeResourse(null,pstm,null);
         }
         return excute;
     }
  5. UserService层

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

     1 public boolean updatePwd(int id, int pwd) {
     2      Connection connection = null;
     3      boolean flag = false;
     4  5      //修改密码
     6      try {
     7          connection = BaseDao.getConnection();
     8          if (userDao.updatePwd(connection, id, pwd) > 0){
     9              flag = true;
    10          }
    11      } catch (SQLException e) {
    12          e.printStackTrace();
    13      }finally {
    14          BaseDao.closeResourse(connection,null,null);
    15      }
    16      return flag;
    17  }
    18 19  //记得注册
  7. 记得实现复用,需要提出方法! 

    @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);
         }
     }
  8. 测试

优化密码修改使用Ajax

  1. 阿里巴巴的fastjson

    <dependency>
         <groupId>com.alibaba</groupId>
         <artifactId>fastjson</artifactId>
         <version>1.2.80</version>
     </dependency>
  2. 后台代码修改

     1 //修改密码
     2  public void updatePwd(HttpServletRequest req, HttpServletResponse resp){
     3      //从Session里面拿ID;
     4      Object o = req.getSession().getAttribute(Constants.USER_SESSION);
     5      String newpassword = req.getParameter("newpassword");
     6      boolean flag = false;
     7  8      if(o!=null && !StringUtils.isNullOrEmpty(newpassword)){
     9          UserService userService = new UserServiceImpl();
    10          flag = userService.updatePwd(((User)o).getId(), newpassword);
    11          if (flag){
    12              req.setAttribute("message","修改密码成功,请推出,使用新密码登录");
    13              //密码修改成功,移除当前Session
    14              req.getSession().removeAttribute(Constants.USER_SESSION);
    15          }else{
    16              req.setAttribute("message","修改密码失败");
    17          }
    18      }else {
    19          req.setAttribute("message","新密码有问题");
    20      }
    21 22      try {
    23          resp.sendRedirect("pwdmodify.jsp");
    24      } catch (IOException e) {
    25          e.printStackTrace();
    26      }
    27  }
    28 29  //验证旧密码,session中有用户的密码
    30  public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
    31      //从Session里面拿ID;
    32      Object o = req.getSession().getAttribute(Constants.USER_SESSION);
    33      String oldpassword = req.getParameter("oldpassword");
    34 35      //万能的Map : 结果集
    36      Map<String, String> resultMap = new HashMap<String, String>();
    37 38      if(o==null){//session失效了,session过期了
    39          resultMap.put("result","sessionerror");
    40      }else if(StringUtils.isNullOrEmpty(oldpassword)){//输入的密码为空
    41          resultMap.put("result","error");
    42      }else{
    43          String userPassword = ((User) o).getUserPassword();//Session中用户的密码
    44          if (oldpassword.equals(userPassword)){
    45              resultMap.put("result","true");
    46          }else{
    47              resultMap.put("result","false");
    48          }
    49      }
    50 51      try {
    52          resp.setContentType("application/json");
    53          PrintWriter writer = null;
    54          writer = resp.getWriter();
    55          //JSONArray 阿里巴巴的JSON工具类,转换格式
    56          /*
    57              * resultMap = ["result","sessionerror","result","error"]
    58              * JSON格式 = {key:value}
    59              * */
    60          writer.write(JSONArray.toJSONString(resultMap));
    61          writer.flush();
    62          writer.close();
    63      } catch (IOException e) {
    64          e.printStackTrace();
    65      }
    66  }
  3. 测试

用户管理实现

思路:

  1. 要导入分页的工具类

  2. 用户列表页面导入

    userlist.jsp

    rollpage.jsp

获取用户数量

UserDao

//根据用户名或者角色查询用户数量
public int getUserCount(Connection connection,String username,int userRole)throws SQLException;

UserDaoImpl

 1 //根据用户名或者角色查询用户数量
 2 public int getUserCount(Connection connection, String username, int userRole) throws SQLException {
 3     PreparedStatement pstm = null;
 4     ResultSet rs = null;
 5     int count = 0;
 6 
 7     if (connection!=null){
 8         StringBuffer sql = new StringBuffer();
 9         sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id");
10         ArrayList<Object> list = new ArrayList<Object>();//存放我们的参数
11 
12         if (!StringUtils.isNullOrEmpty(username)){
13             sql.append(" and u.userName like ?");  //and前需要一个空格,否则sql拼接的时候有问题
14             list.add("%"+username+"%");//index:0
15         }
16 
17         if(userRole>0){
18             sql.append(" and u.userRole = ?");
19             list.add(userRole);//index:1
20         }
21 
22         //怎么把list转成数组
23         Object[] params = list.toArray();
24 
25         System.out.println("UserDaoIml-->getUserCount:"+sql.toString());//输出最后完整的代码
26 
27         rs = BaseDao.excute(connection, pstm, rs, sql.toString(), params);
28 
29         if (rs.next()){
30             count = rs.getInt("count");//从结果集中获得最终的数量
31         }
32         BaseDao.closeResourse(null,pstm,rs);
33     }
34     return count;
35 }

UserService

//查询记录数
public int getUserCount(String username,int userRole);

UserServiceImpl

//查询记录数
public int getUserCount(String username, int userRole) {

    Connection connection = null;
    int count = 0;
    try {
        connection = BaseDao.getConnection();
        count = userDao.getUserCount(connection, username, userRole);
    } catch (SQLException e) {
        e.printStackTrace();
    }finally {
        BaseDao.closeResourse(connection,null,null);
    }
    return count;
}

获取用户列表

UserDao

//根据用户条件获取用户列表
public List<User> getUserList(Connection connection,String userName,int userRole,int currentPageNo,int pageSize)throws Exception;

UserDaoImpl

 1 //根据用户条件获取用户列表
 2 public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception {
 3     PreparedStatement pstm = null;
 4     ResultSet rs = null;
 5     List<User> userList = new ArrayList<User>();
 6     if (connection!=null){
 7         StringBuffer sql = new StringBuffer();
 8         sql.append("select u.*,r.roleName as userRoleName from smbms_user u,smbms_role r where u.userRole = r.id");
 9         List<Object> list = new ArrayList<Object>();//存放我们的参数
10 
11         if (!StringUtils.isNullOrEmpty(userName)){
12             sql.append(" and u.userName like ?");  //and前需要一个空格,否则sql拼接的时候有问题
13             list.add("%"+userName+"%");//index:0
14         }
15 
16         if(userRole>0){
17             sql.append(" and u.userRole = ?");
18             list.add(userRole);//index:1
19         }
20         sql.append(" order by creationDate DESC limit ?,?");
21         currentPageNo = (currentPageNo-1)*pageSize;
22         list.add(currentPageNo);
23         list.add(pageSize);
24 
25         Object[] params = list.toArray();
26         System.out.println("sql-->"+sql.toString());
27         rs = BaseDao.excute(connection, pstm, rs, sql.toString(), params);
28         while (rs.next()){
29             User _user = new User();
30             _user.setId(rs.getInt("id"));
31             _user.setUserCode(rs.getString("userCode"));
32             _user.setUserName(rs.getString("userName"));
33             _user.setGender(rs.getInt("gender"));
34             _user.setBirthday(rs.getDate("birthday"));
35             _user.setPhone(rs.getString("phone"));
36             _user.setAddress(rs.getString("address"));
37             _user.setUserRole(rs.getInt("userRole"));
38             _user.setCreateBy(rs.getInt("createdBy"));
39             userList.add(_user);
40         }
41         BaseDao.closeResourse(null,pstm,rs);
42     }
43     return userList;
44 }

UserService

//根据条件查询用户列表
public List<User> getUserList(String queryUserName,int queryUserRole,int currentPageNo,int pageSize);

UserServiceImpl

 1 //根据条件查询用户列表
 2 public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) {
 3     Connection connection = null;
 4     List<User> userList = null;
 5     System.out.println("queryUserName--->"+queryUserName);
 6     System.out.println("queryUserRole--->"+queryUserRole);
 7     System.out.println("currentPageNo--->"+currentPageNo);
 8     System.out.println("pageSize--->"+pageSize);
 9 
10     try {
11         connection = BaseDao.getConnection();
12         userList = userDao.getUserList(connection,queryUserName,queryUserRole,currentPageNo,pageSize);
13     } catch (Exception e) {
14         e.printStackTrace();
15     }finally {
16         BaseDao.closeResourse(connection,null,null);
17     }
18     return userList;
19 }

获取角色列表

为了我们职责统一,可以把角色的操作单独放在一个包中,和POJO类对应

RoleDao

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

RoleDaoImpl

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

    PreparedStatement pstm = null;
    ResultSet rs = null;
    ArrayList<Role> roleList = new ArrayList<Role>();

    if(connection!=null){
        String sql = "select * from smbms_role";
        Object[] parame = {};
        rs = BaseDao.excute(connection,pstm,rs,sql,parame);

        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.closeResourse(null,pstm,rs);
    }
    return roleList;
}

RoleService

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

RoleServiceImpl

package com.study.service.role;

import com.study.dao.BaseDao;
import com.study.dao.role.RoleDao;
import com.study.dao.role.RoleDaoImpl;
import com.study.pojo.Role;

import javax.sql.RowSetInternal;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class RoleServiceImpl implements RoleService {

    //引入Dao
    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 e) {
            e.printStackTrace();
        }finally {
            BaseDao.closeResourse(connection,null,null);
        }
        return roleList;
    }
}

用户用于显示的Servlet

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

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

  3. 为了实现分页,需要极端当前页面合总页数,页面大小……

  4. 用户列表展示

  5. 返回前端

 1 //重点、难点
 2 public void query(HttpServletRequest req, HttpServletResponse resp){
 3 
 4     //查询用户列表
 5 
 6     //从前端端获取数据:
 7     String queryUserName = req.getParameter("queryname");
 8     String temp = req.getParameter("queryUserRole");
 9     String pageIndex = req.getParameter("pageIndex");
10     int queryUserRole = 0;
11 
12     //获取用户列表
13     UserServiceImpl userService = new UserServiceImpl();
14     List<User> userList = null;
15 
16     //第一次走这个请求,一定是第一页,页面大小是固定的:
17     int pageSize = 5;//可以把这个写到配置中,方便否其修改;
18     int currentPageNo = 1;
19 
20     if(queryUserName == null){
21         queryUserName = "";
22     }
23     if (temp!=null&&!temp.equals("")){
24         queryUserRole = Integer.parseInt(temp);//给查询赋值!0,1,2,3
25     }
26     if (pageIndex!=null){
27         currentPageNo = Integer.parseInt(pageIndex);
28     }
29 
30     //获取用户的总数(分页:上一页,下一页的情况)
31     int totalCount = userService.getUserCount(queryUserName, queryUserRole);
32     //总页数支持
33     PageSupport pageSupport = new PageSupport();
34     pageSupport.setCurrentPageNo(currentPageNo);
35     pageSupport.setPageSize(pageSize);
36     pageSupport.setTotalCount(totalCount);
37 
38     int totalPageCount = ((int)(totalCount/pageSize))+1;//总的页数
39 
40     //控制首页和页面
41     //如果页面要小于1,就显示第一页的东西
42     if(currentPageNo<1){
43         currentPageNo = 1;
44     }else if(currentPageNo>totalPageCount){//当前页面大于最后一页
45         currentPageNo = totalPageCount;
46     }
47 
48     //获取用户列表展示
49     userList = userService.getUserList(queryUserName,queryUserRole,currentPageNo,pageSize);
50     req.setAttribute("userList",userList);
51 
52     RoleServiceImpl roleService = new RoleServiceImpl();
53     List<Role> roleList = roleService.getRoleList();
54     req.setAttribute("roleList",roleList);
55     req.setAttribute("totalCount",totalCount);
56     req.setAttribute("currentPageNo",currentPageNo);
57     req.setAttribute("totalPageCount",totalPageCount);
58     req.setAttribute("queryUserName",queryUserName);
59     req.setAttribute("queryUserRole",queryUserRole);
60 
61     //返回前端
62     try {
63         req.getRequestDispatcher("userlist.jsp").forward(req,resp);
64     } catch (ServletException e) {
65         e.printStackTrace();
66     } catch (IOException e) {
67         e.printStackTrace();
68     }
69 }

 

posted @ 2022-04-08 16:14  冰山醉酒  阅读(99)  评论(0)    收藏  举报