详解Shiro认证流程

2023-10-30

详解Shiro认证流程

通过前面对shiro源码的解读,我们知道,只要我们在拦截器里面配置了所有请求都经过FormAuthenticationFilter,那么我们就不用自己写login方法,shiro会自己帮我们处理登录逻辑。

isAccessAllowed

shiro中的判断一个请求是否允许通过的条件是当前得到的subject是否已经认证过,或者当前请求是否是登录请求。
如何判断Subject是否认证过?

org.apache.shiro.subject.support.DelegatingSubject#isAuthenticated
public boolean isAuthenticated() {
  return authenticated;
 }

接来下依次追寻subject.isAuthenticated的结果:

Subject在如何得到?

org.apache.shiro.SecurityUtils#getSubject

    public static Subject getSubject() {
        Subject subject = ThreadContext.getSubject();
        if (subject == null) {
            subject = (new Subject.Builder()).buildSubject();
            ThreadContext.bind(subject);
        }
        return subject;
    }

从当前线程的上下文中获取,如果没取到就用Builder创建一个,然后把subject绑定到线程上下文。那么取的过程就可以不看了,看下build过程。
org.apache.shiro.subject.Subject.Builder#Builder()

public static class Builder {
	private final SubjectContext subjectContext;
	private final SecurityManager securityManager;
	public Builder() {
		this(SecurityUtils.getSecurityManager());
	}
    public Builder(SecurityManager securityManager) {
       if (securityManager == null) {
           throw new NullPointerException("SecurityManager method argument cannot be null.");
       }
       this.securityManager = securityManager;
       this.subjectContext = newSubjectContextInstance();
       if (this.subjectContext == null) {
           throw new IllegalStateException("Subject instance returned from 'newSubjectContextInstance' " +
                   "cannot be null.");
       }
       this.subjectContext.setSecurityManager(securityManager);
   }
}

org.apache.shiro.subject.Subject.Builder#buildSubject

public Subject buildSubject() {
	return this.securityManager.createSubject(this.subjectContext);
}

shiro中的createSubject的实现只有org.apache.shiro.mgt.DefaultSecurityManager#createSubject(org.apache.shiro.subject.SubjectContext)

    public Subject createSubject(SubjectContext subjectContext) {
        //create a copy so we don't modify the argument's backing map:
        SubjectContext context = copy(subjectContext);

        //ensure that the context has a SecurityManager instance, and if not, add one:
        context = ensureSecurityManager(context);

        //解析关联的session(通常基于引用的session ID),并将其放置在之前的上下文中发送到SubjectFactory。
        //SubjectFactory不需要知道如何获取session作为过程通常是特定于环境的-更好地保护SF不受以下细节的影响:
        context = resolveSession(context);

        //Similarly, the SubjectFactory should not require any concept of RememberMe - translate that here first
        //if possible before handing off to the SubjectFactory:
        context = resolvePrincipals(context);

        Subject subject = doCreateSubject(context);

        //如有必要,请保存此subject以备将来参考:(此处需要此subject,以防rememberMe principals 已解决,
        //并且需要将其存储在session中,因此我们不会在每次操作中不断地对rememberMe PrincipalCollection进行rehydrate)。
        //在1.2中添加的;
        save(subject);

        return subject;
    }

重点看下resolveSession、doCreateSubject和save(subject)三个部分:

resolveSession

org.apache.shiro.mgt.DefaultSecurityManager#resolveSession

    protected SubjectContext resolveSession(SubjectContext context) {
        if (context.resolveSession() != null) {
            log.debug("Context already contains a session.  Returning.");
            return context;
        }
        try {
            //Context couldn't resolve it directly, let's see if we can since we have direct access to 
            //the session manager:
            Session session = resolveContextSession(context);
            if (session != null) {
                context.setSession(session);
            }
        } catch (InvalidSessionException e) {
            log.debug("Resolved SubjectContext context session is invalid.  Ignoring and creating an anonymous " +
                    "(session-less) Subject instance.", e);
        }
        return context;
    }

这里太细了就不贴代码了,大意就是从当前的上下文取session,没取到就通过上下文来生成session,然后设置到上下文中,debug看了下,这个地方的session最开始都是用HttpServletSession包装来的。所以session跟是从客户端拿来的。

doCreateSubject

org.apache.shiro.mgt.DefaultSecurityManager#doCreateSubject

