smbms項目(一)

項目搭建準備工作

1. 搭建一個maven web項目

2. 配置tomcat

3. 測試項目是否可以運行

4. 導入項目中需要的jar包

  <dependencies>
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>javax.servlet.jsp-api</artifactId>
      <version>2.3.3</version>
    </dependency>
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.47</version>
    </dependency>
    <!--JSTL表達式依賴-->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <!--Standard標簽庫-->
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

  </dependencies>

5. 創(chuàng)建項目包結構

6. 編寫實體類

  • ORM映射:表——類映射

7. 編寫基礎公共類

  • 數據庫配置文件
    此文件注意不要亂加;
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/?useUnicode=true&characterEncoding=UTF-8&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
username=root
password=11232020
  • 數據庫公共類
//操作數據的公共類
public class BaseDao {

    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    //靜態(tài)代碼塊,類加載就初始化
    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 connetion = null;
        try {
            Class.forName(driver);
            connetion = DriverManager.getConnection(url,username,password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connetion;
    }

    //編寫查詢公共類
    public static ResultSet execute(Connection connection,String sql,Object[] params,ResultSet resultSet,PreparedStatement preparedStatement) throws SQLException {
        //預編譯的sql后面直接執(zhí)行就行
        preparedStatement = connection.prepareStatement(sql);

        for (int i = 0; i < params.length; i++) {
            //setObject冷溶,占位符從一開始,但我們的數組是從0開始借杰!
            preparedStatement.setObject(i+1,params[i]);
        }
        resultSet = preparedStatement.executeQuery();
        return resultSet;
    }

    //編寫增刪改查公共方法
    public static int execute(Connection connection,String sql,Object[] params,PreparedStatement preparedStatement) throws SQLException {
        preparedStatement = connection.prepareStatement(sql);
        for (int i = 0; i < params.length; i++) {
            //setObject,占位符從一開始进泼,但我們的數組是從0開始蔗衡!
            preparedStatement.setObject(i+1,params[i]);
        }
        int updateRows = preparedStatement.executeUpdate();
        return updateRows;
    }

    //釋放資源
    public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet) {
        boolean flag = true;
        if (resultSet != null) {
            try {
                resultSet.close();
                //GC回收
                resultSet = null;
            } catch (SQLException e) {
                e.printStackTrace();
                //回收失敗
                flag = false;
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
                //GC回收
                preparedStatement = null;
            } catch (SQLException e) {
                e.printStackTrace();
                //回收失敗
                flag = false;
            }
        }
        if (connection != null) {
            try {
                connection.close();
                //GC回收
                connection = null;
            } catch (SQLException e) {
                e.printStackTrace();
                //回收失敗
                flag = false;
            }
        }
        return flag;
    }
}
  • 編寫字符編碼過濾器
public class CharacterEncodingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");

        chain.doFilter(request,response);
    }

    public void destroy() {

    }
}
    <!--    字符編碼過濾器-->
    <filter>
        <filter-name>CharacterEncodingFilter</filter-name>
        <filter-class>com.vigil.filter.CharacterEncodingFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>CharacterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

8. 導入靜態(tài)資源

登錄功能實現

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 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.getTimestamp("creationDate"));
                user.setModifyBy(resultSet.getInt("modifyBy"));
                user.setModifyDate(resultSet.getTimestamp("modifyDate"));
            }
            BaseDao.closeResource(null,preparedStatement,resultSet);
        }

        return user;
    }
}

5.業(yè)務層接口

public interface UserService {
    public User login(String userCode, String password);
}

6. 實現業(yè)務層接口

public class UserServiceImpl implements UserService {

    //業(yè)務層都會調用dao層,所以要引入dao層
    private UserDao userDao = null;
    public UserServiceImpl() {
        userDao = new UserDaoImpl();
    }

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

        try {
            connection = BaseDao.getConnection();
            //通過業(yè)務層乳绕,調用對應的具體的數據庫操作
            user = userDao.getLoginUser(connection,userCode);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            BaseDao.closeResource(connection,null,null);
        }
        return user;
    }
}

7. 編寫Servlet

public class LoginServlet extends HttpServlet {

    //控制層绞惦,調用業(yè)務層代碼
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("LoginServlet run----start");
        //獲得用戶登錄名和密碼
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");

