SpringBoot中实现Druid前端监控界面自动登录 改进版

1、前提

SpringBoot中实现Druid前端监控界面自动登录

在上篇文章中,使用了WebFilter来实现的Druid自动登录,其实也不需要用到Filter,因为自动登录的原理是获取到HttpServletRequest填入账号密码并进行转发,这个工作在Controller中也可以完成。

2、实现方法

(1)项目中使用到的依赖版本

  • Druid版本1.2.23
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.2.23</version>
</dependency>

Spring Boot版本为2.7.18,此文章适用于Spring Boot为2的版本,适用于Spring Security。

(2)实现原理

见上一篇文章 SpringBoot中实现Druid前端监控界面自动登录

(3)具体代码

  • 添加一个代理登录路径,必须允许POST方法,这里允许了全部的方法。
/**
 * Druid自动登录
 */
@RequestMapping("/loginDruid")
public void loginDruid(HttpServletRequest request, HttpServletResponse response) {
    Map<String, String[]> parameterMap = request.getParameterMap();
    if (parameterMap instanceof org.apache.catalina.util.ParameterMap) {
        try {
        	// 使用反射,允许修改ParameterMap
            Field field = ParameterMap.class.getDeclaredField("locked");
            field.setAccessible(true);
            field.setBoolean(parameterMap, false);
            // 从配置文件中获取到账号密码,填入
            parameterMap.put("loginUsername", new String[]{druidStatProperties.getStatViewServlet().getLoginUsername()});
            parameterMap.put("loginPassword", new String[]{druidStatProperties.getStatViewServlet().getLoginPassword()});
            field.setBoolean(parameterMap, true);
            // 转发到实际的Druid登录地址
            request.getRequestDispatcher("/druid/submitLogin").forward(request, response);
        } catch (NoSuchFieldException | IllegalAccessException | ServletException | IOException e) {
            throw new RuntimeException(e);
        }
    }
}
  • 配置文件,部分配置,请按需使用
spring:
  datasource:
    druid:
      webStatFilter:
        enabled: true
      statViewServlet:
        enabled: true
        allow:
        # 访问路径,按下面的填
        url-pattern: /druid/*
        # 控制台管理用户名和密码,无所谓,因为从后端取,随机字符串即可
        login-username: BvcLixhs
        login-password: dcqMZCWhnGZrnPhiKRYp
  • 前端代码

仅展示Vue3的版本,其他版本一致,需要先请求代理方法后,再来到Druid首页。

<script setup>
import request from '@/utils/request'

const url = ref('')

// 必须使用POST方法,因为要转发给Druid,Druid的登录方法为POST
request.post('/loginDruid', {
  // 参数无所谓,但必须要有,没有参数后端会找不到parameterMap
  ignore: 1
}).then(() => {
  url.value = import.meta.env.VITE_API_BASE_SERVER + '/druid/index.html'
})
</script>

<template>
  <div style="width: 100%;height: 100%;">
    <iframe 
      :src="url" 
      frameborder="no" 
      style="width: 100%; height: 100%" 
      scrolling="auto" />
  </div>
</template>

3、效果展示

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值