protected Subject doCreateSubject(SubjectContext context) {
   return getSubjectFactory().createSubject(context);
}

org.apache.shiro.web.mgt.DefaultWebSubjectFactory#createSubject

    public Subject createSubject(SubjectContext context) {
        if (!(context instanceof WebSubjectContext)) {
            return super.createSubject(context);
        }
        WebSubjectContext wsc = (WebSubjectContext) context;
        SecurityManager securityManager = wsc.resolveSecurityManager();
        Session session = wsc.resolveSession();
        boolean sessionEnabled = wsc.isSessionCreationEnabled();
        PrincipalCollection principals = wsc.resolvePrincipals();
        boolean authenticated = wsc.resolveAuthenticated();
        String host = wsc.resolveHost();
        ServletRequest request = wsc.resolveServletRequest();
        ServletResponse response = wsc.resolveServletResponse();

        return new WebDelegatingSubject(principals, authenticated, host, session, sessionEnabled,
                request, response, securityManager);
    }

这个地方其实可以看到subject的创建过程也没干什么,就是上下文中获取认证信息,session等相关配置来创建一个委派对象WebDelegatingSubject,所以我们在shiro里面看到的subject都是WebDelegatingSubject。

save(Subject subject)

org.apache.shiro.mgt.DefaultSecurityManager#save

    protected void save(Subject subject) {
        this.subjectDAO.save(subject);
    }

org.apache.shiro.mgt.DefaultSubjectDAO#save

    public Subject save(Subject subject) {
        if (isSessionStorageEnabled(subject)) {
            saveToSession(subject);
        } else {
            log.trace("Session storage of subject state for Subject [{}] has been disabled: identity and " +
                    "authentication state are expected to be initialized on every request or invocation.", subject);
        }

        return subject;
    }

save过程就是把subject里面的Principals和认证状态缓存到session的过程。

isAuthenticated

这里我们回归下主题,我们是想看subject.authenticated 是在什么时候赋值的。所以我们先看看authenticated 的判断:
org.apache.shiro.subject.support.DefaultSubjectContext#resolveAuthenticated

    public boolean resolveAuthenticated() {
        Boolean authc = getTypedValue(AUTHENTICATED, Boolean.class);
        if (authc == null) {
            //see if there is an AuthenticationInfo object.  If so, the very presence of one indicates a successful
            //authentication attempt:
            AuthenticationInfo info = getAuthenticationInfo();
            authc = info != null;
        }
        if (!authc) {
            //fall back to a session check:
            Session session = resolveSession();
            if (session != null) {
                Boolean sessionAuthc = (Boolean) session.getAttribute(AUTHENTICATED_SESSION_KEY);
                authc = sessionAuthc != null && sessionAuthc;
            }
        }

        return authc;
    }

从上下文里面拿的,先从上下文拿AUTHENTICATED,再拿AUTHENTICATION_INFO,如果两个都没有,那就从session里面拿AUTHENTICATED_SESSION_KEY,只要有一个拿到了就算已经认证过了,authenticated的赋值也是这个时候赋值的。

onAccessDenied

isAccessAllowed的结果是false后,就将执行onAccessDenied方法。我们仍然研究FormAuthenticationFilter的onAccessDenied,看他是怎么处理的。

protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
	if (isLoginRequest(request, response)) {
	    if (isLoginSubmission(request, response)) {
	        if (log.isTraceEnabled()) {
	            log.trace("Login submission detected.  Attempting to execute login.");
	        }
	        return executeLogin(request, response);
	    } else {
	        if (log.isTraceEnabled()) {
	            log.trace("Login page view.");
	        }
	        //allow them to see the login page ;)
	        return true;
	    }
	} else {
	    if (log.isTraceEnabled()) {
	        log.trace("Attempting to access a path which requires authentication.  Forwarding to the " +
	                "Authentication url [" + getLoginUrl() + "]");
	    }
	
	    saveRequestAndRedirectToLogin(request, response);
	    return false;
	}
}

很简单,如果是login请求就执行login操作,如果不是就直接重定向到login页面。