        //和數據庫中的密碼進行對比
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.login(userCode, userPassword);//通過查詢得到登錄的人全部在數據庫的信息對應的保存在一個JavaBean類中

        if(user != null && user.getUserPassword() != null && user.getUserPassword().equals(userPassword)) {//查有此人并且密碼正確
            //將用戶的信息存放到Session中
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            //跳轉到主頁
            resp.sendRedirect("jsp/frame.jsp");
        } else {//查無此人
            //轉發(fā)回登錄頁面,順帶提示洋措,用戶名或者密碼錯誤
            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>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>com.vigil.servlet.user.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/dologin.html</url-pattern>
    </servlet-mapping>

9. 測試功能是否全部實現

登錄功能優(yōu)化

注銷功能

  • 思路:移除Session济蝉,返回登錄頁面

1. servlet

public class LogoutServlet extends HttpServlet {
    @Override
    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");//返回登錄頁面
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}

2. 配置xml

    <servlet>
        <servlet-name>LogoutServlet</servlet-name>
        <servlet-class>com.vigil.servlet.user.LogoutServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>LogoutServlet</servlet-name>
        <url-pattern>/user/logout.html</url-pattern>
    </servlet-mapping>

登錄攔截優(yōu)化

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

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;

        //過濾器,從Session獲取用戶
        User user = (User) req.getSession().getAttribute(Constants.USER_SESSION);
        if(user == null) {
            resp.sendRedirect("/smbms/error.jsp");
        } else {
            chain.doFilter(request,response);
        }

    }

    public void destroy() {

    }
}
    <!--    用戶登錄過濾器-->
    <filter>
        <filter-name>SysFilter</filter-name>
        <filter-class>com.vigil.filter.SysFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>SysFilter</filter-name>
        <url-pattern>/jsp/*</url-pattern>
    </filter-mapping>

密碼修改

1. 導入前端素材

2. 寫項目菠发,從底層往上寫

  • 從dao層開始寫起王滤,再寫業(yè)務層service,再寫控制層servlet滓鸠,再和視圖層jsp作聯(lián)系雁乡。要思考好一個事務和數據庫的邏輯關系,分別實現不同層次的代碼糜俗。

3. UserDao接口

public interface UserDao {
    //得到要登錄的用戶
    public User getLoginUser(Connection connection, String userCode) throws SQLException;

    //修改當前用戶密碼
    public int updatePwd(Connection connection,int id,String password) throws SQLException;
}

4. UserDao接口實現類

    //修改當前用戶密碼
    public int updatePwd(Connection connection, int id, String 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,pstm,sql,params);
            BaseDao.closeResource(null,pstm,null);
        }
        return execute;

5. UserService接口

public interface UserService {
    //得到要登錄的用戶
    public User login(String userCode, String password);

    //根據用戶ID更改密碼
    public boolean updatePwd(int id,String pwd);

}

6. UserService實現

    //根據用戶ID更改密碼
    public boolean updatePwd(int id, String pwd) {
        Connection connection = null;
        boolean flag = false;
        try {
            connection = BaseDao.getConnection();
            if(userDao.updatePwd(connection,id,pwd) > 0) {
                flag = true;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        finally {
            BaseDao.closeResource(connection,null,null);
        }
        return flag;
    }

7. 編寫Servlet

//實現Servlet的復用
public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if("savepwd".equals(method)) {//修改用戶密碼
            this.savepwd(req,resp);
        } else if("pwdmodify".equals(method)) {
            this.pwdmodify(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    //修改用戶密碼(包含了舊密碼驗證踱稍,刪去也行)
    public void savepwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //從Session里面拿id,得到用戶的實體類對象User
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String newpassword = req.getParameter("newpassword");
        String oldpassword = req.getParameter("oldpassword");
        boolean flag = false;
        //用戶Session中有這個用戶吩跋,并且新舊密碼不空寞射,不為0長度
        if(o != null && (newpassword != null && newpassword.length() > 0) && (oldpassword != null && oldpassword.length() > 0)) {
            User user = (User)o;
            if((user.getUserPassword().equals(oldpassword))) {//舊密碼是是一致的
                UserService userService = new UserServiceImpl();
                flag = userService.updatePwd(user.getId(),newpassword);
                if (flag) {
                    req.setAttribute("message", "修改密碼成功,請退出锌钮,使用新密碼登錄");
                    //密碼修改成功引矩,移除當前Session
                    req.getSession().removeAttribute(Constants.USER_SESSION);
                } else {
                    req.setAttribute("message", "修改密碼失敗");
                }
            } else {
                req.setAttribute("message", "修改密碼失敗");
            }
        } else {
            req.setAttribute("message", "修改密碼失敗");
        }
        req.getRequestDispatcher("/jsp/pwdmodify.jsp").forward(req,resp);
    }

    //驗證舊密碼梁丘,利用session中的用戶User實例對象(登錄就會有)
    public void pwdmodify(HttpServletRequest req, HttpServletResponse resp) {
        //從Session里面拿id值漫,得到用戶的實體類對象User
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        Map<String, String> resultMap = new HashMap<String, String>();

        if(o == null) {//session過期了
            resultMap.put("result","sessionerror");
        } else if(oldpassword == null) {//舊密碼輸入為空
            resultMap.put("result","error");
        } else if(!((User)o).getUserPassword().equals(oldpassword)) {//舊密碼輸入不正確
            resultMap.put("result","false");
        } else {//舊密碼輸入正確
            resultMap.put("result","true");
        }

        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            /*
            JSONArray,工具類酱塔,轉換格式蕊玷,將map轉換為json
             */
            writer.write(JSONArray.toJSONString(resultMap));
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
  • json工具包導入
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.75</version>
    </dependency>

