1、前提
在上篇文章中,使用了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>