【愚公系列】2023年04月 Java面面刷题系统-003.报表与权限模块


一、报表与权限模块

1. ​报表

报表是一种用于展示数据、统计信息、业务流程等的文件或文档,通常用于管理决策、业务分析和信息沟通等方面。报表可以包括表格、图表、图像、文本等形式,通过数据的可视化展示,帮助用户更好地了解业务情况、分析趋势、制定计划、评估绩效等。报表在各种领域都有应用,如财务、市场、生产、人力资源等。

在Java中对于Excel报表的技术实现上也有很多种选择:

  • JXL:支持xls文件操作
  • POI:支持xls和xlsx文件操作

我们只要来讲POI技术,要使用POI就要导入其坐标,如下

<!--POI-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>4.0.1</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>4.0.1</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>4.0.1</version>
</dependency>

1.1 POI写Excel文件

1、在测试包下创建POI测试类:PoiTest

public class PoiTest {
    
    

    @Test
    public void testWriteByPoi() throws IOException {
    
    
        //1.获取到对应的Excel文件,工作簿文件
        Workbook wb = new XSSFWorkbook();
        //2.创建工作表
        Sheet sheet = wb.createSheet();
        wb.createSheet("这是啥呀");

        //3.创建工作表中的行对象
        Row row = sheet.createRow(1);
        //4.创建工作表中行中的列对象
        Cell cell = row.createCell(1);
        //5.在列中写数据
        cell.setCellValue("测试一下单元格");

        //创建一个文件对象,作为excel文件内容的输出文件
        File f = new File("test.xlsx");
        //输出时通过流的形式对外输出,包装对应的目标文件
        OutputStream os = new FileOutputStream(f);
        //将内存中的workbook数据写入到流中
        wb.write(os);
        wb.close();
        os.close();
    }
}

使用单元测试进行测试!

1.2 POI读Excel文件

创建读Excel的测试方法:testReadByPoi

@Test
public void testReadByPoi() throws IOException {
    
    
    //1.获取要读取的文件工作簿对象
    Workbook wb = new XSSFWorkbook("test.xlsx");
    //2.获取工作表
    Sheet s = wb.getSheetAt(0);
    //3.获取行
    Row row = s.getRow(3);
    //4.获取列
    Cell cell = row.getCell(1);
    //5.根据数据的类型获取数据
    //        String data = cell.getStringCellValue();
    //        double data = cell.getNumericCellValue();
    boolean data = cell.getBooleanCellValue();

    System.out.println(data);

    wb.close();
}

直接读取第一节创建好的Excel文件

1.3 题目模板表头制作

导出报表的模板:资料\Excel解析\模板.xlsx

在这里插入图片描述

@Test
public void testProjectPoi() throws IOException {
    
    
    //1.获取到对应的Excel文件,工作簿文件
    Workbook wb = new XSSFWorkbook();
    //2.创建工作表
    Sheet s = wb.createSheet("题目数据文件");
    //制作标题
    s.addMergedRegion(new CellRangeAddress(1,1,1,12)); 
    Row row_1 = s.createRow(1);
    Cell cell_1_1 = row_1.createCell(1);
    cell_1_1.setCellValue("在线试题导出信息");
    //创建一个样式
    CellStyle cs_title = wb.createCellStyle();
    cs_title.setAlignment(HorizontalAlignment.CENTER);
    cs_title.setVerticalAlignment(VerticalAlignment.CENTER);
    cell_1_1.setCellStyle(cs_title);
    //制作表头
    
    //制作数据区
    
    //创建一个文件对象,作为excel文件内容的输出文件
    File f = new File("test.xlsx");
    //输出时通过流的形式对外输出,包装对应的目标文件
    OutputStream os = new FileOutputStream(f);
    //将内存中的workbook数据写入到流中
    wb.write(os);
    wb.close();
    os.close();
}

1.4 题目模板标题制作

下面我们接着来做Excel的表头

在测试方法testProjectPoi中继续编写代码

