Druid如何跳过登录
即直接进入/druid/index.html
1.错误做法
很多都是这样配置的,可是并不能跳过登录@WebServlet(urlPatterns = "/druid/*",
initParams={
@WebInitParam(name="allow",value="127.0.0.1"),// IP白名单 (没有配置或者为空,则允许所有访问)
@WebInitParam(name="deny",value=""),// IP黑名单 (存在共同时,deny优先于allow)
@WebInitParam(name="loginUsername",value="root"),// 用户名
@WebInitParam(name="loginPassword",value="root"),// 密码
@WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能
})
public class DruidStatViewServlet extends StatViewServlet {
}
Application.java
@ServletComponentScan
2.正确做法
druid自带的登录时的ajax请求源码 $.namespace("druid.login");
druid.login = function () {
return {
login : function() {
$.ajax({
type: 'POST',
url: "submitLogin",
data: $("#loginForm").serialize(),
success: function(data) {
if("success" == data)
location.href = "index.html";
else {
$("#alertInfo").show();
$("#loginForm")[0].reset();
}
},
dataType: "text"
});
}
}
}();
$(document).ready(function() {
$("#loginBtn").click(druid.login.login);
});
通过源码可以发现 ajax 提交到 submitLogin,返回值是 success 就是登录成功
一般都是用于菜单栏(注意*)1.通常,当我们点击菜单的某一项时,发出请求,请求的是/druid/login.html
2.现在我们需要将菜单点击后发出一个新的请求,例如:/toDruidLogin
3.在IndexController里面拦截请求 /toDruidLogin
code:
@RequestMapping("/toDruidLogin")
public String toDruidLogin(HttpSession session){
if (session.getAttribute("user")!=null){
return "druidlogin";
}
return "redirect:/login";
}
4.新建对应页面,例如druidlogin.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<title>Document</title>
<link rel="stylesheet" th:href="@{/layui/css/layui.css}">
</head>
<body>
<!--jquery.min-->
<script th:src="@{https://code.jquery.com/jquery-3.4.1.min.js}" type="text/javascript"></script>
<script th:src="@{/layui/layui.js}" charset="utf-8"></script>
<script>
layui.use(['layer','element'], function() {
$(function () {
autoLogin();
})
/** 自动登录 @author gaoyuan */
function autoLogin() {
var loadingLayer = layer.load(1, {shade: [0.1, '#fff']});//loading
$.ajax({
type: 'get',
url: '/doDruidLogin',
dataType: "text",
data: {},
success: function (data) {
layer.close(loadingLayer);
if (data == "success") {
location.href = "/druid";
} else {
layer.msg('自动登录出错,请手动登录!', {icon: 2}, function () {
location.href = "/druid";
});
}
}, error: function () {
layer.close(loadingLayer);
}
});
}
});
</script>
</body>
</html>
5.模拟druid的自带的ajax请求,请求 /doDruidLogin
全部代码如上
$.ajax({
type: 'get',
url: '/doDruidLogin',
dataType: "text",
data: {},
success: function (data) {
if (data == "success") {
location.href = "/druid";
}
}
});
6.在IndexController里面拦截请求 /doDruidLogin
此处随意写,过滤后不会执行,但必须要拦截/doDruidLogin,否则会保错
@RequestMapping("/doDruidLogin")
public String doDruidLogin(HttpSession session){
if (session.getAttribute("user")!=null){
return "/";
}
return "redirect:/login";
}
7.最重要一点Filter
@Configuration
@WebFilter(filterName = "moni",urlPatterns = "/doDruidLogin")
public class DruidLoginFilter implements Filter {
private static final Logger log = LoggerFactory.getLogger(DruidLoginFilter.class);
@Override
public void init(FilterConfig filterConfig) throws ServletException {
log.info("DruidLoginFilter初始化");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = ((HttpServletResponse) servletResponse);
String requestUrl = request.getRequestURL().toString();
//log.info(requestUrl);
// 针对druid做自动登录
if(requestUrl.contains("/doDruidLogin")){
String queryString = "loginUsername=root&loginPassword=root";
// 获取完整路径
// log.info("====="+requestUrl);
StringBuffer url = new StringBuffer(requestUrl);
// 获取路径加上项目名称
String tempContextUrl = url.delete(url.length() - request.getRequestURI().length(), url.length()).append(request.getServletContext().getContextPath()).append("/").toString();
// log.info(tempContextUrl);
/** 构造新地址,其实就是druid的登录地址 */
URL newUrl = new URL(tempContextUrl + "druid/submitLogin?" + queryString);
// log.info(newUrl.toString());
response.setStatus(307);
response.setHeader("Location", newUrl.toString());
response.setHeader("Connection", "close");
//允许所有跨域请求
response.addHeader("Access-Control-Allow-Origin", "*");
}else {
chain.doFilter(request,response);
}
}
@Override
public void destroy() {
log.info("DruidLoginFilter销毁");
}
}
doFilter里面判断请求链接是否包含 /doDruidLogin
if(requestUrl.contains("/doDruidLogin")){
//将参数拼接到 一个Url
//状态码307 要求浏览器继续向 Location 的地址 POST 内容。
response.setStatus(307);
response.setHeader("Location", newUrl.toString());
response.setHeader("Connection", "close");
//所以会跳转到 /druid/index.html
}else{
//放行...
chain.doFilter(request,response);
}
3.最后GIF展示
此篇完!