8. 配置xml

    <servlet>
        <servlet-name>UserServlet</servlet-name>
        <servlet-class>com.vigil.servlet.user.UserServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>UserServlet</servlet-name>
        <url-pattern>/user/pwd.html</url-pattern>
    </servlet-mapping>

     <!--session默認過期時間剪勿,真實業(yè)務處理-->
    <session-config>
        <session-timeout>30</session-timeout>
    </session-config>

用戶管理實現

  • 思路:
  • 導入分頁的工具類

  • 用戶列表頁面導入

  • 獲取用戶數量

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 pstm = null;
        ResultSet rs = null;
        int count = 0;
        //sql語句通過StringBuffer追加
        if(connection != null) {
            StringBuffer sql = new StringBuffer();
            ArrayList<Object> list = new ArrayList<Object>();
            sql.append("select count(1) as count from smbms_user u,smbms_role r where u.userRole = r.id");

            if(username != null) {//追加username的查詢判斷
                sql.append(" and u.userName like ?");
                list.add("%" + username + "%");//index : 0
            }
            if(userRole > 0) {//追加userRole的查詢判斷
                sql.append(" and u.userRole = ?");
                list.add(userRole);//index : 1
            }

            //list轉化為數組
            Object[] params = list.toArray();

            System.out.println("UserDaoImpl.getUserCount.SQL:" + sql);//輸出sql查詢語句
            System.out.println(list.toString());

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

            if(rs.next()) {//從結果集中獲取最終的數量
                count = rs.getInt("count");
            }
        }
        //關閉資源
        BaseDao.closeResource(null,pstm,rs);

        return count;
    }

3. Service

    //根據用戶名或者角色查詢用戶總數
    public int getUserCount(String username,int userRole);