@Test
public void testProjectPoi() throws IOException {
    
    
    //1.获取到对应的Excel文件,工作簿文件
    Workbook wb = new XSSFWorkbook();
    //2.创建工作表
    Sheet s = wb.createSheet("题目数据文件");
    //设置通用配置
    //        s.setColumnWidth(4,100);
    //制作标题
    s.addMergedRegion(new CellRangeAddress(1,1,1,12));  
    Row row_1 = s.createRow(1);
    Cell cell_1_1 = row_1.createCell(1);
    cell_1_1.setCellValue("在线试题导出信息");
    //创建一个样式
    CellStyle cs_title = wb.createCellStyle();
    cs_title.setAlignment(HorizontalAlignment.CENTER);
    cs_title.setVerticalAlignment(VerticalAlignment.CENTER);
    cell_1_1.setCellStyle(cs_title);
    //制作表头
   String[] fields = {
    
    "题目ID","所属公司ID","所属目录ID","题目简介","题干描述",
                "题干配图","题目分析","题目类型","题目难度","是否经典题","题目状态","审核状态"};
    Row row_2 = s.createRow(2);
    for (int i = 0; i < fields.length; i++) {
    
    
        Cell cell_2_temp = row_2.createCell(1 + i); //++
        cell_2_temp.setCellValue(fields[i]);    //++
        
        CellStyle cs_field = wb.createCellStyle();
        cs_field.setAlignment(HorizontalAlignment.CENTER);
        cell_2_temp.setCellStyle(cs_field);
    }
    
    //制作数据区

    //创建一个文件对象,作为excel文件内容的输出文件
    File f = new File("test.xlsx");
    //输出时通过流的形式对外输出,包装对应的目标文件
    OutputStream os = new FileOutputStream(f);
    //将内存中的workbook数据写入到流中
    wb.write(os);
    wb.close();
    os.close();
}

1.5 题目模板数据制作

我们继续来做数据区

@Test
public void testProjectPoi() throws IOException {
    
    
    //1.获取到对应的Excel文件,工作簿文件
    Workbook wb = new XSSFWorkbook();
    //2.创建工作表
    Sheet s = wb.createSheet("题目数据文件");
    //设置通用配置
    //        s.setColumnWidth(4,100);
    CellStyle cs_field = wb.createCellStyle();
    cs_field.setAlignment(HorizontalAlignment.CENTER);
    cs_field.setBorderTop(BorderStyle.THIN);
    cs_field.setBorderBottom(BorderStyle.THIN);
    cs_field.setBorderLeft(BorderStyle.THIN);
    cs_field.setBorderRight(BorderStyle.THIN);

    
    //制作标题
    s.addMergedRegion(new CellRangeAddress(1,1,1,12));
    Row row_1 = s.createRow(1);
    Cell cell_1_1 = row_1.createCell(1);
    cell_1_1.setCellValue("在线试题导出信息");
    //创建一个样式
    CellStyle cs_title = wb.createCellStyle();
    cs_title.setAlignment(HorizontalAlignment.CENTER);
    cs_title.setVerticalAlignment(VerticalAlignment.CENTER);
    cell_1_1.setCellStyle(cs_title);
    //制作表头
    String[] fields = {
    
    "题目ID","所属公司ID","所属目录ID","题目简介","题干描述",
                       "题干配图","题目分析","题目类型","题目难度","是否经典题","题目状态","审核状态"};
    Row row_2 = s.createRow(2);

    for (int i = 0; i < fields.length; i++) {
    
    
        Cell cell_2_temp = row_2.createCell(1 + i); //++
        cell_2_temp.setCellValue(fields[i]);    //++
        cell_2_temp.setCellStyle(cs_field);
    }

    
    //制作数据区
    List<Question> questionList = new ArrayList<>();
    Question qq = new Question();
    qq.setId("1");
    qq.setPicture("12");
    qq.setReviewStatus("13");
    qq.setAnalysis("14");
    qq.setCatalogId("15");
    qq.setCompanyId("16");
    qq.setDifficulty("17");
    qq.setIsClassic("18");
    qq.setRemark("19");
    qq.setState("21");
    qq.setSubject("31");
    qq.setType("41");
    questionList.add(qq);
    Question qqq = new Question();
    qqq.setId("1");
    qqq.setPicture("12");
    qqq.setReviewStatus("13");
    qqq.setAnalysis("14");
    qqq.setCatalogId("15");
    qqq.setCompanyId("16");
    qqq.setDifficulty("17");
    qqq.setIsClassic("18");
    qqq.setRemark("19");
    qqq.setState("21");
    qqq.setSubject("31");
    qqq.setType("41");
    questionList.add(qqq);


    int row_index = 0;
    for (Question q : questionList) {
    
    
        int cell_index = 0;
        Row row_temp = s.createRow(3 + row_index++);

        Cell cell_data_1 = row_temp.createCell(1 + cell_index++);
        cell_data_1.setCellValue(q.getId());    //++
        cell_data_1.setCellStyle(cs_field);

        Cell cell_data_2 = row_temp.createCell(1 + cell_index++);
        cell_data_2.setCellValue(q.getCompanyId());    //++
        cell_data_2.setCellStyle(cs_field);

        Cell cell_data_3 = row_temp.createCell(1 + cell_index++);
        cell_data_3.setCellValue(q.getCatalogId());    //++
        cell_data_3.setCellStyle(cs_field);

        Cell cell_data_4 = row_temp.createCell(1 + cell_index++);
        cell_data_4.setCellValue(q.getRemark());    //++
        cell_data_4.setCellStyle(cs_field);

        Cell cell_data_5 = row_temp.createCell(1 + cell_index++);
        cell_data_5.setCellValue(q.getSubject());    //++
        cell_data_5.setCellStyle(cs_field);

        Cell cell_data_6 = row_temp.createCell(1 + cell_index++);
        cell_data_6.setCellValue(q.getPicture());    //++
        cell_data_6.setCellStyle(cs_field);

        Cell cell_data_7 = row_temp.createCell(1 + cell_index++);
        cell_data_7.setCellValue(q.getAnalysis());    //++
        cell_data_7.setCellStyle(cs_field);

        Cell cell_data_8 = row_temp.createCell(1 + cell_index++);
        cell_data_8.setCellValue(q.getType());    //++
        cell_data_8.setCellStyle(cs_field);

        Cell cell_data_9 = row_temp.createCell(1 + cell_index++);
        cell_data_9.setCellValue(q.getDifficulty());    //++
        cell_data_9.setCellStyle(cs_field);

        Cell cell_data_10 = row_temp.createCell(1 + cell_index++);
        cell_data_10.setCellValue(q.getIsClassic());    //++
        cell_data_10.setCellStyle(cs_field);

        Cell cell_data_11 = row_temp.createCell(1 + cell_index++);
        cell_data_11.setCellValue(q.getState());    //++
        cell_data_11.setCellStyle(cs_field);

        Cell cell_data_12 = row_temp.createCell(1 + cell_index++);
        cell_data_12.setCellValue(q.getReviewStatus());    //++
        cell_data_12.setCellStyle(cs_field);
    }

    //创建一个文件对象,作为excel文件内容的输出文件
    File f = new File("test.xlsx");
    //输出时通过流的形式对外输出,包装对应的目标文件
    OutputStream os = new FileOutputStream(f);
    //将内存中的workbook数据写入到流中
    wb.write(os);
    wb.close();
    os.close();
}

