smbms 获取角色操作,角色管理实现

2023-11-20

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

RoleDao(接口):

package com.Li.dao.role;

import com.Li.pojo.Role;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
//专职搞Role这一块。
public interface RoleDao {
    //获取角色列表
    public List<Role> getRoleList(Connection connection) throws SQLException;
}

RoleDaoImpl(实现类):

package com.Li.dao.role;

import com.Li.dao.BaseDao;
import com.Li.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 resultSet = null;
        ArrayList<Role> roleList = new ArrayList<Role>();

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

            while (resultSet.next()){//从数据库中读出来.把所有角色读取,放在列表里面
                Role _role = new Role();
                _role.setId(resultSet.getInt("id"));
                _role.setRoleCode(resultSet.getString("roleCode"));
                _role.setRoleName(resultSet.getString("roleName"));
                roleList.add(_role);
            }
            BaseDao.closeResource(null, resultSet, pstm);
        }
        return roleList;

    }
}

之前没放进user包中,我这次自己建了一个包放了进去。

RoleService(接口)
package com.Li.service.role;

import com.Li.pojo.Role;

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

public interface RoleService {
    //获取角色列表
    public List<Role> getRoleList();
}
RoleServiceImpl(实现类)
package com.Li.service.role;

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

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

public class RoleServiceImpl implements RoleService{

    //先引入Dao.为了一开始进入这个java文件就加载下层的Dao。
    private RoleDao roleDao;
    public RoleServiceImpl() {
        roleDao = new RoleDaoImpl();
    }

    //得到用户的列表.并且返回
    public List<Role> getRoleList() {

        Connection connection = null;
        List<Role> roleList = null;

        try {
            connection = BaseDao.getConnection();//就这try里面这两句。其他的都是衍生的。
            roleList = roleDao.getRoleList(connection);//得到用户的列表
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } finally {
            BaseDao.closeResource(connection, null, null);
        }
        return roleList;
    }
}

接下来可以在service层的实现类进行测试:

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

 成功!

接下来就依据前端的代码开始写了。。。

在servlet中:

以上都是准备工作,可以和上一个博客内容放在一块。准备工作做完。下面才是重点!

 用户显示的servlet:

步骤:(都是由需求而创建的)

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

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

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

4.用户列表展示

5.返回前端

新写的是query类。我把所有的类都粘了过来,不要介意。

package com.Li.servlet.user;

import com.Li.pojo.Role;
import com.Li.pojo.User;
import com.Li.service.role.RoleServiceImpl;
import com.Li.service.user.UserServiceImp1;
import com.Li.util.Constants;
import com.Li.util.PageSupport;
import com.alibaba.fastjson.JSONArray;
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.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!=null && method.equals("savepwd")){//新密码修改
            this.updatePwd(req, resp);
        }else if (method!=null && method.equals("pwdmodify")){//旧密码验证
            this.pwdmodify(req, resp);
        }else if (method!=null && method.equals("query")){
            this.query(req, resp);
        }
    }

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