4. ServiceImpl

    //根據用戶名或者角色查詢用戶總數
    public int getUserCount(String username, int userRole) {

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

    @Test
    public void test() {//測試
        UserServiceImpl userService = new UserServiceImpl();
        int count = userService.getUserCount("李四",1);
        System.out.println(count);
    }
  • 獲得用戶列表

1. UserDao

    //通過條件查詢獲得用戶列表
    public List<User> getUserList(Connection connection,String userName,int userRole,int currentPageNo,int pageSize) throws SQLException;

2. UserDaoImpl

//通過條件查詢獲得用戶列表
    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(userName != null && userName.length() > 0) {
                sql.append(" and u.userName like ?");
                list.add("%" + userName + "%");
            }
            if(userRole > 0) {
                sql.append(" and u.userRole = ?");
                list.add(userRole);
            }

            //在數據庫中定踱,分頁使用    limit(傳的兩個數值分別是開始位和總數)   startIndex畅哑,pageSize 呵恢;總數
            //startIndex  = (當前頁-1)*頁面大小--->對應前端頁面的第幾頁
            //0,5            1 - 1 = 0 * 01234
            //5挥唠,5            2 - 1 = 1 * 5唤锉,56789
            //10,5           3 - 1 = 2 * 10 10听系,11,12脑豹,13,14
            sql.append(" order by creationDate DESC limit ?,?");
            currentPageNo = (currentPageNo - 1) * pageSize;
            list.add(currentPageNo);
            list.add(pageSize);

            Object[] params = list.toArray();
            System.out.println("UserDaoImpl.getUserList--->sql" + sql.toString());
            System.out.println("sql--->?" + list.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. Service

    //根據條件查詢用戶列表
    public List<User> getUserList(String queryUserName, int queryUserRole,int currentPageNo, int pagaSize);

4. ServiceImpl

    //根據條件查詢用戶列表
    public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pagaSize) {
        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("pagaSize-->" + pagaSize);

        try {
            connection = BaseDao.getConnection();
            userList = userDao.getUserList(connection,queryUserName,queryUserRole,currentPageNo,pagaSize);
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            BaseDao.closeResource(connection,null,null);
        }

        return userList;
    }

    @Test
    public void test() {//測試
        UserServiceImpl userService = new UserServiceImpl();
        List<User> userList = userService.getUserList(null,3,1,5);
        System.out.println(userList.size());
        for (User user : userList) {
            System.out.println(user.getUserName()+user.getId());
        }
    }

  • 獲得角色列表

為了職責分明清晰衡查,可以把角色的操作單獨放到一個包中瘩欺,和pojo一一對應

1. RoleDao

public interface RoleDao {
    //獲得角色列表
    public List<com.vigil.pojo.Role> getRoleList(Connection connection) throws SQLException;

}

2. RoleDaoImpl

public class RoleDaoImpl implements RoleDao {

    //獲得角色列表
    public List<com.vigil.pojo.Role> getRoleList(Connection connection) throws SQLException {

        PreparedStatement pstm = null;
        ResultSet rs = null;
        ArrayList<com.vigil.pojo.Role> roleList = new ArrayList<com.vigil.pojo.Role>();

        if(connection != null) {
            String sql = "select * from smbms_role";
            Object[] params = {};
            rs = BaseDao.execute(connection, pstm, rs, sql, params);
            while(rs.next()) {
                com.vigil.pojo.Role _role = new Role();
                _role.setId(rs.getInt("id"));
                _role.setRoleName(rs.getString("roleName"));
                _role.setRoleCode(rs.getString("roleCode"));
                roleList.add(_role);
            }
            BaseDao.closeResource(null,pstm,rs);
        }

        return roleList;
    }

}

3. RoleService

public interface RoleService {
    //獲得角色列表
    public List<Role> getRoleList();

}

4. RoleServiceImpl

public class RoleServiceImpl implements RoleService {
    //引入Dao
    private RoleDao roleDao = null;
    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.closeResource(connection,null,null);
        }
        return roleList;

    }

    @Test
    public void test() {
        RoleServiceImpl roleService = new RoleServiceImpl();
        List<Role> roleList = roleService.getRoleList();
        System.out.println(roleList.size());
        for(Role role : roleList) {
            System.out.println(role.getId()+role.getRoleName()+role.getRoleCode());
        }
    }
}

5. Servlet