1.6 题目报表数据准备

1、找到/WEB-INF/pages/store/question/list.jsp页面,修改导出题目的链接

<button type="button" class="btn btn-default" title="导出题目" οnclick=location.href="${ctx}/store/question?operation=downloadReport"> <i class="fa fa-download"></i>导出题目</button>

在这里插入图片描述

2、在后台servlet中添加对应的方法

// uri:/store/question?operation=list
@WebServlet("/store/question")
public class QuestionServlet extends BaseServlet {
    
    

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        String operation = request.getParameter("operation");
        if("list".equals(operation)){
    
    
            this.list(request,response);
        }
        //其他的else if判断省略
        else if("downloadReport".equals(operation)){
    
    
            this.downloadReport(request,response);
        }
    }

    private void downloadReport(HttpServletRequest request, HttpServletResponse response) throws IOException {
    
    
        //生成报告的文件,然后传递到前端页面
        questionService.getReport();
    }
}

3、在业务层QuestionService添加一个方法getReport

public void getReport() throws IOException;

4、在对应的实现类中去实现该方法,把之前在测试类中的测试方法testProjectPoi里面的所有代码拷贝过来,其中数据我们应该是从数据库中查询出来,因此调用dao完成数据的查询

@Override
public void getReport() throws IOException{
    
    
     //获取对应要展示的数据
        SqlSession sqlSession = null;
        List<Question> questionList = null;
        try{
    
    
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            QuestionDao questionDao = MapperFactory.getMapper(sqlSession,QuestionDao.class);
            //3.调用Dao层操作
            questionList = questionDao.findAll();
        }catch (Exception e){
    
    
            throw new RuntimeException(e);
            //记录日志
        }finally {
    
    
            try {
    
    
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
    
    
        //1.获取到对应的Excel文件,工作簿文件
        Workbook wb = new XSSFWorkbook();
        //2.创建工作表
        Sheet s = wb.createSheet("题目数据文件");
        //设置通用配置
//        s.setColumnWidth(4,100);
        CellStyle cs_field = wb.createCellStyle();
        cs_field.setAlignment(HorizontalAlignment.CENTER);
        cs_field.setBorderTop(BorderStyle.THIN);
        cs_field.setBorderBottom(BorderStyle.THIN);
        cs_field.setBorderLeft(BorderStyle.THIN);
        cs_field.setBorderRight(BorderStyle.THIN);
        //制作标题
        s.addMergedRegion(new CellRangeAddress(1,1,1,12));
        Row row_1 = s.createRow(1);
        Cell cell_1_1 = row_1.createCell(1);
        cell_1_1.setCellValue("在线试题导出信息");
        //创建一个样式
        CellStyle cs_title = wb.createCellStyle();
        cs_title.setAlignment(HorizontalAlignment.CENTER);
        cs_title.setVerticalAlignment(VerticalAlignment.CENTER);
        cell_1_1.setCellStyle(cs_title);

    
        //制作表头
        String[] fields = {
    
    "题目ID","所属公司ID","所属目录ID","题目简介","题干描述",
                "题干配图","题目分析","题目类型","题目难度","是否经典题","题目状态","审核状态"};
        Row row_2 = s.createRow(2);
        for (int i = 0; i < fields.length; i++) {
    
    
            Cell cell_2_temp = row_2.createCell(1 + i); //++
            cell_2_temp.setCellValue(fields[i]);    //++
            cell_2_temp.setCellStyle(cs_field);
        }
        //制作数据区
        int row_index = 0;
        for (Question q : questionList) {
    
    
            int cell_index = 0;
            Row row_temp = s.createRow(3 + row_index++);

            Cell cell_data_1 = row_temp.createCell(1 + cell_index++);
            cell_data_1.setCellValue(q.getId());    //++
            cell_data_1.setCellStyle(cs_field);

            Cell cell_data_2 = row_temp.createCell(1 + cell_index++);
            cell_data_2.setCellValue(q.getCompanyId());    //++
            cell_data_2.setCellStyle(cs_field);

            Cell cell_data_3 = row_temp.createCell(1 + cell_index++);
            cell_data_3.setCellValue(q.getCatalogId());    //++
            cell_data_3.setCellStyle(cs_field);

            Cell cell_data_4 = row_temp.createCell(1 + cell_index++);
            cell_data_4.setCellValue(q.getRemark());    //++
            cell_data_4.setCellStyle(cs_field);

            Cell cell_data_5 = row_temp.createCell(1 + cell_index++);
            cell_data_5.setCellValue(q.getSubject());    //++
            cell_data_5.setCellStyle(cs_field);

            Cell cell_data_6 = row_temp.createCell(1 + cell_index++);
            cell_data_6.setCellValue(q.getPicture());    //++
            cell_data_6.setCellStyle(cs_field);

            Cell cell_data_7 = row_temp.createCell(1 + cell_index++);
            cell_data_7.setCellValue(q.getAnalysis());    //++
            cell_data_7.setCellStyle(cs_field);

            Cell cell_data_8 = row_temp.createCell(1 + cell_index++);
            cell_data_8.setCellValue(q.getType());    //++
            cell_data_8.setCellStyle(cs_field);

            Cell cell_data_9 = row_temp.createCell(1 + cell_index++);
            cell_data_9.setCellValue(q.getDifficulty());    //++
            cell_data_9.setCellStyle(cs_field);

            Cell cell_data_10 = row_temp.createCell(1 + cell_index++);
            cell_data_10.setCellValue(q.getIsClassic());    //++
            cell_data_10.setCellStyle(cs_field);

            Cell cell_data_11 = row_temp.createCell(1 + cell_index++);
            cell_data_11.setCellValue(q.getState());    //++
            cell_data_11.setCellStyle(cs_field);

            Cell cell_data_12 = row_temp.createCell(1 + cell_index++);
            cell_data_12.setCellValue(q.getReviewStatus());    //++
            cell_data_12.setCellStyle(cs_field);
        }

        //创建一个文件对象,作为excel文件内容的输出文件
        File f = new File("test.xlsx");
        //输出时通过流的形式对外输出,包装对应的目标文件
        OutputStream os = new FileOutputStream(f);
        //将内存中的workbook数据写入到流中
        wb.write(os);
        wb.close();
        os.close();
}

1.7 题目报表业务实现

现在后台已经能够生成Excel文件并且填充了数据,但是真实的业务中我们是需要将这个文件下载到客户端

1、修改接口方法getReport,添加返回值

/**
     * 获取包含了数据的流对象
     * @return 包含了报表数据的流对象
     * @throws IOException
     */
ByteArrayOutputStream getReport() throws IOException;

2、在实现类中实现该方法时,将内存中的Excel相关数据写入到ByteArrayOutputStream流中

@Override
public ByteArrayOutputStream getReport() throws IOException {
    
    
    //前面的代码无变动 故省略

    
    /**
    //创建一个文件对象,作为excel文件内容的输出文件
        File f = new File("test.xlsx");
        //输出时通过流的形式对外输出,包装对应的目标文件
        OutputStream os = new FileOutputStream(f);
        //将内存中的workbook数据写入到流中
        wb.write(os);
        wb.close();
        os.close();
    */
    //将内存中的workbook数据写入到流中
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    wb.write(os);
    wb.close();
    return os;
}

3、修改后台servlet的downloadReport方法

private void downloadReport(HttpServletRequest request, HttpServletResponse response) throws IOException {
    
    
    //返回的数据类型为文件xlsx类型
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
    String fileName = new String("测试文件名.xlsx".getBytes(),"iso8859-1");
    response.addHeader("Content-Disposition","attachment;fileName="+fileName);

    //生成报告的文件,然后传递到前端页面
    ByteArrayOutputStream os = questionService.getReport();
    //获取产生响应的流对象
    ServletOutputStream sos = response.getOutputStream();
    //将数据从原始的字节流对象中提取出来写入到servlet对应的输出流中
    os.writeTo(sos);
    //将输出流刷新
    sos.flush();
    os.close();
}

在这里插入图片描述

2.权限系统设计与开发

2.1 权限系统简介与结构设计

RBAC(Role-Based Access Control)是一种权限控制模型,基于角色的访问控制。它将用户和资源分配到不同的角色中,用户只能在其角色所允许的范围内访问资源,从而实现对系统的安全控制。

RBAC模型包括以下四个主要组成部分:

  • 用户:系统中使用资源的人员。
  • 角色:用户的职责或职位。角色是在系统中执行操作的访问控制的基本单元。
  • 权限:操作或任务的权限,如访问文件或运行程序。
  • 资源:系统中需要受保护的对象,如文件、数据库等。

在RBAC模型中,管理员首先定义角色和相关的权限,然后将用户分配到角色中。用户只能访问其所属角色的权限和资源,无法访问其他角色的资源。这种模型可以有效地减少管理工作量和提高系统的安全性。

RBAC模型还可以通过角色继承和用户组来进一步扩展。角色继承允许一个角色继承另一个角色的权限,从而简化了角色的管理。用户组允许将一组用户分配到同一角色中,从而更好地管理用户和角色。

2.2 角色与模块功能快速开发

1、创建角色实体:Role

public class Role {
    
    
    private String id;
    private String name;
    private String remark;
    private Date createTime;
	// getter/setter略
}

2、创建角色Dao:RoleDao

public interface RoleDao {
    
    
    int save(Role role);

    int delete(Role role);

    int update(Role role);

    Role findById(String id);

    List<Role> findAll();
}

3、创建业务层接口:RoleService

public interface RoleService {
    
    
    /**
     * 添加
     * @param role
     * @return
     */
    void save(Role role);

    /**
     * 删除
     * @param role
     * @return
     */
    void delete(Role role);

    /**
     * 修改
     * @param role
     * @return
     */
    void update(Role role);

    /**
     * 查询单个
     * @param id 查询的条件(id)
     * @return 查询的结果,单个对象
     */
    Role findById(String id);

    /**
     * 查询全部的数据
     * @return 全部数据的列表对象
     */
    List<Role> findAll();

    /**
     * 分页查询数据
     * @param page 页码
     * @param size 每页显示的数据总量
     * @return
     */
    PageInfo findAll(int page, int size);
}

4、创建接口的实现:com.itheima.service.system.impl

public class RoleServiceImpl implements RoleService {
    
    
    @Override
    public void save(Role role) {
    
    
        SqlSession sqlSession = null;
        try{
    
    
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            RoleDao roleDao = MapperFactory.getMapper(sqlSession,RoleDao.class);
            //id使用UUID的生成策略来获取
            String id = UUID.randomUUID().toString();
            role.setId(id);
            //3.调用Dao层操作
            roleDao.save(role);
            //4.提交事务
            TransactionUtil.commit(sqlSession);
        }catch (Exception e){
    
    
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        }finally {
    
    
            try {
    
    
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
    }

    @Override
    public void delete(Role role) {
    
    
        SqlSession sqlSession = null;
        try{
    
    
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            RoleDao roleDao = MapperFactory.getMapper(sqlSession,RoleDao.class);
            //3.调用Dao层操作
            roleDao.delete(role);
            //4.提交事务
            TransactionUtil.commit(sqlSession);
        }catch (Exception e){
    
    
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        }finally {
    
    
            try {
    
    
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
    }

    @Override
    public void update(Role role) {
    
    
        SqlSession sqlSession = null;
        try{
    
    
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            RoleDao roleDao = MapperFactory.getMapper(sqlSession,RoleDao.class);
            //3.调用Dao层操作
            roleDao.update(role);
            //4.提交事务
            TransactionUtil.commit(sqlSession);
        }catch (Exception e){
    
    
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        }finally {
    
    
            try {
    
    
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
    }

    @Override
    public Role findById(String id) {
    
    
        SqlSession sqlSession = null;
        try{
    
    
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            RoleDao roleDao = MapperFactory.getMapper(sqlSession,RoleDao.class);
            //3.调用Dao层操作
            return roleDao.findById(id);
        }catch (Exception e){
    
    
            throw new RuntimeException(e);
            //记录日志
        }finally {
    
    
            try {
    
    
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<Role> findAll() {
    
    
        SqlSession sqlSession = null;
        try{
    
    
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            RoleDao roleDao = MapperFactory.getMapper(sqlSession,RoleDao.class);
            //3.调用Dao层操作
            return roleDao.findAll();
        }catch (Exception e){
    
    
            throw new RuntimeException(e);
            //记录日志
        }finally {
    
    
            try {
    
    
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
    }

    @Override
    public PageInfo findAll(int page, int size) {
    
    
        SqlSession sqlSession = null;
        try{
    
    
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            RoleDao roleDao = MapperFactory.getMapper(sqlSession,RoleDao.class);
            //3.调用Dao层操作
            PageHelper.startPage(page,size);
            List<Role> all = roleDao.findAll();
            PageInfo pageInfo = new PageInfo(all);
            return pageInfo;
        }catch (Exception e){
    
    
            throw new RuntimeException(e);
            //记录日志
        }finally {
    
    
            try {
    
    
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
    }
}

5、创建sevlet:RoleServlet

// uri:/system/role?operation=list
@WebServlet("/system/role")
public class RoleServlet extends BaseServlet {
    
    

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        String operation = request.getParameter("operation");
        if("list".equals(operation)){
    
    
            this.list(request,response);
        }else if("toAdd".equals(operation)){
    
    
            this.toAdd(request,response);
        }else if("save".equals(operation)){
    
    
            this.save(request, response);
        }else if("toEdit".equals(operation)){
    
    
            this.toEdit(request,response);
        }else if("edit".equals(operation)){
    
    
            this.edit(request,response);
        }else if("delete".equals(operation)){
    
    
            this.delete(request,response);
        }else if("author".equals(operation)){
    
    
            this.author(request,response);
        }
    }

    private void list(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    
    
        //进入列表页
        //获取数据
        int page = 1;
        int size = 5;
        if(StringUtils.isNotBlank(request.getParameter("page"))){
    
    
            page = Integer.parseInt(request.getParameter("page"));
        }
        if(StringUtils.isNotBlank(request.getParameter("size"))){
    
    
            size = Integer.parseInt(request.getParameter("size"));
        }
        PageInfo all = roleService.findAll(page, size);
        //将数据保存到指定的位置
        request.setAttribute("page",all);
        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/system/role/list.jsp").forward(request,response);
    }

    private void toAdd(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    
    
        //加载所有的部门信息放入到roleList
        List<Role> all = roleService.findAll();
        request.setAttribute("roleList",all);
        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/system/role/add.jsp").forward(request,response);
    }

    private void save(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    
    
        //将数据获取到,封装成一个对象
        Role role = BeanUtil.fillBean(request,Role.class,"yyyy-MM-dd");
        //调用业务层接口save
        roleService.save(role);
        //跳转回到页面list
        response.sendRedirect(request.getContextPath()+"/system/role?operation=list");
    }

    private void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //查询要修改的数据findById
        String id = request.getParameter("id");
        Role role = roleService.findById(id);
        //将数据加载到指定区域,供页面获取
        request.setAttribute("role",role);
        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/system/role/update.jsp").forward(request,response);
    }

    private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
    
    
        //将数据获取到,封装成一个对象
        Role role = BeanUtil.fillBean(request,Role.class,"yyyy-MM-dd");
        //调用业务层接口save
        roleService.update(role);
        //跳转回到页面list
        response.sendRedirect(request.getContextPath()+"/system/role?operation=list");
    }

    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
    
    
        //将数据获取到,封装成一个对象
        Role role = BeanUtil.fillBean(request,Role.class);
        //调用业务层接口save
        roleService.delete(role);
        //跳转回到页面list
        response.sendRedirect(request.getContextPath()+"/system/role?operation=list");
    }

    private void author(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
    
    
        //获取要授权的角色id
        String roleId = request.getParameter("id");
        //使用id查询对应的数据(角色id对应的模块信息)
        Role role = roleService.findById(roleId);
        request.setAttribute("role",role);
        //根据当前的角色id获取所有的模块数据,并加载关系数据
        List<Map> map = moduleService.findAuthorDataByRoleId(roleId);
        //map转成json数据
        ObjectMapper om = new ObjectMapper();
        String json = om.writeValueAsString(map);
        request.setAttribute("roleModuleJson",json);
        // TODO 数据未查询
        //跳转到树页面中
        request.getRequestDispatcher("/WEB-INF/pages/system/role/author.jsp").forward(request,response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request,response);
    }
}

同时需要在BaseServlet中添加RoleService

public class BaseServlet extends HttpServlet {
    
    
    protected CompanyService companyService;
    protected DeptService deptService;
    protected UserService userService;
    protected CourseService courseService;
    protected CatalogService catalogService;
    protected QuestionService questionService;
    protected QuestionItemService questionItemService;
    protected RoleService roleService;

    @Override
    public void init() throws ServletException {
    
    
        companyService = new CompanyServiceImpl();
        deptService = new DeptServiceImpl();
        userService = new UserServiceImpl();
        courseService = new CourseServiceImpl();
        catalogService = new CatalogServiceImpl();
        questionService = new QuestionServiceImpl();
        questionItemService = new QuestionItemServiceImpl();
        roleService = new RoleServiceImpl();
    }
}

在这里插入图片描述

按照相同的方式将模块的相关功能快速开发完成

1、创建模块实体:Module

public class Module {
    
    
    private String id;
    private String parentId;
    private String name;
    private Long ctype;
    private Long state;
    private String curl;
    private String remark;

    private Module module;
	// getter/setter略
}

2、创建模块dao:ModuleDao

public interface ModuleDao {
    
    
    int save(Module module);

    int delete(Module module);

    int update(Module module);

    Module findById(String id);

    List<Module> findAll();
}

3、创建业务层接口:ModuleService

public interface ModuleService {
    
    
    /**
     * 添加
     * @param module
     * @return
     */
    void save(Module module);

    /**
     * 删除
     * @param module
     * @return
     */
    void delete(Module module);

    /**
     * 修改
     * @param module
     * @return
     */
    void update(Module module);

    /**
     * 查询单个
     * @param id 查询的条件(id)
     * @return 查询的结果,单个对象
     */
    Module findById(String id);

    /**
     * 查询全部的数据
     * @return 全部数据的列表对象
     */
    List<Module> findAll();

    /**
     * 分页查询数据
     * @param page 页码
     * @param size 每页显示的数据总量
     * @return
     */
    PageInfo findAll(int page, int size);

}

4、创建业务层实现类:ModuleServiceImpl

public class ModuleServiceImpl implements ModuleService {
    
    
    @Override
    public void save(Module module) {
    
    
        SqlSession sqlSession = null;
        try{
    
    
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            ModuleDao moduleDao = MapperFactory.getMapper(sqlSession,ModuleDao.class);
            //id使用UUID的生成策略来获取
            String id = UUID.randomUUID().toString();
            module.setId(id);
            //3.调用Dao层操作
            moduleDao.save(module);
            //4.提交事务
            TransactionUtil.commit(sqlSession);
        }catch (Exception e){
    
    
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        }finally {
    
    
            try {
    
    
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
    }

    @Override
    public void delete(Module module) {
    
    
        SqlSession sqlSession = null;
        try{
    
    
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            ModuleDao moduleDao = MapperFactory.getMapper(sqlSession,ModuleDao.class);
            //3.调用Dao层操作
            moduleDao.delete(module);
            //4.提交事务
            TransactionUtil.commit(sqlSession);
        }catch (Exception e){
    
    
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        }finally {
    
    
            try {
    
    
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
    }

    @Override
    public void update(Module module) {
    
    
        SqlSession sqlSession = null;
        try{
    
    
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            ModuleDao moduleDao = MapperFactory.getMapper(sqlSession,ModuleDao.class);
            //3.调用Dao层操作
            moduleDao.update(module);
            //4.提交事务
            TransactionUtil.commit(sqlSession);
        }catch (Exception e){
    
    
            TransactionUtil.rollback(sqlSession);
            throw new RuntimeException(e);
            //记录日志
        }finally {
    
    
            try {
    
    
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
    }

    @Override
    public Module findById(String id) {
    
    
        SqlSession sqlSession = null;
        try{
    
    
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            ModuleDao moduleDao = MapperFactory.getMapper(sqlSession,ModuleDao.class);
            //3.调用Dao层操作
            return moduleDao.findById(id);
        }catch (Exception e){
    
    
            throw new RuntimeException(e);
            //记录日志
        }finally {
    
    
            try {
    
    
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
    }

    @Override
    public List<Module> findAll() {
    
    
        SqlSession sqlSession = null;
        try{
    
    
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            ModuleDao moduleDao = MapperFactory.getMapper(sqlSession,ModuleDao.class);
            //3.调用Dao层操作
            return moduleDao.findAll();
        }catch (Exception e){
    
    
            throw new RuntimeException(e);
            //记录日志
        }finally {
    
    
            try {
    
    
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
    }

    @Override
    public PageInfo findAll(int page, int size) {
    
    
        SqlSession sqlSession = null;
        try{
    
    
            //1.获取SqlSession
            sqlSession = MapperFactory.getSqlSession();
            //2.获取Dao
            ModuleDao moduleDao = MapperFactory.getMapper(sqlSession,ModuleDao.class);
            //3.调用Dao层操作
            PageHelper.startPage(page,size);
            List<Module> all = moduleDao.findAll();
            PageInfo pageInfo = new PageInfo(all);
            return pageInfo;
        }catch (Exception e){
    
    
            throw new RuntimeException(e);
            //记录日志
        }finally {
    
    
            try {
    
    
                TransactionUtil.close(sqlSession);
            }catch (Exception e){
    
    
                e.printStackTrace();
            }
        }
    }
}

5、创建servlet:ModuleServlet

// uri:/system/module?operation=list
@WebServlet("/system/module")
public class ModuleServlet extends BaseServlet {
    
    

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        String operation = request.getParameter("operation");
        if("list".equals(operation)){
    
    
            this.list(request,response);
        }else if("toAdd".equals(operation)){
    
    
            this.toAdd(request,response);
        }else if("save".equals(operation)){
    
    
            this.save(request, response);
        }else if("toEdit".equals(operation)){
    
    
            this.toEdit(request,response);
        }else if("edit".equals(operation)){
    
    
            this.edit(request,response);
        }else if("delete".equals(operation)){
    
    
            this.delete(request,response);
        }
    }

    private void list(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    
    
        //进入列表页
        //获取数据
        int page = 1;
        int size = 10;
        if(StringUtils.isNotBlank(request.getParameter("page"))){
    
    
            page = Integer.parseInt(request.getParameter("page"));
        }
        if(StringUtils.isNotBlank(request.getParameter("size"))){
    
    
            size = Integer.parseInt(request.getParameter("size"));
        }
        PageInfo all = moduleService.findAll(page, size);
        //将数据保存到指定的位置
        request.setAttribute("page",all);
        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/system/module/list.jsp").forward(request,response);
    }

    private void toAdd(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    
    
        //加载所有的信息放入到moduleList
        List<Module> all = moduleService.findAll();
        request.setAttribute("moduleList",all);
        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/system/module/add.jsp").forward(request,response);
    }

    private void save(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
    
    
        //将数据获取到,封装成一个对象
        Module module = BeanUtil.fillBean(request,Module.class,"yyyy-MM-dd");
        //调用业务层接口save
        moduleService.save(module);
        //跳转回到页面list
        response.sendRedirect(request.getContextPath()+"/system/module?operation=list");
    }

    private void toEdit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        //查询要修改的数据findById
        String id = request.getParameter("id");
        Module module = moduleService.findById(id);
        //将数据加载到指定区域,供页面获取
        request.setAttribute("module",module);
        //跳转页面
        request.getRequestDispatcher("/WEB-INF/pages/system/module/update.jsp").forward(request,response);
    }

    private void edit(HttpServletRequest request, HttpServletResponse response) throws IOException {
    
    
        //将数据获取到,封装成一个对象
        Module module = BeanUtil.fillBean(request,Module.class,"yyyy-MM-dd");
        //调用业务层接口save
        moduleService.update(module);
        //跳转回到页面list
        response.sendRedirect(request.getContextPath()+"/system/module?operation=list");
    }

    private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
    
    
        //将数据获取到,封装成一个对象
        Module module = BeanUtil.fillBean(request,Module.class);
        //调用业务层接口save
        moduleService.delete(module);
        //跳转回到页面list
        response.sendRedirect(request.getContextPath()+"/system/module?operation=list");
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    
        this.doGet(request,response);
    }
}

同时需要在BserServlet中添加ModuleService

public class BaseServlet extends HttpServlet {
    
    
    protected CompanyService companyService;
    protected DeptService deptService;
    protected UserService userService;
    protected CourseService courseService;
    protected CatalogService catalogService;
    protected QuestionService questionService;
    protected QuestionItemService questionItemService;
    protected RoleService roleService;
    protected ModuleService moduleService;

    @Override
    public void init() throws ServletException {
    
    
        companyService = new CompanyServiceImpl();
        deptService = new DeptServiceImpl();
        userService = new UserServiceImpl();
        courseService = new CourseServiceImpl();
        catalogService = new CatalogServiceImpl();
        questionService = new QuestionServiceImpl();
        questionItemService = new QuestionItemServiceImpl();
        roleService = new RoleServiceImpl();
        moduleService = new ModuleServiceImpl();
    }
}

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/aa2528877987/article/details/129946479