执行登录

    protected boolean executeLogin(ServletRequest request, ServletResponse response) throws Exception {
       AuthenticationToken token = createToken(request, response);
       if (token == null) {
           String msg = "createToken method implementation returned null. A valid non-null AuthenticationToken " +
                   "must be created in order to execute a login attempt.";
           throw new IllegalStateException(msg);
       }
       try {
           Subject subject = getSubject(request, response);
           subject.login(token);
           return onLoginSuccess(token, subject, request, response);
       } catch (AuthenticationException e) {
           return onLoginFailure(token, e, request, response);
       }
   }

从org.apache.shiro.web.filter.authc.AuthenticatingFilter#executeLogin的源码来看,shiro的执行登录的过程大致分成下面这4步:

  1. 创建token
  2. 获取subject
  3. subject.login
  4. 登录结果的回调

创建token

    protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
        String username = getUsername(request);
        String password = getPassword(request);
        return createToken(username, password, request, response);
    }
    protected String getUsername(ServletRequest request) {
    	return WebUtils.getCleanParam(request, getUsernameParam());
    }
    protected String getPassword(ServletRequest request) {
     	return WebUtils.getCleanParam(request, getPasswordParam());
    }
    protected AuthenticationToken createToken(String username, String password,
                                           ServletRequest request, ServletResponse response) {
	     boolean rememberMe = isRememberMe(request);
	     String host = getHost(request);
	     return createToken(username, password, rememberMe, host);
    }
    protected AuthenticationToken createToken(String username, String password,
                                            boolean rememberMe, String host) {
      	return new UsernamePasswordToken(username, password, rememberMe, host);
    }

从上面贴出的源码看,shiro通过配置的username和password参数名从request中获取到对应的username和password来构建了一个简单的UsernamePasswordToken。

获取subject

    protected Subject getSubject(ServletRequest request, ServletResponse response) {
        return SecurityUtils.getSubject();
    }
     public static Subject getSubject() {
        Subject subject = ThreadContext.getSubject();
        if (subject == null) {
            subject = (new Subject.Builder()).buildSubject();
            ThreadContext.bind(subject);
        }
        return subject;
    }

可以看到这个时候获取的subject其实在一开始就已经创建好了,这个地方只是从线程的上下文中取出来就好了。

subject.login

    public void login(AuthenticationToken token) throws AuthenticationException {
        clearRunAsIdentitiesInternal();
        Subject subject = securityManager.login(this, token);

        PrincipalCollection principals;

        String host = null;

        if (subject instanceof DelegatingSubject) {
            DelegatingSubject delegating = (DelegatingSubject) subject;
            //we have to do this in case there are assumed identities - we don't want to lose the 'real' principals:
            principals = delegating.principals;
            host = delegating.host;
        } else {
            principals = subject.getPrincipals();
        }

        if (principals == null || principals.isEmpty()) {
            String msg = "Principals returned from securityManager.login( token ) returned a null or " +
                    "empty value.  This value must be non null and populated with one or more elements.";
            throw new IllegalStateException(msg);
        }
        this.principals = principals;
        this.authenticated = true;
        if (token instanceof HostAuthenticationToken) {
            host = ((HostAuthenticationToken) token).getHost();
        }
        if (host != null) {
            this.host = host;
        }
        Session session = subject.getSession(false);
        if (session != null) {
            this.session = decorate(session);
        } else {
            this.session = null;
        }
    }

看下securityManager.login:

    public Subject login(Subject subject, AuthenticationToken token) throws AuthenticationException {
        AuthenticationInfo info;
        try {
            info = authenticate(token);
        } catch (AuthenticationException ae) {
            try {
                onFailedLogin(token, ae, subject);
            } catch (Exception e) {
                if (log.isInfoEnabled()) {
                    log.info("onFailedLogin method threw an " +
                            "exception.  Logging and propagating original AuthenticationException.", e);
                }
            }
            throw ae; //propagate
        }

        Subject loggedIn = createSubject(token, info, subject);

        onSuccessfulLogin(token, info, loggedIn);

        return loggedIn;
    }
      public AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {
        return this.authenticator.authenticate(token);
    }

SecurityManager首先需要从authenticator中去认证token,并且返回一个AuthenticationInfo,所以我们登录的用户凭证校验其实是交个了这个authenticator;
从SecurityManager的构造方法里面可以知道,authenticator是一个ModularRealmAuthenticator实例。

    public AuthenticatingSecurityManager() {
        super();
        this.authenticator = new ModularRealmAuthenticator();
    }