1. 查詢獲得用戶列表
2. 從前端獲取數據
3. 獲得用戶的總數(分頁:上一頁、下一頁的情況)
4. 控制首頁和尾頁,如果頁面要小于1俱饿,就顯示第一頁的東西
5. 獲取用戶列表展示
6. 返回前端
//
    public void query(HttpServletRequest req, HttpServletResponse resp) {
        //查詢獲得用戶列表
        UserServiceImpl userService = new UserServiceImpl();
        List<User> userList = null;

        //第一次請求歌粥,是可以固定頁面大寫和頁數的,還有下拉欄默認值,建議把這些數值寫到配置文件拍埠,方便后期修改
        int pageSize = 5;
        int currentPageNo = 1;
        int queryUserRole = 0;

        //從前端獲取數據
        String queryUserName = req.getParameter("queryUserName");
        String tempUR = req.getParameter("queryUserRole");
        String pageIndex = req.getParameter("pageIndex");
        System.out.println("queryUserName:" + queryUserName + " tempUR: " + tempUR + " pageIndex: " + pageIndex);
        if (queryUserName == null) {
            queryUserName = "";
        }
        if(tempUR != null && !tempUR.equals("")) {//賦值0失驶,1,2
            queryUserRole = Integer.parseInt(tempUR);
        }
        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 = pageSupport.getTotalPageCount();//總頁數
        //控制首頁和尾頁
        //如果頁面要小于1嬉探,就顯示第一頁的東西
        if(currentPageNo < 1) {
            currentPageNo = 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);

        //返回前端
        try {
            req.getRequestDispatcher("/jsp/userlist.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市棉圈,隨后出現的幾起案子涩堤,更是在濱河造成了極大的恐慌,老刑警劉巖分瘾,帶你破解...
    沈念sama閱讀 217,734評論 6 505
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件胎围,死亡現場離奇詭異,居然都是意外死亡德召,警方通過查閱死者的電腦和手機白魂,發(fā)現死者居然都...
    沈念sama閱讀 92,931評論 3 394
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來上岗,“玉大人福荸,你說我怎么就攤上這事∫壕ィ” “怎么了逞姿?”我有些...
    開封第一講書人閱讀 164,133評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長捆等。 經常有香客問我滞造,道長,這世上最難降的妖魔是什么栋烤? 我笑而不...
    開封第一講書人閱讀 58,532評論 1 293
  • 正文 為了忘掉前任谒养,我火速辦了婚禮,結果婚禮上明郭,老公的妹妹穿的比我還像新娘买窟。我一直安慰自己,他們只是感情好薯定,可當我...
    茶點故事閱讀 67,585評論 6 392
  • 文/花漫 我一把揭開白布始绍。 她就那樣靜靜地躺著,像睡著了一般话侄。 火紅的嫁衣襯著肌膚如雪亏推。 梳的紋絲不亂的頭發(fā)上学赛,一...
    開封第一講書人閱讀 51,462評論 1 302
  • 那天,我揣著相機與錄音吞杭,去河邊找鬼盏浇。 笑死,一個胖子當著我的面吹牛芽狗,可吹牛的內容都是我干的绢掰。 我是一名探鬼主播,決...
    沈念sama閱讀 40,262評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼童擎,長吁一口氣:“原來是場噩夢啊……” “哼滴劲!你這毒婦竟也來了?” 一聲冷哼從身側響起柔昼,我...
    開封第一講書人閱讀 39,153評論 0 276
  • 序言:老撾萬榮一對情侶失蹤哑芹,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后捕透,有當地人在樹林里發(fā)現了一具尸體聪姿,經...
    沈念sama閱讀 45,587評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 37,792評論 3 336
  • 正文 我和宋清朗相戀三年乙嘀,在試婚紗的時候發(fā)現自己被綠了末购。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片咏雌。...
    茶點故事閱讀 39,919評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡戳鹅,死狀恐怖,靈堂內的尸體忽然破棺而出脏嚷,到底是詐尸還是另有隱情婴噩,我是刑警寧澤擎场,帶...
    沈念sama閱讀 35,635評論 5 345
  • 正文 年R本政府宣布,位于F島的核電站几莽,受9級特大地震影響迅办,放射性物質發(fā)生泄漏。R本人自食惡果不足惜章蚣,卻給世界環(huán)境...
    茶點故事閱讀 41,237評論 3 329
  • 文/蒙蒙 一站欺、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧纤垂,春花似錦矾策、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,855評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至吼鱼,卻和暖如春榄鉴,著一層夾襖步出監(jiān)牢的瞬間履磨,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,983評論 1 269
  • 我被黑心中介騙來泰國打工庆尘, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人巷送。 一個月前我還...
    沈念sama閱讀 48,048評論 3 370
  • 正文 我出身青樓驶忌,卻偏偏與公主長得像,于是被迫代替她去往敵國和親笑跛。 傳聞我的和親對象是個殘疾皇子付魔,可洞房花燭夜當晚...
    茶點故事閱讀 44,864評論 2 354

推薦閱讀更多精彩內容