//重难点!
    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;

        //获取用户列表
        UserServiceImp1 userService = new UserServiceImp1();

        //第一次走这个请求,一定是第一页,页面大小固定
        int pageSize = 5;//可以把这个写到配置文件中,方便后期的修改;
        int currentPageNo = 1;

        if (queryUserName==null){
            queryUserName = "";
        }
        if (temp!=null && !temp.equals("")){
            queryUserRole = Integer.parseInt(temp);//给查询先赋初值。0123等等。。。
        }
        if(pageIndex!=null){//解析前端传过来的数字。判断具体是第几页,对current进行赋值
            currentPageNo = Integer.parseInt(pageIndex);
        }

        //获取用户的总数
        int totalCount = userService.getUserCount(queryUserName, queryUserRole);
        //总页数支持
        PageSupport pageSupport = new PageSupport();
        pageSupport.setCurrentPageNo(currentPageNo);
        pageSupport.setPageSize(pageSize);
        pageSupport.setTotalCount(totalCount);


        int totalPageCount = ((int)totalCount/pageSize)+1;//这里是狂神的方式,建议自己升级一下
        //控制首页和尾页
        //如果页面要小于一,就显示第一页的东西。反之亦然
        if (totalPageCount<1){
            currentPageNo = 1;
        }else if (currentPageNo>totalPageCount){
            totalPageCount = totalPageCount;
        }

        //获取用户列表显示
        List<User> 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);
        req.setAttribute("queryUserName",queryUserName);
        req.setAttribute("queryUserRole",queryUserRole);

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

    }

    //封装updatePwd
    //修改密码
    public void updatePwd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从session中拿ID
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);

        String newpassword = req.getParameter("newpassword");

        boolean flag = false;

        if (o!=null && newpassword!=null){
            UserServiceImp1 userService = new UserServiceImp1();
            flag = userService.updatePwd(((User) o).getId(), newpassword);//将o转为User并且获取代码

            //如果27句成功。
            if (flag){
                req.setAttribute("message", "修改密码成功,请退出,使用新密码登录");
                //密码修改成功。移除当前Session.之后由于过滤器,没有session之后就会跳转到错误页面
                req.getSession().removeAttribute(Constants.USER_SESSION);
            }else {
                req.setAttribute("message", "密码修改失败。");
                //密码修改失败。
            }
        }else {
            req.setAttribute("message", "新密码有问题。");
        }

        req.getRequestDispatcher("pwdmodify.jsp").forward(req, resp);
    }

    //验证就旧密码,session中有用户的旧密码
    public void pwdmodify(HttpServletRequest req, HttpServletResponse resp){
        //从session中拿ID
        Object o = req.getSession().getAttribute(Constants.USER_SESSION);
        String oldpassword = req.getParameter("oldpassword");

        //万能的Map : 结果集
        Map<String, String> resultMap = new HashMap<String,String>();

        if (o==null){//session失效了,session过期了
            resultMap.put("result", "sessionerror");
        }else if (StringUtils.isNullOrEmpty(oldpassword)){//输入的密码为空
            resultMap.put("result","error");
        }else {
            String userPassword = ((User) o).getUserPassword();//session中用户的密码
            if (oldpassword.equals(userPassword)){
                resultMap.put("result","true");
            }else {
                resultMap.put("result","false");
            }
        }


        try {
            resp.setContentType("application/json");
            PrintWriter writer = resp.getWriter();
            //JSONArray 阿里巴巴的Json工具类,就是一个转换格式的。
            /*
            * resultMap = ["result","error","result","true"]
            * Json格式 = {key,value}
            * */
            writer.write(JSONArray.toJSONString(resultMap));//就是把结果集编程json字符串传给前端。
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

}

里面的细节:

userList的由来 

roleList:

 

 

set的值由来:

 

 成果:

 

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

smbms 获取角色操作,角色管理实现 的相关文章

随机推荐

  • ENSP—NAT综合实验

    实验要求 1 IP地址的规划和拓扑搭建 2 IP地址的配置 AR1的代码如下 r1 interface g0 0 1 r1 GigabitEthernet0 0 1 ip add 12 1 1 1 24 r1 GigabitEthernet
  • 服务器虚拟化的优势

    1 提高硬件资源使用效率 一个服务器上可以开多个虚拟机 给不同应用使用 打破一个应用一台服务器的限制 因为某具体用户使用的时间 资源有限 多个用户 应用 就可以大大提高服务器的使用效率 减少服务器数量 可以 降低购买服务器的投资 降低服务器
  • C++(四)——C++标准模板库

    文章目录 1 STL组件 Component 2 容器 Container 2 1 序列式容器 Sequence Container 2 2 关联式容器 Associative Container 2 3 无序容器 Unordered Co
  • 用matlab绘制系统函数的DTFT

    freqz函数 frequency response of digital filter 对于一个输入离散序列 输出离散序列的离散时间系统 我们可以用它的系统函数H Z 来描述这个系统 求这个系统函数的DTFT 可以得到这个系统的幅频响应和
  • logback-spring.xml中三种相对路径生成的日志文件的位置

    logback spring xml中关于路径配置的三种写法 写法1
  • 大屏图表,ECharts 从“熟练”到入门

    阅读本文 你将 了解 配置驱动 的思想 理解 Echarts 基本概念 了解 graphic 和 动画基本玩法 了解 Echarts 基底组件的封装的思路 一 不是标题党 Echarts 简历上人均 熟练 公司最近在招外包 而因为目前大屏的
  • java自动识别文件编码格式UTF-8,UTF-8无BOM,GBK

    背景 在解读properties配置文件时windows操作系统编辑过的内容上传后总是无法通过键获取文件中内容 讲过分析是文件的编码格式为UTF 8带BOM的 因此通过该程序获取文件编码格式 import java io BufferedI
  • ES6阮一峰入门教程

    地址为 https es6 ruanyifeng com
  • visual studio 一直显示正在准备解决方案

    首先重启电脑 无法解决的情况下执行以下步骤 Kill Visual Studio Open Visual Studio without loading a solution Disable AnkhSvn as Source Control
  • vue动态绑定video视频src问题解决

    做个项目 视频部分需要先后台上传 然后前端页面显示 然后就遇到了视频动态获取地址的问题 一开始想着很简单 使用v model双向绑定就行了 结果试了下并不行 后面开始度娘 尝试过很多人说的 refs解决 结果并不行 虽然浏览器中看地址确实绑
  • 设计模式(2)

    2 2 结构型模式 结构型模式一共有七种 其中 适配器模式和装饰模式统称为包装模式 装饰模式和代理模式的类图基本相同 但目的不同 这些有相似目的或者有相似结构的模式需要对其概念辨析清楚 才能较好地掌握 下面将对结构型模式分别进行介绍 2 2
  • C++启蒙笔记(八)---类继承、动态内存分配

    目录 一 基本概念 1 1派生类 1 2 继承关系 二 常规写法 2 1 头文件 2 2 类实现 2 3 主程序 2 4 编译及显示 三 多态公有继承 3 1 虚方法 3 2 抽象基类 3 3 多重继承MI 四 动态内存分配 4 1 头文件
  • PyTorch实现Logistic Regression

    1 PyTorch基础实现Logistic regression import torch from torch autograd import Variable torch manual seed 2 x data Variable to
  • Python in Visual Studio Code 2023年9月更新

    作者 Courtney Webster Program Manager Python Extension in Visual Studio Code 排版 Alan Wang 我们很高兴地宣布 Visual Studio Code 的 Py
  • 黑白图片上色算法

    效果图 Marked B W image Result Marked B W image Result Marked B W image Result Marked B W i
  • win10 系统锁屏壁纸的目录

    路径 C Users 你自己的用户名 AppData Local Packages Microsoft Windows ContentDeliveryManager cw5n1h2txyewy LocalState Assets 查看 需要
  • 使用php简单网页抓取和内容分析,PHP抓取及分析网页的方法详解

    本文实例讲述了PHP抓取及分析网页的方法 分享给大家供大家参考 具体如下 抓取和分析一个文件是非常简单的事 这个教程将通过一个例子带领你一步一步地去实现它 让我们开始吧 首先 我首必须决定我们将抓取的URL地址 可以通过在脚本中设定或通过
  • python 去除所有的中文 英文标点符号

    去除英文标点符号 python的string模块下的 punctuation 包含所有的英文标点符号 所以用replace 一下就可以去除 代码示例 import string stri today is friday so happy p
  • MacOS中清除原有ssh公钥方法

    2019独角兽企业重金招聘Python工程师标准 gt gt gt 用ssh的跳转登录服务器后 ssh会把你每个你访问过计算机的公钥 public key 都记录在 ssh known hosts 当下次访问相同计算机时 SSH会核对公钥
  • smbms 获取角色操作,角色管理实现

    为了我们职责统一 可以把角色的操作单独放在一个包中 和pojo中的对应 RoleDao 接口 package com Li dao role import com Li pojo Role import java sql Connectio