smbms

SMBMS

系统功能结构图

img

数据库结构要素

img

项目如何搭建

考虑使用不使用maven?

项目搭建准备工作

1.搭建一个maven web项目

配置好web文件和pom文件

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
                      http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1"
         metadata-complete="true">
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
​
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
​
  <groupId>com.cofe</groupId>
  <artifactId>smbms</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

2.配置Tomcat

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

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

jsp,servlet,mysql驱动,jstl,standard

5.创建项目包结构

6.编写实体类

ORM映射:表---》类映射

7.编写基础公共类

1.数据库配置文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306?useUnicode=true&characterEncoding=utf-8
username=root
password=123456

2.编写数据库的公共类

package com.cofe.dao;
​
​
​
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
​
//数据库的公共类
public class BaseClass {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;
//    静态代码块,类加载的时候就开始初始化
    static {
    Properties properties = new Properties();
//    通过类加载器读取对应的资源
    ClassLoader loader = BaseClass.class.getClassLoader();
        InputStream is = loader.getResourceAsStream("db.properties");
​
    try {
        properties.load(is);
    } catch (IOException e) {
        e.printStackTrace();
    }
    driver = properties.getProperty("driver");
    url = properties.getProperty("url");
    username = properties.getProperty("username");
    password = properties.getProperty("password");
}
//获取数据库的连接
    public static Connection getConnection(){
        Connection connection = null;
        try {
            Class.forName(driver);
             connection = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return connection;
    }
//    编写查询公共方法
    public static ResultSet execute(Connection connection,String sql,Object[] params,PreparedStatement preparedStatement,ResultSet resultSet) throws SQLException {
//        预编译的sql,在后面直接执行就可以了
            preparedStatement = connection.prepareStatement(sql);
            for (int i = 0;i < params.length;i++){
//               setObject是 从站位符1开始查询,而数组下标是从0开始
                preparedStatement.setObject(i+1,params[i]);
            }
            resultSet = preparedStatement.executeQuery();
​
        return resultSet;
    }
//    编写增删改公共方法
    public static int execute(Connection connection,String sql,PreparedStatement preparedStatement,Object[] params) throws SQLException {
        preparedStatement = connection.prepareStatement(sql);
        for (int i = 0;i < params.length;i++){
            // setObject是 从站位符1开始查询,而数组下标是从0开始
            preparedStatement.setObject(i+1,params[i]);
        }
        int i = preparedStatement.executeUpdate();
        return i;
    }
//    释放资源
    public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){
        boolean flag = false;
        if (resultSet != null){
            try {
                resultSet.close();
//                如果清理不干净,使用GC(垃圾回收器)进行清理
                resultSet = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if (connection != null){
            try {
                connection.close();
//                如果清理不干净,使用垃圾回收器进行清理
                connection = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if (preparedStatement != null){
            try {
                preparedStatement.close();
//                如果清理不干净,使用垃圾回收器进行清理
                resultSet = null;
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        return false;
    }
}

3.编写字符编码过滤器

package com.cofe.filter;
​
import javax.servlet.*;
import java.io.IOException;
​
//字符编码过滤器
public class CharacterEncodingFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {
​
    }
​
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");
        filterChain.doFilter(servletRequest,servletResponse);
    }
​
    public void destroy() {
​
    }
}

8.导入静态资源

登录功能实现

1.编写前端登录页面login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>系统登录 - 超市订单管理系统</title>
    <link type="text/css" rel="stylesheet" href="${pageContext.request.contextPath }/css/style.css" />
    <script type="text/javascript">
    </script>
</head>
<body class="login_bg">
<section class="loginBox">
    <header class="loginHeader">
        <h1>超市订单管理系统</h1>
    </header>
    <section class="loginCont">
        <form class="loginForm" action="${pageContext.request.contextPath }/login.do"  name="actionForm" id="actionForm"  method="post" >
            <div class="info">${error}</div>
            <div class="inputbox">
                <label>用户名:</label>
                <input type="text" class="input-text" id="userCode" name="userCode" placeholder="请输入用户名" required/>
            </div>
            <div class="inputbox">
                <label>密码:</label>
                <input type="password" id="userPassword" name="userPassword" placeholder="请输入密码" required/>
            </div>
            <div class="subBtn">
​
                <input type="submit" value="登录"/>
                <input type="reset" value="重置"/>
            </div>
        </form>
    </section>
</section>
</body>
</html>

2.在web.xml文件中设置欢迎页面 (作用:打开Tomcat直接进入指定的jsp文件)

<!--  设置欢迎界面  -->
    <welcome-file-list>
        <welcome-file>login.jsp</welcome-file>
    </welcome-file-list>

3.编写dao层得到用户登录的接口

public interface UserDao {
    public User getLoginUser(Connection connection,String userCode,String userPassword) throws SQLException;
}

4.编写dao接口的实现类

package com.cofe.dao.user;

import com.cofe.dao.BaseClass;
import com.cofe.pojo.User;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserImpl implements UserDao {
    //    得到要登录的用户,根据userCode获取用户的所有信息
    public User getLoginUser(Connection connection, String userCode, String userPassword) throws SQLException {
        PreparedStatement pstm = null;
        ResultSet rs = null;
        User user = null;
        if (connection != null) {
            String sql = "select * from smbms.smbms_user where userCode=?";
            Object[] params = {userCode};
            rs = BaseClass.execute(connection, sql, pstm, params, rs);
            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.setModifyBy(rs.getInt("modifyBy"));
                user.setModifyDate(rs.getDate("modifyDate"));
            }
            BaseClass.closeResource(null, pstm, rs);
            if (!user.getUserPassword().equals(userPassword)) {
                user = null;
            }

        }
        return user;
    }
}

5.业务层接口

package com.cofe.service.user;

import com.cofe.pojo.User;

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

6.业务层实现类

package com.cofe.service.user;

import com.cofe.dao.BaseClass;
import com.cofe.dao.user.UserDao;
import com.cofe.dao.user.UserImpl;
import com.cofe.pojo.User;
import org.junit.Test;


import java.sql.Connection;
import java.sql.SQLException;

public class UserServiceImpl implements UserService {
//    业务层都会调用dao层,所以我们要引入dao层
    private UserDao userDao;
//    调用无参构造器
    public UserServiceImpl(){

        userDao = new UserImpl();
    }

    public  User login(String userCode, String userPassword){
        Connection connection = null;
        User user = null;
        try {
            connection = BaseClass.getConnection();
            user = userDao.getLoginUser(connection, userCode, userPassword);
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            BaseClass.closeResource(connection,null,null);
        }
        return user;
    }
    @Test
    public void test() throws SQLException {
        UserServiceImpl userService = new UserServiceImpl();
        User user = userService.login("admin", "1234567");
        System.out.println(user.getUserPassword());

    }
}

7.编写servlet

package com.cofe.servlet.user;

import com.cofe.pojo.User;
import com.cofe.service.user.UserService;
import com.cofe.service.user.UserServiceImpl;
import com.cofe.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

public class LoginServlet extends HttpServlet {
//    servlet:控制层,调用业务层
    @Override
    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");
//        和数据库中的密码进行对比,调用业务层
        UserService userService = new UserServiceImpl();
        User user = null;
        try {
            user = userService.login(userCode, userPassword);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        System.out.println(userCode);
            System.out.println(userPassword);
            if (user != null){//查有此人,可以登录
//                 将用户信息存到session中
                req.getSession().setAttribute(Constants.USER_SESSION,user);
//                跳转到内部主页
                resp.sendRedirect("jsp/frame.jsp");
            }else {//查无此人,无法登录,转发回登录页面,顺带提示他,用户名或密码错误
                req.setAttribute("error","用户名或密码错误");
                req.getRequestDispatcher("login.jsp").forward(req,resp);
            }


    }

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

8.注册servlet

<servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>com.cofe.servlet.user.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/login.do</url-pattern>
</servlet-mapping>

9.测试访问,确保以上功能成功

登录功能优化

注销功能

package com.cofe.servlet.user;

import com.cofe.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class LogoutServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        移除session中的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);
    }
}

注册xml

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

登录拦截优化

编写一个过滤器

package com.cofe.filter;

import com.cofe.pojo.User;
import com.cofe.util.Constants;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

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

    }

    @Override
    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(request.getContextPath()+"/error.jsp");
        }else {
            filterChain.doFilter(servletRequest,servletResponse);
        }
    }

    @Override
    public void destroy() {

    }
}

