Github: https://github.com/alibaba/druid
Druid 的验证方式官网提供了一种根据ip来做访问限制的方式,即allow和deny, 详询 https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_StatViewServlet%E9%85%8D%E7%BD%AE
还有一种方式,即用户名和密码,但是此方法官网没有提及,这个方式也是我看了源码后才知道的,现在分享给大家
首先从web.xml中的servlet出发
<servlet>
<servlet-name>DruidStatView</servlet-name>
<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
</servlet>
打开源码StatViewServlet,
public class StatViewServlet extends ResourceSerlvet {
// ....
}
在跟进源码 ResourceSerlvet
然后在看service方法,这里是处理请求的
public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String contextPath = request.getContextPath();
String servletPath = request.getServletPath();
String requestURI = request.getRequestURI();
response.setCharacterEncoding("utf-8");
if (contextPath == null) { // root context
contextPath = "";
}
String uri = contextPath + servletPath;
String path = requestURI.substring(contextPath.length() + servletPath.length());
if (!isPermittedRequest(request)) {
path = "/nopermit.html";
returnResourceFile(path, uri, response);
return;
}
if ("/submitLogin".equals(path)) {
String usernameParam = request.getParameter(PARAM_NAME_USERNAME);
String passwordParam = request.getParameter(PARAM_NAME_PASSWORD);
if (username.equals(usernameParam) && password.equals(passwordParam)) {
request.getSession().setAttribute(SESSION_USER_KEY, username);
response.getWriter().print("success");
} else {
response.getWriter().print("error");
}
return;
}
if (isRequireAuth() //
&& !ContainsUser(request)//
&& !("/login.html".equals(path) //
|| path.startsWith("/css")//
|| path.startsWith("/js") //
|| path.startsWith("/img"))) {
if (contextPath == null || contextPath.equals("") || contextPath.equals("/")) {
response.sendRedirect("/druid/login.html");
} else {
if ("".equals(path)) {
response.sendRedirect("druid/login.html");
} else {
response.sendRedirect("login.html");
}
}
return;
}
if ("".equals(path)) {
if (contextPath == null || contextPath.equals("") || contextPath.equals("/")) {
response.sendRedirect("/druid/index.html");
} else {
response.sendRedirect("druid/index.html");
}
return;
}
if ("/".equals(path)) {
response.sendRedirect("index.html");
return;
}
if (path.indexOf(".json") >= 0) {
String fullUrl = path;
if (request.getQueryString() != null && request.getQueryString().length() > 0) {
fullUrl += "?" + request.getQueryString();
}
response.getWriter().print(process(fullUrl));
return;
}
// find file in resources path
returnResourceFile(path, uri, response);
}
我们注意这2行
if ("/submitLogin".equals(path)) {
if (isRequireAuth() //
从着两行看以看出是校验用的,第一个是登录,第二个是确认是否需要验证权限,再来看方法isRequireAuth
public boolean isRequireAuth() {
return this.username != null;
}
此方法仅有1行判断,即用户名不为空即可
在搜索一下username的赋值
原来在servlet初始化时获取的PARAM_NAME_USERNAME,在到上图即可知道参数是loginUsername
在看看登录代码
综合上面的分析在web.xml中配置servlet的初始化参数loginUsername和loginPassword即可
在访问druid的监控页面,会自动转到login.html
本文地址: http://blog.csdn.net/lanmo555/article/details/40107441