关于ModularRealmAuthenticator这里就不贴代码了。简单描述下就是ModularRealmAuthenticator有一个Realm集合,默认情况下AuthenticationStrategy需要至少一个Realm。
看下authenticator的authenticate(token)实现:
org.apache.shiro.authc.AbstractAuthenticator#authenticate

    public final AuthenticationInfo authenticate(AuthenticationToken token) throws AuthenticationException {

        if (token == null) {
            throw new IllegalArgumentException("Method argument (authentication token) cannot be null.");
        }

        log.trace("Authentication attempt received for token [{}]", token);

        AuthenticationInfo info;
        try {
            info = doAuthenticate(token);
            if (info == null) {
                String msg = "No account information found for authentication token [" + token + "] by this " +
                        "Authenticator instance.  Please check that it is configured correctly.";
                throw new AuthenticationException(msg);
            }
        } catch (Throwable t) {
            AuthenticationException ae = null;
            if (t instanceof AuthenticationException) {
                ae = (AuthenticationException) t;
            }
            if (ae == null) {
                //Exception thrown was not an expected AuthenticationException.  Therefore it is probably a little more
                //severe or unexpected.  So, wrap in an AuthenticationException, log to warn, and propagate:
                String msg = "Authentication failed for token submission [" + token + "].  Possible unexpected " +
                        "error? (Typical or expected login exceptions should extend from AuthenticationException).";
                ae = new AuthenticationException(msg, t);
                if (log.isWarnEnabled())
                    log.warn(msg, t);
            }
            try {
                notifyFailure(token, ae);
            } catch (Throwable t2) {
                if (log.isWarnEnabled()) {
                    String msg = "Unable to send notification for failed authentication attempt - listener error?.  " +
                            "Please check your AuthenticationListener implementation(s).  Logging sending exception " +
                            "and propagating original AuthenticationException instead...";
                    log.warn(msg, t2);
                }
            }


            throw ae;
        }

        log.debug("Authentication successful for token [{}].  Returned account [{}]", token, info);

        notifySuccess(token, info);

        return info;
    }
    protected AuthenticationInfo doAuthenticate(AuthenticationToken authenticationToken) throws AuthenticationException {
        assertRealmsConfigured();
        Collection<Realm> realms = getRealms();
        if (realms.size() == 1) {
            return doSingleRealmAuthentication(realms.iterator().next(), authenticationToken);
        } else {
            return doMultiRealmAuthentication(realms, authenticationToken);
        }
    }
  1. 要求token不能为空
  2. authenticator里面的Realm取出来对token进行认证。
  3. 如果Realm只有一个,那么就直接进行认证即可。否则进行多个Realm的逻辑处理,我们一般情况下都是单个Realm,所以就不过多分析多Realm的情况了。

Realm认证:
org.apache.shiro.realm.AuthenticatingRealm#getAuthenticationInfo

    public final AuthenticationInfo getAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {

        AuthenticationInfo info = getCachedAuthenticationInfo(token);
        if (info == null) {
            //otherwise not cached, perform the lookup:
            info = doGetAuthenticationInfo(token);
            log.debug("Looked up AuthenticationInfo [{}] from doGetAuthenticationInfo", info);
            if (token != null && info != null) {
                cacheAuthenticationInfoIfPossible(token, info);
            }
        } else {
            log.debug("Using cached authentication info [{}] to perform credentials matching.", info);
        }

        if (info != null) {
            assertCredentialsMatch(token, info);
        } else {
            log.debug("No AuthenticationInfo found for submitted AuthenticationToken [{}].  Returning null.", token);
        }

        return info;
    }
     private AuthenticationInfo getCachedAuthenticationInfo(AuthenticationToken token) {
        AuthenticationInfo info = null;

        Cache<Object, AuthenticationInfo> cache = getAvailableAuthenticationCache();
        if (cache != null && token != null) {
            log.trace("Attempting to retrieve the AuthenticationInfo from cache.");
            Object key = getAuthenticationCacheKey(token);
            info = cache.get(key);
            if (info == null) {
                log.trace("No AuthorizationInfo found in cache for key [{}]", key);
            } else {
                log.trace("Found cached AuthorizationInfo for key [{}]", key);
            }
        }

        return info;
    }