注册xml

<filter>
    <filter-name>SysFilter</filter-name>
    <filter-class>com.cofe.filter.SysFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>SysFilter</filter-name>
    <url-pattern>/jsp/*</url-pattern>
</filter-mapping>

测试,登录,注销,权限都要成功

密码修改

1.dao层接口

//    修改用户密码
    public int updatePassword(Connection connection,int id,String password) throws SQLException;

2.dao层实现类

//修改当前用户密码,修改当前用户会影响数据库几行,所以返回的类型为int
    @Override
    public int updatePassword(Connection connection, int id, String userPassword) throws SQLException {
        PreparedStatement preparedStatement = null;
        int updateRow = 0;
        boolean flag = false;
        if (connection != null) {
            String sql = "update smbms.smbms_user set userPassword = ? where id = ?";
            Object[] params = {userPassword, id};
             updateRow= BaseClass.execute(connection, sql, preparedStatement, params);
        }
        BaseClass.closeResource(null,preparedStatement,null);
        return updateRow;
    }

3.编写业务接口

//    根据用户id去修改密码
//    通过返回的参数flag判断是否修改成功
    public boolean updatePws(int id,String userPassword);

4.业务实现类

public boolean updatePws(int id, String userPassword) {
    Connection connection = null;
    boolean flag = false;

    try {
        connection = BaseClass.getConnection();
        int i = userDao.updatePassword(connection, id, userPassword);
        if (i > 0)
            flag = true;
    } catch (SQLException e) {
        e.printStackTrace();
    }finally {
        BaseClass.closeResource(connection,null,null);
    }
    return flag;
}

5.在servlet.user包下建立UserServlet

package com.cofe.servlet.user;

import com.cofe.pojo.User;
import com.cofe.service.user.UserService;
import com.cofe.service.user.UserServiceImpl;
import com.cofe.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class UserServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//     实现servlet复用,实现servlet复用需要提取出方法,然后在doGet函数中调用
        String method = req.getParameter("method");
        if (method.equals("savepws") && method != null)
            this.updatePsw(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
    protected void updatePsw(HttpServletRequest req, HttpServletResponse resp){
        String newPassword = req.getParameter("newPassword");
//        从session中获得id,这里的o是用户的所有信息
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        boolean flag = false;
//        判断是否有这个用户存在,以及新密码是否为空
        if (o != null && newPassword != null) {
            UserService userService = new UserServiceImpl();
            flag = userService.updatePws(((User) o).getId(), newPassword);
            if (flag){
//                发送信息
                req.setAttribute(Constants.SYS_MESSAGE,"密码修改成功,请退出后重新登录");
//                密码修改成功后,移除当前session
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else
                req.setAttribute(Constants.SYS_MESSAGE,"密码修改失败,请重新输入");

        }else {
            req.setAttribute(Constants.SYS_MESSAGE,"新密码设置错误,请重新输入");
        }
        try {
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

6.注册xml

<servlet>
    <servlet-name>UserServlet</servlet-name>
    <servlet-class>com.cofe.servlet.user.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>UserServlet</servlet-name>
    <url-pattern>/jsp/user.do</url-pattern>
</servlet-mapping>

7.测试

优化密码修改使用Ajax

1.阿里巴巴的fastjson

<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.78</version>
</dependency>

2.设置默认的session有效时间

<session-config>
    <session-timeout>30</session-timeout>
</session-config>
//    验证旧密码,session中有用户的密码
public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
//        从session里面拿到ID
    Object o = req.getSession().getAttribute(Constants.USER_SESSION);
    String oldpassword = req.getParameter("oldpassword");
//    万能的Map
    HashMap<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");
        PrintWriter writer = resp.getWriter();
//        JSONArray 阿里巴巴的工具类 转换格式
        writer.write(JSONArray.toJSONString(resultMap));
        writer.flush();
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

3.测试

用户管理实现

1.导入分页的工具类

pageSupport.java

2.用户列表页面导入

userlist.jsp和rollpage.jsp

1.获取用户数量

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;
        ArrayList<Object> list = new ArrayList<Object>();
        if (connection != null){
            StringBuffer sql = new StringBuffer();
            sql.append("select count(1) as count from smbms.smbms_user u,smbms.smbms_role r where u.userRole = r.id");
            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());//输出最后完整的sql语句
            rs = BaseClass.execute(connection, sql.toString(), pstm, params, rs);
            if (rs.next()){
                count = rs.getInt("count");
            }
            BaseClass.closeResource(null,pstm,rs);
        }
        return count;
    }

3.UserService

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

4.UserServiceImpl

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

2.获取用户了列表

1.UserDao

//    获取用户列表
    public List<User> getUserList(Connection connection,String queryUserName,int queryUserRole,int currentPageNo,int pageSize) throws Exception;

2.UserDaoImpl

public List<User> getUserList(Connection connection, String queryUserName, int queryUserRole, int currentPageNo, int pageSize) throws Exception {
    PreparedStatement pstm = null;
    ResultSet rs = null;
    List<User> userList = new ArrayList<User>();
    if (connection != null){
       List<Object> list = new ArrayList<Object>();
        StringBuffer sql = new StringBuffer();
        sql.append("select count(1) as count from smbms.smbms_user u,smbms.smbms_role r where u.userRole = r.id");
        if (!StringUtils.isNullOrEmpty(queryUserName)){
            sql.append(" and u.userName like ?");
            list.add("%"+queryUserName+"%");
        }
        if (queryUserRole > 0){
            sql.append(" and u.userRole = ?");
            list.add(queryUserRole);
        }
        //在数据库中,分页使用limit startIndex,pageSize;
        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 = BaseClass.execute(connection, sql.toString(), pstm, params, rs);
        if (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("roleName"));
            userList.add(user);
        }
        BaseClass.closeResource(null,pstm,rs);
    }
    return userList;
}

3.UserService

//    获取用户列表
    public List<User> getUserList(String queryUserName,int queryUserRole,int currentPageNo,int pageSize) throws Exception;

4.UserServiceImpl

public List<User> getUserList(String queryUserName, int queryUserRole, int currentPageNo, int pageSize) throws Exception {
    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);

    connection = BaseClass.getConnection();
    userList = userDao.getUserList(connection, queryUserName, queryUserRole, currentPageNo, pageSize);
    BaseClass.closeResource(connection,null,null);
    return userList;
}

3.获取用户角色列表

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

1.RoleDao

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

2.RoleDaoImpl

public List<Role> getRoleList(Connection connection) throws Exception {
    PreparedStatement pstm = null;
    ResultSet rs = null;
    List<Role> roleList = new ArrayList<Role>();
    if (connection != null){
        String sql = "select * from smbms_role";
        Object[] params = null;
        rs = BaseClass.execute(connection, sql.toString(), pstm, params, rs);
        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);
        }
        BaseClass.closeResource(null,pstm,rs);
    }
    return roleList;
}

3.RoleService

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

4.RoleServiceImpl

public List<Role> getRoleList() {
    Connection connection = null;
    List<Role> roleList= null;
    try {
        connection = BaseClass.getConnection();
        roleList = roleDao.getRoleList(connection);
    } catch (Exception e) {
        e.printStackTrace();
    }finally {
        BaseClass.closeResource(connection,null,null);
    }
    return roleList;
}

4.用户显示的servlet

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

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

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

4.用户列表展示

5.返回前端

    public void query(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException  {
//        接受前端传来的参数
        String queryUserName = req.getParameter("queryname");
        String temp = req.getParameter("queryUserRole");//从前端传回来的用户角色不知是否为空或者是有效码,所以先暂存起来
        String pageIndex = req.getParameter("pageIndex");
        int queryUserRole = 0;

//        通过UserServiceImpl得到用户列表,用户数
        UserServiceImpl userService = new UserServiceImpl();
//        通过RoleServiceImpl得到角色列表
        RoleService roleService = new RoleServiceImpl();
        List<User> userList = null;//用来存储用户列表
        List<Role> roleList = null;//用来存储角色列表
//        第一次走这个请求,一定是第一页,页面大小固定
        int pageSize = Constants.pageSize;//可以把这个写在配置文件中,方便后期修改
        int currentPageNo = 1;
        //输出控制台,显示参数的当前值
        System.out.println("queryUserName servlet--------"+queryUserName);
        System.out.println("queryUserRole servlet--------"+queryUserRole);
        System.out.println("query pageIndex--------- > " + pageIndex);
//     前端传来的参数若不符合查询sql语句
        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 = pageSupport.getTotalPageCount();

//        控制首页和尾页
//        如果页面小于1,就显示第一页的东西
        if (currentPageNo < 1){
            currentPageNo = 1;
        }else if (currentPageNo >totalPageCount){//当前页面大于最后一页
            currentPageNo = totalPageCount;
        }
//        获取用户列表展示
        userList = userService.getUserList(queryUserName, queryUserRole, currentPageNo, pageSize);
        roleList = roleService.getRoleList();

        req.setAttribute("userList",userList);
        req.setAttribute("roleList",roleList);
        req.setAttribute("totalCount",totalCount);
        req.setAttribute("currentPageNo",currentPageNo);
        req.setAttribute("totalPageCount",totalPageCount);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);

//        返回前段
        req.getRequestDispatcher("userlist.jsp").forward(req,resp);

    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值