• javaweb-SMBMS


    SMBMS超市订单管理系统

    javaweb基础学习总结,模拟简单的超市订单管理系统



    一、SMBMS架构、数据库表

    在这里插入图片描述

    数据库表
    在这里插入图片描述

    二、项目准备

    1、搭建一个maven web项目
    在这里插入图片描述
    2、配置tomcat
    3、测试启动项目
    4、导入项目中会遇到的jar包依赖
    5、创建项目包结构
    在这里插入图片描述

    6、编写实体类
    ORM映射:表——类映射
    7.编写基础公共类

    • 数据库配置文件(properties)

      driver=com.mysql.cj.jdbc.Driver
      url =jdbc:mysql://localhost:3306/jdbcstudy?useUnicode=true&charaterEncoding=ut8&useSSL=true
      username=root
      password=1234qwer
      
      • 1
      • 2
      • 3
      • 4
    • 编写数据库的公共类

      package com.jjl.dao;
      import java.io.IOException;
      import java.io.InputStream;
      import java.sql.*;
      import java.util.Properties;
      
      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) {
                  throw new RuntimeException(e);
              }
              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,ResultSet resultSet,PreparedStatement preparedStatement) throws SQLException {
              preparedStatement = connection.prepareStatement(sql);
              for (int i = 0; i < params.length; i++) {
                  //Object[] params 这个参数是从1开始的,而数组是从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++) {
                  //Object[] params 这个参数是从1开始的,而数组是从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;
          }
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
      • 14
      • 15
      • 16
      • 17
      • 18
      • 19
      • 20
      • 21
      • 22
      • 23
      • 24
      • 25
      • 26
      • 27
      • 28
      • 29
      • 30
      • 31
      • 32
      • 33
      • 34
      • 35
      • 36
      • 37
      • 38
      • 39
      • 40
      • 41
      • 42
      • 43
      • 44
      • 45
      • 46
      • 47
      • 48
      • 49
      • 50
      • 51
      • 52
      • 53
      • 54
      • 55
      • 56
      • 57
      • 58
      • 59
      • 60
      • 61
      • 62
      • 63
      • 64
      • 65
      • 66
      • 67
      • 68
      • 69
      • 70
      • 71
      • 72
      • 73
      • 74
      • 75
      • 76
      • 77
      • 78
      • 79
      • 80
      • 81
      • 82
      • 83
      • 84
      • 85
      • 86
      • 87
      • 88
      • 89
      • 90
      • 91
      • 92
      • 93
      • 94
      • 95
      • 96
      • 97
    • 编写字符编码过滤器

      package com.jjl.filter;
      import javax.servlet.*;
      import java.io.IOException;
      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");
              request.setCharacterEncoding("utf-8");
              chain.doFilter(request,response);
          }
          public void destroy() {}
      }
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 8
      • 9
      • 10
      • 11
      • 12
      • 13
          <filter>
              <filter-name>CharacterEncodingFilterfilter-name>
              <filter-class>com.jjl.filter.CharacterEncodingFilterfilter-class>
          filter>
          <filter-mapping>
              <filter-name>CharacterEncodingFilterfilter-name>
              <url-pattern>/*url-pattern>
          filter-mapping>
      
      • 1
      • 2
      • 3
      • 4
      • 5
      • 6
      • 7
      • 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">
    	/* if(top.location!=self.location){
    	      top.location=self.location;
    	 } */
        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 }/user/login.do"  name="actionForm" id="actionForm"  method="post" >
    				<div class="info">${error }div>
    				<div class="inputbox">
                        <label for="userCode">用户名:label>
    					<input type="text" class="input-text" id="userCode" name="userCode" placeholder="请输入用户名" required/>
    				div>	
    				<div class="inputbox">
                        <label for="userPassword">密码: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>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40

    2、设置欢迎页(web.xml)

    <welcome-file-list>
        <welcome-file>login.jspwelcome-file>
    welcome-file-list>
    
    • 1
    • 2
    • 3

    在这里插入图片描述

    3、编写dao层登录用户的接口

    package com.jjl.dao.user;
    
    import com.jjl.pojo.User;
    
    import java.sql.Connection;
    import java.sql.SQLException;
    
    public interface UserDao {
        //得到要登录的用户
        public User getLoginUser(Connection connection, String userCode) throws SQLException;
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    4、编写dao接口的实现类

    package com.jjl.dao.user;
    
    import com.jjl.dao.BaseDao;
    import com.jjl.pojo.User;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    public class UserDaoImpl implements UserDao{
        public User getLoginUser(Connection connection, String userCode) throws SQLException {
    
            PreparedStatement pstm = null;
            ResultSet rs= null;
            User user = null;
    
            //如果数据库连接成功,则就执行sql
            if(connection!=null) {
                String sql = "select * from smbms_user where userCode=?";
                Object[] params = {userCode};
    
                rs = BaseDao.execute(connection, sql, params, rs, pstm);
                if (rs.next()) {
                    user = new User();
                    user.setId(rs.getInt("id"));
                    user.setUserCode(rs.getString("userCode"));
                    user.setUserName(rs.getString("userName"));
                    user.setUserPassword(rs.getString("userPassword"));
                    user.setGender(rs.getInt("gender"));
                    user.setBirthday(rs.getDate("birthday"));
                    user.setPhone(rs.getString("phone"));
                    user.setAddress(rs.getString("address"));
                    user.setUserRole(rs.getInt("userRole"));
                    user.setCreatedBy(rs.getInt("createdBy"));
                    user.setCreationDate(rs.getTimestamp("creationDate"));
                    user.setModifyBy(rs.getInt("modifyBy"));
                    user.setModifyDate(rs.getTimestamp("modifyDate"));
                }
                BaseDao.closeResource(null,pstm,rs);
            }
            return user;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44

    5、业务层接口

    package com.jjl.service.user;
    
    import com.jjl.pojo.User;
    
    import java.sql.SQLException;
    
    public interface UserService {
        //用户登录
        public User login(String userCode, String password) throws SQLException;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    6、业务层实现类

    package com.jjl.service.user;
    
    import com.jjl.dao.BaseDao;
    import com.jjl.dao.user.UserDao;
    import com.jjl.dao.user.UserDaoImpl;
    import com.jjl.pojo.User;
    
    import java.sql.Connection;
    import java.sql.SQLException;
    
    public class UserServiceImpl implements UserService{
        //业务层都会调用dao层,所以要引入dao层
        private UserDao userDao;
        public UserServiceImpl(){
            userDao = new UserDaoImpl();
        }
        public User login(String userCode, String password) {
            Connection connection =null;
            User user = null;
            connection = BaseDao.getConnection();
            //通过业务层调用嘴硬的数据库操作
            try {
                user = userDao.getLoginUser(connection,userCode);
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                BaseDao.closeResource(connection,null,null);
            }
            return user;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    7、编写servlet

    设置存放用户session的常量

    package com.jjl.util;
    
    public class Constants {
        public final static String USER_SESSION = "userSession";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    编写servlet

    package com.jjl.servlet.user;
    import com.jjl.pojo.User;
    import com.jjl.service.user.UserServiceImpl;
    import com.jjl.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 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");
    
            //和数据库中的密码进行对比,调用业务层
            UserServiceImpl userService = new UserServiceImpl();
            User user = userService.login(userCode, 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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    8、注册servlet

    <servlet>
            <servlet-name>LoginServletservlet-name>
            <servlet-class>com.jjl.servlet.user.LoginServletservlet-class>
        servlet>
        <servlet-mapping>
            <servlet-name>LoginServletservlet-name>
            <url-pattern>/login.dourl-pattern>
        servlet-mapping>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    9、测试访问

    特别注意,遇到了如下报错:

    java.lang.ClassNotFoundException: com.mysql.cj.jdbc.Driver 	
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1364) 	
    at org.apache.catalina.loader.WebappClassLoaderBase.loadClass(WebappClassLoaderBase.java:1187)
    
    • 1
    • 2
    • 3

    是由于tomcat的lib中没有连接mysql的驱动(mysql-connector-java-8.0.28.jar),只需要将项目中的驱动复制到tomcat的lib中即可
    测试访问:
    在这里插入图片描述

    10、优化登录功能(注销、权限过滤)

    1、注销

    思路:

    • 移除session
    • 返回登录页面
    package com.jjl.servlet.user;
    import com.jjl.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 {
            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);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20

    注册:

    <servlet>
        <servlet-name>LogoutServletservlet-name>
        <servlet-class>com.jjl.servlet.user.LogoutServletservlet-class>
    servlet>
    <servlet-mapping>
        <servlet-name>LogoutServletservlet-name>
        <url-pattern>/user/logouturl-pattern>
    servlet-mapping>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    2、登录拦截(权限控制)

    四、修改密码

    1、导入前端页面

    2、思路

    在这里插入图片描述

    3、编写UserDao接口

    package com.jjl.dao.user;
    import com.jjl.pojo.User;
    import java.sql.Connection;
    import java.sql.SQLException;
    public interface UserDao {
        //得到要登录的用户
        public User getLoginUser(Connection connection, String userCode, String userPassword) throws SQLException;
    
        //新增接口:获取当前用户密码
        public int updatePwd (Connection connection, int id, String userPassword)throws SQLException;
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    4、UserDao类中新增修改密码的实现接口

    package com.jjl.dao.user;
    import com.jjl.dao.BaseDao;
    import com.jjl.pojo.User;
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    
    public class UserDaoImpl implements UserDao{
        //获取要登录的用户
        略:
        //修改当前用户密码
        public int updatePwd(Connection connection, int id, String userPassword) throws SQLException {
            PreparedStatement pstm = null;
            int execute = 0;
            if (connection!=null) {
                String sql = "update smbms_user set userPassword=? where id=?";
                Object params[] = {userPassword, id};
                execute = BaseDao.execute(connection, sql, params, pstm);
                BaseDao.closeResource(null, pstm, null);
            }
            return execute;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    5、编写service层接口(UserService)

    package com.jjl.service.user;
    import com.jjl.pojo.User;
    import java.sql.Connection;
    import java.sql.SQLException;
    
    public interface UserService {
        //用户登录
        public User login(String userCode, String userPassword) throws SQLException;
        
        //根据用户id,修改密码
        public boolean updatePwd (int id, String userPassword);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    6、UserServiceImpl实现类,传递参数返回业务处理结果

    package com.jjl.service.user;
    import com.jjl.dao.BaseDao;
    import com.jjl.dao.user.UserDao;
    import com.jjl.dao.user.UserDaoImpl;
    import com.jjl.pojo.User;
    import java.sql.Connection;
    import java.sql.SQLException;
    
    public class UserServiceImpl implements UserService{
        //用户登录//业务层实现类,修改密码
        public boolean updatePwd(int id, String userPassword) {
            Connection connection =null;
            boolean flag = false;
            connection = BaseDao.getConnection();
            try {
                if(userDao.updatePwd(connection,id,userPassword)>0){
                    flag=true;
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }finally {
                BaseDao.closeResource(connection,null,null);
            }
            return flag;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    7、编写servlet

    package com.jjl.servlet.user;
    import com.jjl.pojo.User;
    import com.jjl.service.user.UserService;
    import com.jjl.service.user.UserServiceImpl;
    import com.jjl.util.Constants;
    import com.mysql.cj.util.StringUtils;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    //实现servlet复用
    public class UserServlet extends HttpServlet {
        @Override
        protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //从session里面拿id;
            Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
            String newpassword = req.getParameter("newpassword");
            System.out.println("UserServlet" +newpassword );
            boolean flag = false;
            //!StringUtils.isNullOrEmpty(newpassword)
            if (attribute!= null && newpassword!=null){
                UserServiceImpl 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","新密码有误");
            }
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req, resp);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    注册web.xml

        <servlet>
            <servlet-name>UserServletservlet-name>
            <servlet-class>com.jjl.servlet.user.UserServletservlet-class>
        servlet>
        <servlet-mapping>
            <servlet-name>UserServletservlet-name>
            <url-pattern>/jsp/user.dourl-pattern>
        servlet-mapping>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8

    8、实现复用,提取方法

    package com.jjl.servlet.user;
    import com.jjl.pojo.User;
    import com.jjl.service.user.UserService;
    import com.jjl.service.user.UserServiceImpl;
    import com.jjl.util.Constants;
    import com.mysql.cj.util.StringUtils;
    
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    //实现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 {
            doGet(req,resp);
        }
        public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            //从session里面拿id;
            Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
            String newpassword = req.getParameter("newpassword");
            System.out.println("UserServlet" +newpassword );
            boolean flag = false;
            //!StringUtils.isNullOrEmpty(newpassword)
            if (attribute!= null && newpassword!=null){
                UserServiceImpl 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","新密码有误");
            }
            req.getRequestDispatcher("pwdmodify.jsp").forward(req,resp);
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51

    9、优化密码修改时,旧密码验证,使用Ajax

    1、导入阿里巴巴的fastjson.jar包,并且将jar复制到tomcat的lib中

    
    <dependency>
        <groupId>com.alibabagroupId>
        <artifactId>fastjsonartifactId>
        <version>2.0.10version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    2、设置session的默认过期时间

    
        <session-config>
            <session-timeout>30session-timeout>
        session-config>
    
    • 1
    • 2
    • 3
    • 4

    3、编写验证密码的方法

    package com.jjl.servlet.user;
    import com.alibaba.fastjson.JSONArray;
    import com.jjl.pojo.User;
    import com.jjl.service.user.UserServiceImpl;
    import com.jjl.util.Constants;
    import com.mysql.cj.util.StringUtils;
    
    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.io.PrintWriter;
    import java.util.HashMap;
    import java.util.Map;
    
    //实现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);
            }else if (method.equals("pwdmodify")&&method!=null){
                this.pwdModify(req, resp);
            }
        }
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req,resp);
        }
        //修改密码
        public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            略·····
        }
    
        //验证旧密码
        public void pwdModify(HttpServletRequest req, HttpServletResponse resp){
            Object attribute = req.getSession().getAttribute(Constants.USER_SESSION);
            String oldpassword = req.getParameter("oldpassword");
    
            //万能的Map: 结果集
            Map<String, String> resultMap = new HashMap<String, String>();
            if (attribute==null){//如果session失效获取过期了,
                resultMap.put("result","sessionerror");
            }else if(StringUtils.isNullOrEmpty(oldpassword)){//如果密码为空
                resultMap.put("result","error");
            }else {
                String userPassword = ((User) attribute).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 阿里巴巴的json工具类,转换格式
                /*
                将Map的格式
                resultMap={"result","error","result","sessionerror"}
                转化成json的格式
                Json格式 = {key: value}
                 */
                writer.write(JSONArray.toJSONString(resultMap));
                writer.flush();//刷新
                writer.close();//关闭
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75

    五、用户管理、分页展示

    思路图
    在这里插入图片描述
    1、导入分页的工具类
    2、用户列表页面导入

    1、获取用户数量

    1、UserDao

    package com.jjl.dao.user;
    
    import com.jjl.pojo.User;
    
    import java.sql.Connection;
    import java.sql.SQLException;
    
    public interface UserDao {
        //得到要登录的用户//获取当前用户密码//查询用户总数
        public int getUserCount(Connection connection, String userName,int userRole) throws SQLException;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    2、UserDaolmpl

    package com.jjl.dao.user;
    
    import com.jjl.dao.BaseDao;
    import com.jjl.pojo.User;
    import com.mysql.cj.util.StringUtils;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    
    public class UserDaoImpl implements UserDao{
        //获取要登录的用户
       	略:
        //修改当前用户密码
        略:
    
        //根据用户名或者用户角色查询用户总数
        public int getUserCount(Connection connection, String userName, int userRole) throws SQLException {
            PreparedStatement pstm=null;
            ResultSet rs =null;
            int count = 0;
            if (connection!=null){
                StringBuilder sql = new StringBuilder();//可变字符串
                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 userName like ?");
                    list.add("%"+userName+"%");
                }
                if (userRole>0){
                    sql.append(" and u.userRole = ?;");
                    list.add(userRole);
                }
                //把list转换为数组
                Object[] params = list.toArray();
                System.out.println("UserDaoImpl->getUserCount:"+sql.toString());
    
                rs = BaseDao.execute(connection,sql.toString(),params,rs,pstm);
                if (rs.next()){
                    count = rs.getInt("count");//从结果集中获取最终的数量
                }
                BaseDao.closeResource(null,pstm,rs);
    
            }
            return count;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49

    3、UserService

    package com.jjl.service.user;
    import com.jjl.pojo.User;
    import java.sql.Connection;
    import java.sql.SQLException;
    public interface UserService {
        //用户登录//根据用户id,修改密码//查询记录数
        public int getUserCount(String username,int userRole);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12

    4、UserServicelmpl

    package com.jjl.service.user;
    
    import com.jjl.dao.BaseDao;
    import com.jjl.dao.user.UserDao;
    import com.jjl.dao.user.UserDaoImpl;
    import com.jjl.pojo.User;
    import org.junit.Test;
    
    import java.sql.Connection;
    import java.sql.SQLException;
    
    public class UserServiceImpl implements UserService{
        //业务层都会调用dao层,所以要引入dao层//业务层实现类,修改密码//查询记录
        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.closeResource(connection,null,null);
            }
            return count;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31

    2、获取用户列表

    1、UserDao

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

    2、UserDaoImpl

    //根据条件查询用户列表
        public List<User> getUserList(Connection connection, String userName, int userRole, int currentPageNo, int pageSize) throws Exception {
            PreparedStatement pstm = null;
            ResultSet rs = null;
            List<User> userList=new ArrayList<User>();
            if (connection!=null){
                StringBuilder sql = new StringBuilder();
                sql.append("select u.*,r.roleName as userRoleName 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+"%");
                }
                if (userRole>0){
                    sql.append(" and u.userRole = ?");
                    list.add(userRole);
                }
    
                //limit在sql中用于指定显示数据的条数,它有两个参数,分别是(从第几条(0开始),到第几条)
                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,sql.toString(),params,rs,pstm);
                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;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43

    3、UserService

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

    4、UserServiceImpl

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

    3、获取角色列表

    把角色的操作放在另一个包中
    1、RoleDao

    package com.jjl.dao.role;
    
    import com.jjl.pojo.Role;
    
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.util.List;
    
    public interface RoleDao {
        //获取角色列表
        public List<Role> getRoleList(Connection connection)throws SQLException;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    2、RoleDaoImpl

    package com.jjl.dao.role;
    
    import com.jjl.dao.BaseDao;
    import com.jjl.pojo.Role;
    
    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.List;
    
    public class RoleDaoImpl implements RoleDao {
        //获取角色列表
        public List<Role> getRoleList(Connection connection) throws SQLException {
            PreparedStatement pstm =null;
            ResultSet rs=null;
            ArrayList<Role> rolesList = new ArrayList<Role>();
            if (connection!=null){
                String sql = "select * from smbms_role";
                Object[] params = {};
                rs= BaseDao.execute(connection,sql,params,rs,pstm);
                while (rs.next()){
                    Role role = new Role();
                    role.setId(rs.getInt("id"));
                    role.setRoleCode(rs.getString("roleCode"));
                    role.setRoleName(rs.getString("roleName"));
                    rolesList.add(role);
                }
                BaseDao.closeResource(null,pstm,rs);
            }
            return rolesList;
        }
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35

    3、RoleService

    package com.jjl.service.role;
    
    import com.jjl.pojo.Role;
    
    import java.sql.Connection;
    import java.sql.SQLException;
    import java.util.List;
    
    public interface RoleService {
        //获取角色列表
        public List<Role> getRoleList()throws SQLException;
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13

    4、RoleServiceImpl

    package com.jjl.service.role;
    
    import com.jjl.dao.BaseDao;
    import com.jjl.dao.role.RoleDao;
    import com.jjl.dao.role.RoleDaoImpl;
    import com.jjl.pojo.Role;
    import org.junit.Test;
    
    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() throws SQLException {
            Connection connection = null;
            List<Role> roleList=null;
            connection = BaseDao.getConnection();
            roleList = roleDao.getRoleList(connection);
            BaseDao.closeResource(connection,null,null);
            return roleList;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28

    4、Servlet层

    package com.jjl.servlet.user;
    import com.alibaba.fastjson.JSONArray;
    import com.jjl.pojo.Role;
    import com.jjl.pojo.User;
    import com.jjl.service.role.RoleServiceImpl;
    import com.jjl.service.user.UserServiceImpl;
    import com.jjl.util.Constants;
    import com.jjl.util.PageSupport;
    import com.mysql.cj.util.StringUtils;
    
    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.io.PrintWriter;
    import java.sql.SQLException;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    //实现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);
            }else if (method.equals("pwdmodify")&&method!=null){
                this.pwdModify(req, resp);
            } else if (method.equals("query")&&method!=null) {
                try {
                    this.query(req, resp);
                } catch (SQLException e) {
                    throw new RuntimeException(e);
                }
    
            }
        }
    
        @Override
        protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
            doGet(req,resp);
        }
        //修改密码//验证旧密码//用户管理
        public void query(HttpServletRequest req, HttpServletResponse resp) throws IOException, SQLException, ServletException {
            //查询用户列表
            //从前端获取数据
            String queryUserName = req.getParameter("queryname");
            String queryUserRole = req.getParameter("queryUserRole");
            String pageIndex = req.getParameter("pageIndex");
            int queryuserrole =0;
            List<User> userList=null;
    
            //获取用户列表
            UserServiceImpl userService = new UserServiceImpl();
            //第一次走这个请求,一定是第一页,页面大小固定的
            int pageSize = 3;
            int currentPageNo = 1;
    
            if (queryUserName==null){
                queryUserName="";
            }
            if (queryUserRole!=null&&!queryUserRole.equals("")){
                queryuserrole=Integer.parseInt(queryUserRole);
            }
            if (pageIndex!=null){
                try {
                    currentPageNo = Integer.parseInt(pageIndex);
                }catch (Exception e){
                    resp.sendRedirect("error.jsp");
                }
    
            }
            //获取用户总数(分页,上一页,下一页)
            int totalCount = userService.getUserCount(queryUserName, queryuserrole);
            PageSupport pageSupport = new PageSupport();
            //用户输入的当前页数
            pageSupport.setCurrentPageNo(currentPageNo);
            //页面容量
            pageSupport.setPageSize(pageSize);
            //总页数
            pageSupport.setTotalCount(totalCount);
    
            int totalPageCount = pageSupport.getTotalPageCount();
            //控制首页和尾页
            if (currentPageNo<1){//如果当前页数小于1了,则就强制显示第一页内容
                currentPageNo=1;
            } else if (currentPageNo>totalPageCount) {//如果当前页面大于了最后一页,则就当前页面就等于最后一页
                currentPageNo=totalPageCount;
            }
    
            //获取用户列表展示
            userList = userService.getUserList(queryUserName, queryuserrole, currentPageNo, pageSize);
            req.setAttribute("userList",userList);
            req.setAttribute("queryUserName",queryUserName);
            req.setAttribute("queryUserRole",queryuserrole);
    
            //获取角色列表
            RoleServiceImpl roleService = new RoleServiceImpl();
            List<Role> roleList = roleService.getRoleList();
            req.setAttribute("roleList",roleList);
    
            //把总页数、总数、当前页数返回前端
            req.setAttribute("totalPageCount",totalPageCount);
            req.setAttribute("totalCount",totalCount);
            req.setAttribute("currentPageNo",currentPageNo);
    
    
            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
    
            ArrayList<User> arrayList = new ArrayList<User>(userList);
            for (User user : arrayList) {
                System.out.println(user.getAge().toString());
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124

    5、添加用户

    1、dao

    public int add(Connection connection, User user) throws SQLException {
            PreparedStatement pstm=null;
            int updateRows = 0;
            if (connection!=null){
                String sql = "insert into smbms_user (userCode, userName, userPassword, " +
                        "gender, birthday, phone, address, userRole, createdBy, creationDate) " +
                        "VALUES (?,?,?,?,?,?,?,?,?,?)";
                Object [] params = {user.getUserCode(),user.getUserName(),user.getUserPassword(), user.getGender(),
                        user.getBirthday(),user.getPhone(),user.getAddress(),user.getUserRole(),user.getCreatedBy(),user.getCreationDate()};
                updateRows = BaseDao.execute(connection,sql,params,pstm);
                BaseDao.closeResource(null,pstm,null);
            }
            return updateRows;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    2、service层

    //添加用户
        public boolean add(User user) {
            boolean flag = false;
            Connection connection= null;
    
            try {
                connection = BaseDao.getConnection();
                connection.setAutoCommit(false);//打开jdbc事务管理
                int updateRows = userDao.add(connection,user);
                connection.commit();
                if (updateRows>0){
                    flag=true;
                    System.out.println("add success!");
                }else {
                    System.out.println("add failed!");
                }
            } catch (SQLException e) {
                e.printStackTrace();
                try {
                    connection.rollback();
                } catch (SQLException ex) {
                    ex.printStackTrace();
                }
            }finally {
                BaseDao.closeResource(connection,null,null);
            }
            return flag;
        }
        
        //验证用户编码
        public boolean getUserCode(String userCode) {
            boolean flag = false;
            Connection connection=null;
            connection = BaseDao.getConnection();
            try {
                if (userDao.userCode(connection,userCode)>0){
                    flag = true;
                }
            } catch (Exception e) {
                throw new RuntimeException(e);
            }finally {
                BaseDao.closeResource(connection,null,null);
            }
            return flag;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45

    3、srivlet层

    //增加用户
        public void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
            req.getRequestDispatcher("useradd.jsp").forward(req,resp);
            System.out.println("add()============");
            String userCode = req.getParameter("userCode");
            String userName = req.getParameter("userName");
            String password = req.getParameter("userPassword");
            String gender = req.getParameter("gender");
            String birthday = req.getParameter("birthday");
            String phone = req.getParameter("phone");
            String address = req.getParameter("address");
            String userRole = req.getParameter("userRole");
    
            User user = new User();
            user.setUserCode(userCode);
            user.setUserName(userName);
            user.setUserPassword(password);
            user.setGender(Integer.valueOf(gender));
            try {
                user.setBirthday(new SimpleDateFormat("yyyyy-MM-dd").parse(birthday));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            user.setPhone(phone);
            user.setAddress(address);
            user.setUserRole(Integer.valueOf(userRole));
            user.setCreationDate(new Date());
            user.setCreatedBy(((User)req.getSession().getAttribute(Constants.USER_SESSION)).getId());
    
            UserServiceImpl userService = new UserServiceImpl();
            if (userService.add(user)){
                resp.sendRedirect(req.getContextPath()+"/jsp/user.do?method=query");
                System.out.println("用户添加成功");
    //            req.getRequestDispatcher("userlist.jsp").forward(req,resp);
            }else {
                req.getRequestDispatcher("useradd.jsp").forward(req,resp);
            }
        }
    
        //获取角色列表
        public void rolelist(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException, SQLException {
            RoleServiceImpl roleService = new RoleServiceImpl();
            List<Role> roleList = roleService.getRoleList();
            req.setAttribute("RoleList",roleList);
    
            Map<String, String> roleMap = new HashMap<String, String>();
            for (Role role : roleList) {
                roleMap.put(String.valueOf(role.getId()),role.getRoleName());
            }
    
            resp.setContentType("application/json");
            resp.setCharacterEncoding("utf-8");
            PrintWriter writer = resp.getWriter();
            writer.write(JSONArray.toJSONString(roleMap));
            writer.flush();//刷新
            writer.close();//关闭
        }
    
    
        //验证用户名
        public void ucexist(HttpServletRequest req, HttpServletResponse resp){
            UserServiceImpl userService = new UserServiceImpl();
            //万能的Map: 结果集
            Map<String, String> userCodeMap = new HashMap<String, String>();
            reqUserCode = req.getParameter("userCode");
            boolean userCode = userService.getUserCode(reqUserCode);
            System.out.println(userCode);
            if (reqUserCode==null || reqUserCode==""){
                userCodeMap.put("userCode","existnull");
            }else if(userCode){
                userCodeMap.put("userCode","exist");
                System.out.println("ucexist=====>"+userCode);
            }else {
                System.out.println("可以新添加用户");
            }
            try {
                resp.setContentType("application/json");
                PrintWriter writer = resp.getWriter();
                writer.write(JSONArray.toJSONString(userCodeMap));
                writer.flush();//刷新
                writer.close();//关闭
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
  • 相关阅读:
    Armv8/9-A cpu在安全/非安全世界切换时,是否需要对共享内存进行cache维护操作?
    【正点原子STM32连载】第一章 本书学习方法 摘自【正点原子】MiniPro STM32H750 开发指南_V1.1
    【三维目标检测】Part-A2(二)
    7-38 最小生成树的唯一性
    人工智能三要素之算法Transformer
    6.DesignForPlacement\QueryorModifyObject
    SQL 选择数据库 USE语句
    vue3+ts的computed属性
    AS/400连接字符串
    计算机毕业设计之java+javaweb的烘焙爱好者网站
  • 原文地址:https://blog.csdn.net/qq_43427354/article/details/125934439