首先会从缓存里面获取AuthenticationInfo,如果缓存中没有,就会执行doGetAuthenticationInfo来获取。而这个方法就是我们自己实现realm的时候需要实现的方法。
得到AuthenticationInfo后会进行缓存(如果需要的话,通过org.apache.shiro.realm.AuthenticatingRealm#isAuthenticationCachingEnabled(org.apache.shiro.authc.AuthenticationToken, org.apache.shiro.authc.AuthenticationInfo)控制。)。
得到的AuthenticationInfo还会通过org.apache.shiro.realm.AuthenticatingRealm#assertCredentialsMatch与传进来的token一起进行校验,只有校验通过后才会成功返回。

    protected void assertCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) throws AuthenticationException {
        CredentialsMatcher cm = getCredentialsMatcher();
        if (cm != null) {
            if (!cm.doCredentialsMatch(token, info)) {
                //not successful - throw an exception to indicate this:
                String msg = "Submitted credentials for token [" + token + "] did not match the expected credentials.";
                throw new IncorrectCredentialsException(msg);
            }
        } else {
            throw new AuthenticationException("A CredentialsMatcher must be configured in order to verify " +
                    "credentials during authentication.  If you do not wish for credentials to be examined, you " +
                    "can configure an " + AllowAllCredentialsMatcher.class.getName() + " instance.");
        }
    }

可以看到CredentialsMatcher是配置到Realm中的。

登录后的回调

1.authenticatorh会将登录结果告知各监听者。

SecurityManager会做一些rememberMe的登录成功或失败的回调。同时会用当前的token和info创建一个新的Subject返回。

如果登录成功,subject会记录principals并把authenticated标记为true,如果能获取到session还会对session做部分调整。

最后就是执行org.apache.shiro.web.filter.authc.AuthenticatingFilter的成功和失败回调。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

详解Shiro认证流程 的相关文章

  • 从文本文件中读取阿拉伯字符

    我完成了一个项目 在该项目中我读取了用记事本编写的文本文件 我的文本文件中的字符是阿拉伯语 文件编码类型是UTF 8 当在 Netbeans 7 0 1 中启动我的项目时 一切似乎都正常 但是当我将项目构建为 jar 文件时 字符以这种方式
  • 如何在url请求中发送数组

    我的要求如下 我想给出演员姓名 开始日期 结束日期并获取他在该时期出演的所有电影 因此 我的服务请求是这样的 http localhost 8080 MovieDB GetJson name Actor startDate 20120101
  • Java 卡布局。多张卡中的一个组件

    一个组件 例如JLabel 在多张卡中使用CardLayout 目前看来该组件仅出现在它添加到的最后一张卡上 如果有办法做到这一点 我应该吗 这是不好的做法吗 或者有其他选择吗 你是对的 它只出现在 添加到的最后一张卡 中 但这与CardL
  • 迭代函数可以调用自身吗?

    当观看下面的 MIT 6 001 课程视频时 讲师在 28 00 将此算法标记为迭代 但是 在 30 27 他说这个算法和实际的 递归 算法都是递归的 该函数正在使用基本情况调用自身 那么这次迭代情况如何 private int itera
  • 这个等待通知线程语义的真正目的是什么?

    我刚刚遇到一些代码 它使用等待通知构造通过其其他成员方法与类中定义的线程进行通信 有趣的是 获取锁后 同步范围内的所有线程都会在同一锁上进行定时等待 请参见下面的代码片段 随后 在非同步作用域中 线程执行其关键函数 即 做一些有用的事情1
  • java setFullScreenWindow 在 Mac 中隐藏登录对话框

    我使用的是全屏窗口 类似于屏幕保护程序 使用这里的方法 GraphicsEnvironment getLocalGraphicsEnvironment getDefaultScreenDevice setFullScreenWindow t
  • Java:SortedMap、TreeMap、可比较?如何使用?

    我有一个对象列表 需要根据其中一个字段的属性进行排序 我听说 SortedMap 和 Comparator 是实现此目的的最佳方法 我是否要与正在排序的类实现 Comparable 还是创建一个新类 如何实例化 SortedMap 并传入
  • 具有 JPA 持久性的 Spring 状态机 - 存储库使用

    我试图弄清楚如何轻松使用 Spring 状态机 包括使用 JPA 进行持久化 这是我正在处理的问题 不兼容的数据类型 工厂和持久性 在程序的某个时刻 我想使用连接到用户的状态机 有用于此目的的存储库 项目spring statemachin
  • 生成 equals 和 hashcode 时忽略属性

    假设我有一个类 Customer public class Customer private String firstName private String lastName private String doNotAddMeToEqual
  • 用于层次结构树角色的 Spring Security / Java EE 解决方案

    我知道 Spring Security 非常适合标准角色和基于权限的授权 我不确定的是这种情况 系统中管理着 10 000 名员工 员工被组织成组织结构图 跨部门的谁向谁报告的树 其中一些员工是用户 这些用户仅被允许访问其职责范围内的员工
  • 正确签名的 JNLP 应用程序无法在 Java 7 中运行

    我有一个 JNLP 应用程序 由于证书过期需要更新 我有一个经过 CA 验证的新证书 我已将新证书导入到我的密钥库中 我已导入完整的证书链 我的构建文件对构建中的 jar 进行签名和时间戳
  • 嵌套字段的 Comparator.comparing(...)

    假设我有一个这样的域模型 class Lecture Course course getters class Course Teacher teacher int studentSize getters class Teacher int
  • 如何在不反编译的情况下更改已编译的.class文件?

    我想更改 class 文件方法 我安装 JD Eclipse Decompiler 并打开 class 文件 我添加了一些代码并保存 class 文件 但是 class 文件没有改变 我不知道如何使用反编译器 如果可能的话 如何在不使用反编
  • 如何减去两个 XmlGregorianCalendar 对象来创建一个 Duration 对象?

    我想计算两个时间之间的差值XmlGregorianCalendar对象 从而创建一个Duration object 但我还没有找到执行减法的干净方法 你会怎么做 那应该是 DatatypeFactory newDuration xgc2 t
  • java中使用多线程调用同一类的不同方法

    我有一个类 如下所示 具有三种方法 public class MyRunnable implements Runnable Override public void run what code need to write here to c
  • Android UnityPlayerActivity 操作栏

    我正在构建一个 Android 应用程序 其中包含 Unity 3d 交互体验 我已将 Unity 项目导入 Android Studio 但启动时该 Activity 是全屏的 并且不显示 Android 操作栏 我怎样才能做到这一点 整
  • Collections.sort(list) 和 list.sort(Comparator) 之间的区别

    有什么理由让我应该选择Collections sort list 方法而不是简单地调用list sort 内部Collections sort只是调用sort的方法List无论如何 上课 令人惊讶的是几乎每个人都告诉我使用Collectio
  • Java/MongoDB 按日期查询

    我将一个值作为 java util Date 存储在我的集合中 但是当我查询以获取两个特定日期之间的值时 我最终得到的值超出了范围 这是我的代码 插入 BasicDBObject object new BasicDBObject objec
  • 为什么java.lang.Cloneable不重写java.lang.Object中的clone()方法?

    Java 规范java lang Cloneable接口将自身定义为表示扩展它的任何对象也实现了clone 休眠的方法java lang Object 具体来说 它说 一个类实现了Cloneable接口来指示java lang Object
  • mybatis:使用带有 XML 配置的映射器接口作为全局参数

    我喜欢使用 XML 表示法来指定全局参数 例如连接字符串 我也喜欢 Mapper 注释 当我尝试将两者结合起来时 我得到这个例外 https stackoverflow com questions 4263832 type interfac

随机推荐

  • 解决插入word文档中的图片变得不清晰问题

    打开文件 找到选项 打开高级 找到不压缩图片并勾选 确定并退出
  • saltstack安装

    ubuntu install 1 ppa install sudo add apt repository ppa saltstack salt sudo apt get update sudo apt get install salt ma
  • 字符串替换C++实现

    题目 请实现一个函数 将一个字符串中的每个空格替换成 20 例如 当字符串为We Are Happy 则经过替换之后的字符串为We 20Are 20Happy 思路 给定了字符串 和字符串最大长度 替换空格为 20 找出所有空格 计算新的长
  • vs 自定义 格式化代码快捷键

    vs 自定义 格式化代码快捷键 工具 选项 环境 键盘 编辑 设置选定内容的格式 全局 输入自己想要的快捷键 分配 确定
  • sysdba不能远程登录

    sysdba不能远程登录这个也是一个很常见的问题了 碰到这样的问题我们该如何解决呢 我们用sysdba登录的时候 用来管理我们的数据库实例 特别是有时候 服务器不再本台机器 这个就更是有必要了 当我们用sqlplus as sysdba 是
  • 怎么利用数据库做分布式共享锁

    一 适用环境 1 数据库集群模式 1主多从 2 单机数据库 3 数据库必须提供行级锁功能 二 原理 cas算法 代码 更新当前值为new updateCurrentValue id new old old 通过id 查到的值 new 期望的
  • 变量交换的四种方式

    可以使用以下方法对两个变量进行交换 方法一 定义一个中间量 define CRT SECURE NO WARNINGS include
  • VUE 项目文件夹上传下载解决方案

    原理 js将大文件分成多分 全部上传成功之后 调用合并接口合成文件 如果传输中断 下次上传的时候过滤掉已经上传成功的分片 将剩余的分片上传 成功之后合并文件 前置条件 获取uoloadId接口 用于标记分片 分片上传接口 合成文件接口 后端
  • matplotlib画图间隔范围等设置

    import matplotlib pyplot as plt from matplotlib pyplot import MultipleLocator 从pyplot导入MultipleLocator类 这个类用于设置刻度间隔 x va
  • Burpsuite教程(一)Burpsuite 火狐谷歌浏览器抓包教程

    文章目录 Web抓包 火狐抓包 谷歌抓包 小技巧 结束 Web抓包 火狐抓包 环境需求 火狐浏览器 代理插件 1 打开测试工具BurpSuite 默认工具拦截功能是开启的 颜色较深 我们点击取消拦截 下图取消拦截状态 数据包可以自由通过 2
  • vue3.0中全局注册组件版本1-官方

    前言 在对vue3 0的使用和学习中 发现了很多和以前不一样的方法 这里聊一聊vue3 0中给我们提供的全局的注册组件方法 官方文档 入口 目录 具体方法介绍 1 前提 返回一个提供应用上下文的应用实例 应用实例挂载的整个组件树共享同一个上
  • iOS字典转成JSON换行符问题

    问题 使用系统框架将字典转成压缩转义后的JSON字符串 发现字符串中带有多个换行符 系统转JSON的方法如下 let json try JSONSerialization jsonObject with validData options
  • 嵌入式开发笔记—关于>>和<<、&和&&和指针

    1 gt gt 和 lt lt 符号 gt gt 可以理解为除以2的几次方 例如a gt gt b相当于a除以2 b 相反 符号 lt lt 可以理解为乘2的几次方 上面描述的只是它们的数字意义 实际上 gt gt 为右移运算符 其运算规则
  • 架构师之我见

    架构师是一个项目组的灵魂人物 他决定着整个系统的技术选型 整体架构以及模块划分 同时还可能担当与领导层的沟通角色 从某种意义上来说 架构师在很大程度上决定着项目的成败与否 正所谓火车跑得快 全靠车头带 很多优秀的架构师都是从一个优秀的开发人
  • C模拟C++静态断言

    百度百科 C 11新特性 静态断言 Static assertions Static assert 在解释 if 和 error 之后被处理 简单的说就是检测代码 不可能 事件的发生 如果真的发生了 在编译期间编译器会报错 表示代码的逻辑存
  • vector数组最大、小值及所在坐标

    在普通数组中 例 a 1 2 3 4 5 6 int maxValue max element a a 6 最大值 int minValue min element a a 6 最小值 int maxPosition max element
  • 学创客机器人编程材料费贵吗_创客教育只是学编程、机器人和3D打印?

    创客 Mak er 创 指创造 客 指从事某种活动的人 创客 本指勇于创新 努力将自己的创意变为现实的人 这个词译自英文单词 Mak er 源于美国麻省理工学院微观装配实验室的实验课题 此课题以创新为理念 以客户为中心 以个人设计 个人制造
  • cavans 详解

    Canvas Color Styles Shadows 属性 fillStyle 设置或者返回填充的颜色 渐进色 strokeStyle 设置或者返回描边的颜色 渐进色 shadowColor 设置或者返回shadows的颜色 shadow
  • KEIL MDK中 warning: #223-D: function "xxx" declared implicitly 解决方法

    今天在EINT的范例里添加了一个函数 即eint c中添加了一个datawrite 的函数 并在主函数main c中调用 编译便警告 warning 223 D function datawrite declared implicitly
  • 详解Shiro认证流程

    详解Shiro认证流程 isAccessAllowed Subject在如何得到 resolveSession doCreateSubject save Subject subject isAuthenticated onAccessDen