SpringSecurity 下 Session 使用

spring security的session管理 1 spring security的session管理 spring security关于认证session的逻辑处理在接口SessionAuthenticationStrategy的onAuthentication方法中,先看看这个接口和其实现类。 1.1 SessionAuthenticationStrategy接口 public interface SessionAuthenticationStrategy { /** * 当一个认证生成之后处理sessio 阅读详情

在之前的几章里面,我们分别做了快速入门、自定义表单登录、自定义手机登录。他们有一个共同点,就是目前我们与客户端之间的交互都依赖于 Session。那么本章我们就带大家来了解一下 SpringSecurity 下 Session 的使用与设置。

Session 是什么?

Session 中文意思为会议,在计算机中,尤其在网络应用中称为会话控制。

Session直接翻译成中文比较困难,一般都译成时域。在计算机专业术语中,Session是指一个终端用户与交互系统进行通信的时间间隔,通常指从注册进入系统到注销退出系统之间所经过的时间。以及如果需要的话,可能还有一定的操作空间。

百度百科

为什么要使用 Session?

Http 协议本身是无状态的,多次连接之间的状态无法共享,服务端就判断是否是同一个用户操作的就比较麻烦。

而 Session 就是用来保存状态的,允许通过将对象存储在 Web 服务器内存中,在整个用户会话过程中进行共享。

Session 原理

浏览器第一次访问服务器时,服务端会生成 Session,然后同时为该 Session 生成一个唯一的 SessionId,然后将 SessionId 与 Session 以键值对的形式存储到内存中(Java 默认)。将 SessionId 以 Cookie 的方式返回给浏览器。浏览器下一次访问的时候就携带 SessionId 来访问,这样服务端通过查询就可以取出 Session 达到共享了。

在 SpringSecurity 里面的使用

单机 Session
  • Session 超时设置
    • 设置 Session 超时时间,在系统配置文件(application.properties/yml) 中配置

      server:
        session:
          timeout: 600 #单位为 Second,设置的时间低于 1 分钟,按 1 分钟处理
      
    • 设置 Session 超时/失效后继续访问处理,可以设置跳转页面,也可以设置跳转接口。前后端分离一般返回 Json,不分离可以引导页面跳转。两者都要兼容,可以跳转到自定义接口判断实际请求,进行处理。

      // 设置 Session 失效后访问跳转的页面
      http.sessionManagement().invalidSessionUrl("/session/invalid");
      
  • Session 并发控制
    • Session 最大数设置,限制系统中用户数量

      http.sessionManagement().maximumSessions(1)// 设置同时在线的最大 Session 数
      
    • 设置 Session 数量达到最大值时,是否阻止后面用户登录

      // 设置当 Session 数量达到最大数量时,阻止后面的登录
      http.sessionManagement().maxSessionsPreventsLogin(true);
      
    • 自定义设置 Session 数量达到最大时后续登录的处理策略,默认实现会将前面用户的 Session 置为失效

      // 设置 Session 并发登录时处理策略
      http.sessionManagement().expiredSessionStrategy(new DefaultExpiredSessionStrategy());
      
      /**
       * @author: hblolj
       * @Date: 2019/3/16 9:13
       * @Description: Session 并发登录时的处理策略
       * @Version:
       **/
      public class DefaultExpiredSessionStrategy implements SessionInformationExpiredStrategy{
      
          @Override
          public void onExpiredSessionDetected(SessionInformationExpiredEvent event) throws IOException, ServletException {
              event.getResponse().setCharacterEncoding("UTF-8");
              event.getResponse().getWriter().write("并发登录!");
          }
      }
      
集群 Session(单机 Session 下的设置在集群下一样有效)

在单机 Session 下基本上只要处理好上面的问题就可以了,但是随着系统越来越大,单体应用可能满足不了我们的需求。如果我们对应用进行了集群,那么用户在每个应用上都会产生一个 Session,并且这些 Session 还不是共享的,就达不到 Session 使用的初衷了。

为了让 Session 可以共享,一般我们就会改变 Session 的存储方式,Session 默认存储在内存中,多个主机间就不方便共享。主流处理方案有:

  • 保存在数据库
  • 保存在 Redis 中
  • 利用 Servlet 容器来进行 Session 同步
  • 或者使用 Nginx 使用用户 ip 进行哈希处理,在负载均衡时,让用户每次访问同一个主机避免多 Session 问题

我们这里主要还是讨论 SpringSecurity 下集群 Session 的处理方案,其他扩展信息,大家感兴趣可以自行查询,或者留言讨论。

我们这里示例使用 Redis 作为 Session 存储方式,通过下列配置 Session 就会默认存储在 Redis 中了。关于 SpringBoot 下 Redis 的使用,不了解的可以查询资料使用,上手还是比较简单的。

  • 使用 Redis 作为 Session 的存储,通过配置文件指定存储方式。

    spring:
      session:
        store-type: redis #设置将 Session 存储在 Redis 中
      redis:
        host: redis 所在的主机
        port: 默认是 6379
        database: 选择使用的 database
        password: your self password
        pool:
          max-wait: -1
          max-idle: 1
          max-active: 8
          min-idle: 0
    
  • 添加 Redis 依赖

    <!-- SpringBoot 版本 1.5.19.RELEASE-->
    <dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-data-redis</artifactId>
    </dependency>
    
  • 添加 Spring-Session 依赖

    <!-- SpringBoot 版本 1.5.19.RELEASE-->
    <dependency>
       <groupId>org.springframework.session</groupId>
       <artifactId>spring-session</artifactId>
    </dependency>
    
  • 除了 Redis,SpringBoot 还支持一下存储方式,大家可以自行扩展使用

    public enum StoreType {
        REDIS,
        MONGO,
        JDBC,
        HAZELCAST,
        HASH_MAP,
        NONE;
    
        private StoreType() {
        }
    }
    
退出登录

既然 Session 中共享用户多次请求的状态,那么如果我们要用户登出,就只要清空 Session 即可。那么在 SpringSecurity 下是怎样设置的呢?

  • 如何退出

    • 请求登出地址,默认为 /logout

    • 自定义登出地址

      http.logout().logoutUrl("/quit");// 默认是 logout
      
  • 退出处理原理 (访问退出地址,退出处理逻辑 SpringSecurity 有默认实现)

    • 使当前 Session 失效

      (HttpSession)session.invalidate();
      
    • 清除与当前用户先关的 remember-me 记录

      if (authentication != null) {
          this.tokenRepository.removeUserTokens(authentication.getName());
      }
      
    • 清空当前的 SecurityContext

      if (this.clearAuthentication) {
          SecurityContext context = SecurityContextHolder.getContext();
          context.setAuthentication((Authentication)null);
      }
      
      SecurityContextHolder.clearContext();
      
  • 与退出相关的配置

    • 自定义退出成功跳转页面或处理策略,同时设置只有 logoutSuccessHandler 会生效

      http
      	.logout()
          .logoutSuccessUrl("http://www.baidu.com") // 设置退出成功跳转的页面
          .logoutSuccessHandler(new DefaultLogoutSuccessHandler()) // 设置退出成功的处理策略
      
      /**
       * @author: hblolj
       * @Date: 2019/3/16 10:28
       * @Description:
       * @Version:
       **/
      @Slf4j
      public class DefaultLogoutSuccessHandler implements LogoutSuccessHandler{
      
          @Override
          public void onLogoutSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
      
              log.info("Logout Success!");
          }
      }
      
    • 设置退出时删除客户端 Cookie

      http.logout().deleteCookies("JSESSIONID") // 退出时删除客户端指定的 Cookie
      

OK,到了这里,基本上在 SpringSecurity 里面 Session 的常规设置与使用都介绍完了。大家如果有什么问题,欢迎在下面的留言区留言讨论。

实际上,在现在的开发中,单体 Web 应用可能还是以 Session 为主,但是如果要同时支持 App 的话, Session 就不是那么好用了,因为 Session 依赖 Cookie,虽然 App 访问时可以模拟浏览器设置 Cookie,但是契合度还是不如 Web,所以对于 App 或者集群环境下,现在主流使用基于 OAuth2 的 Token 作为验证。是不是以为我们下一章要讲 SpringSecurity 下 OAuth2 协议的集成与 Token 使用呢?哈哈,下一章我们计划带大家集成一下 SpringSecurity 下第三方登录,比如 QQ 快速登录、微信快速登录等(也依赖于 OAuth 协议)。至于集成 Token 认证还要往后几章哦!

To Be Continue!

SpringSecurity中的集群会话Session存在的问题以及解决方案(保持、复制、共享) 在初步了解Session的时候,我们就知道Session通常是保存在服务器的内存当中的。每一次客户访问都会携带SessionId,然后在服务器的内存中寻找。虽然这种方式简单快捷,但是仍存在比较明显的缺点。服务器的内存是有限的,所以留给Session的空间不多,因此一旦用户的访问量比较多时内存就会捉襟见肘。而且因为session是存在内存当中,并不是持久化存储,就算服务器性能特别好,但是也不免存在服务器的异常停止和重启,这个时候就会导致会话状态的丢失。 阅读详情

相关推荐

Spring Security 6 系列之六 - 会话管理(Session)

我们在本章中了解到Spring Security的Session,并使用Redis实现Session共享。在实际业务中,Session是一种有状态登录,也就是服务器其实会存储Session信息。而现在很多项目都是使用Restful风格的微服务,Restful风格其实强调的是服务的无状态性、前后端分离。因此接下来我们开始了解Spring Security 做前后端分离的一些操作,下一章先从异常处理开始。

代码让AI扣 2128

Spring Security中的会话【Session】管理与防御以及会话的并发控制

众所周知,HTTP本身是没有任何关于当前用户状态的内容,也就是两个HTTP请求之间是没有任何的关联可言,用户在和服务器交互的过程中,站点无法确定是哪个用户访问,也因此不能对其提供相应的个性化服务。Session的诞生就是为了解决这一个难题,提供了无状态的HTTP请求实现用户状态维持的方案——服务器和用户之间约定每个HTTP请求携带一个ID信息【代表当前用户信息】 服务器通过与用户约定每 个请求都携带一个id类的信息,从而让不同请求之间有了关联,而id又可以很方...

SunRains 4955

springSession+springSecurity结合使用实现redis管理session

目录1. pom.xml2. 进行springsession的redis配置3. session配置4. 查看redis5. 获取redis中的当前用户总结 springboot中使用security进行登录及权限控制可以查看之前的文章,springboot中使用spring-security进行登陆控制 此篇主要介绍在已经使用springsecuriy的项目中如何集成springsessi...

nb7474的博客 2万+

Spring Security之Session管理

对于UsernamePasswordAuthenticationFilter而言,SessionManagementFilter有点名不副实,因为前者登录成功后就会自己调用SessionAuthenticationStrategy。因此学习session管理,我们的重点是SessionAuthenticationStrategy。

Evan_L的博客 2966

session在SpringSecurity中如何用——源码分析

登录写入session 在执行登录动作时,在successhandler中,当有流开启对响应头做出修改时就会触发一个onResponseCommit方法,里面调用了HttpSessionSecurityContextRepository.saveContent的方法对session写入或更新 @Override protected void saveContext(SecurityContext...

helloworld_ddd的博客 840

11-SpringSecurity:Session共享

spring-boot-starter-test test 配置文件 server: port: 8000 spring: redis: host: 10.16.1.110 port: 6379 pool.max-idle: 8 pool.min-idle: 0 pool.max-active: 8 pool.max-wait: -1 password: timeout: 1000 资源接口 创建资源接口: 登录之后默认跳转 / ,展示当前服务的端口号。 @RestController publ

m0_66789766的博客 1002

用户登录认证和权限授权(SpringSecurity、JWT、session)

登录认证和权限授权是所有项目中必不可少的功能,本篇文章首先将通过最简单的方式(Session和JWT)实现登录认证和权限授权,然后再整合Springsecurity框架实现。

qq_51076441的博客 1万+

Vercel部署个人博客

先去注册一个账号,建议注册一个Github账号后,使用Github账号来登录Vercel。vercel 部署静态资源网站极其方便简单,并且有可观的访问速度,最主要的是免费部署。此时项目已经成功搭建完毕了,点击图片即可跳转到 vercel 所提供的二级域名访问。然后可以直接拉取我的仓库,所有已经配置好了,可以直接使用,建议fork成自己的!然后修改dns就行,注意vercel提供的域名可能访问不了,需要自己绑定!如果有自己的域名,还可以在 vercel 中进行设置。进入Vercel官网。

醉里博客202271.xyz 2366

【springboot/springsecurity】session超时时间设置

文章目录1 springboot项目session超时时间设置2 springsecurity下如何通知用户session超时2.1 在配置文件BrowserSecurityConfig里加上session超时跳向的url2.2 在配置文件BrowserSecurityConfig里为指定session超时跳向的url授权2.3 写一个controller方法来处理session超时的提示逻辑2....

nrsc 2万+

PSI5协议技术文档与驱动开发指南

• 供电与数据复用:ECU通过双绞线为传感器提供稳压(典型值5V-11V),同时检测线路电流变化实现数据传输。• 同步信号:ECU发送3.5V电压脉冲(上升沿触发传感器响应),用于时序同步。• 安全气囊:PSI5-P模式实现多碰撞传感器同步采样(响应时间<10ms)• CRC-3(3位):ASIL-B以上功能安全要求(如动力总成传感器)• 奇偶校验(1位):适用于低安全等级场景(如PSI5-P10P模式)• 典型应用:PSI5-P(并行总线)、PSI5-U(通用总线)

u012733413的博客 2871

电机控制易混知识点1-基波频率/载波频率/采样频率

在电机控制学习工作中会接触到很多专业名词,其中基波频率,载波频率,采样频率是最常接触到的,特别对于电机控制小白开说,不容易理解,现对这几个概念做下总结归纳。

新能源电机控制工程师 | 聚焦实战问题,搭建互助平台 分享电机控制代码调试、现场故障排查、算法优化中的真实困惑;开放讨论电机基础知识以及工作中遇到难点等共性难题。拒绝单向输出,只做工程师的“技术树洞”与“解忧杂货铺”! 2195

springSecurity结合使用实现redis管理session

1. pom.xml 添加springsession的依赖: <span style="color:#000000"><code><dependency> <groupId>org.springframework.session</groupId> <artifactId>spring-session-data-redis</artifactId> <version>${spring

liberty12345678的专栏 3223

LabVIEW实战:3步搞定Excel模板数据填充(附完整VI源码)

本文提供了一个高效的LabVIEW Excel报表自动化方案,通过使用命名区域定位和动态文件管理,实现数据的精准、动态填充。文章详细阐述了如何构建可复用的数据填充引擎,包括文本、表格数据及图表的写入,并分享了主程序流程、错误处理及性能优化等进阶技巧,帮助工程师彻底摆脱手动操作,提升工作效率。

weixin_29233333的博客 276

SpringSecurity前后端分离的session问题

最近在写一个demo,是前后端分离的,前端通过使用axios来发送异步请求来获取后端的数据,后端使用了SpringSecurity来做系统的鉴权,但发现,SpringSecurity总是拿不到session的问题。 前言: 由于SpringSecurity中,很多东西都是基于session来做的,比如,当用户登录成功后,会创建一个SecurityContextHolder,里面存储了用户认证后的token数据,然后将其存储到session中。 当该用户的后续请求再过...

Mr_FenKuan的博客 3092

从三极管到MOS管:单片机I/O口驱动电路设计实战解析

本文深入解析了从三极管到MOS管的单片机I/O口驱动电路设计实战经验。通过对比三极管与MOS管的本质区别,结合实际案例详细讲解了驱动电路的设计要点、优化技巧及常见问题解决方案,帮助工程师高效完成各类负载驱动设计。

weixin_29161785的博客 322

使用MATLAB实时处理摄像头图像

本文介绍了如何使用MATLAB进行实时图像处理,包括从摄像头获取图像、对图像进行处理并显示处理结果。我们将演示如何使用MATLAB的图像处理工具箱来实现常见的图像处理任务,如图像增强、边缘检测和物体检测。

XsiJava的博客 923

SpringSecurity:session管理

文章目录SpringSecurity:session管理1 Session超时2 限制最大登录数3 踢出用户4 退出登录5 Session 共享 SpringSecurity:session管理 1 Session超时 当用户登录后,我们可以设置 session 的超时时间,当达到超时时间后,自动将用户退出登录。 Session 超时的配置是 SpringBoot 原生支持的,我们只需要在 application.properties 配置文件中配置: server: servlet: sess

拒绝熬夜啊的博客 4775

华为OD机试真题2026双机位C卷 Python&JS 语言 实现【主次关联成环警告】

在ICT运维领域,现网运维工程师面向对设备上报的众多告警,往往需要筛选出最主要的告警优先处理,次等级的告警或许为同一个根因导致的告警,处理优先级会放后或者不处理,这样就诞生出主次关联告警的概念。给定一系列告警的主次关联关系,判断是否存在如下情况:

MISAYAONE的博客 269

SpringSecurity如何管理session

SessionManagementFilter是在用户认证成功后,执行一些session相关的工作,包括防止固定会话攻击,多点登录登自动下线等。用户通过扩展点,能自定义各种策略。下面是SessionManagementFilter的流程图,分为4个子流程:认证通过,执行策略成功,保存SecurityContext,执行下一个Filter认证通过,执行策略失败,执行身份认证失败策略(一般是重定向到登录页面),结束请求。

xsgnzb的专栏 1255

基于Harness Engineering构建AI Agent的全自动化CI_CD流水线

AI Agent的CI/CD是指对Agent的全生命周期资产(代码、Prompt、RAG知识库、模型权重、工具配置)进行持续集成、持续测试、持续发布和持续观测的自动化流程,核心目标是在保障发布质量的前提下,最大化提升Agent的迭代效率。

AI云原生与云计算技术学院 625

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

SpringBoot整合SpringSecurity,SESSION 并发管理,同账号只允许登录一次

SpringBoot整合SpringSecurity,SESSION 并发管理,同账号只允许登录一次   重写了UsernamePasswordAuthenticationFilter,里面继承AbstractAuthenticationProcessingFilter,这个类里面的session认证策略,是一个空方法,貌似RememberMe也是.   publi

codes520的博客 3478

假人有限元模型

假人模型,车辆碰撞假人有限元模型,适合做乘员安全的研究者利用

SpringSecurity2 session超时跳转登陆界面

项目中权限系统使用的是Spring Security2.0,由于对session过期没有过多的支持(Spring Security3.0支持session超时的配置设置),所以只能自己实现。简单的说,也就是通过过滤器拦截请求,判断session是否过期,如果过期跳转登陆界面,否则放行。具体实现如下: 1、web.xml中添加过滤器配置 SessionTimeoutFilter c

Java Dynamic的专栏 5576

复分析 阿尔福斯(Ahlfors) 第三版答案 英文

答案分为十章,有部分习题没有答案,全英文复分析阿尔福斯(Ahlfors) 第三版答案

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

SpringSecurity 配置(登陆验证,session失效等等)

SpringSecurity 配置(登陆验证,session失效等等) 2015年09月28日 15:44:24 iteye_1371 阅读数:9 标签: security 更多 个人分类: spring_security SpringSecurity安全配置—SSH整合 项目中使用了SpringSecurity,将SpringSecurity安全配置整理出来,实现SpringSecurit...

weixin_42858906的博客 5078

《SpringSecurity in Action》一: 基于Session实现登陆认证

SpringSecurity - 基于Session实现登陆认证1 依赖2 代码示例2.1 代码说明 1 依赖 <dependencies> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency>

shangcunshanfu的博客 1693

【SpringSecurity-06】session会话的安全管理

SpringSecurity session会话的安全管理 Spring Security session 创建策略 always: 如果当前请求没有对应的session存在,创建一个session。 ifRequired(默认):在需要使用到session时才创建session。 never:Spring Security将永远不会主动创建session,但是如果session在当前应用中已经存在,它将使用该session。 stateless:Spring Security不会创建或使用任何sessi

weixin_45717355的博客 591

springsecurity扩展session中存放的User对象

springsecurity扩展session中存放的User对象 参考文章 http://www.family168.com/oa/springsecurity/html/ch208-extenduser.html 在原来的mini-web的基础上,参考原来的配置: 这个配置基本上没有改变,只是重新查看了一下UserDetailServiceImpl.java...

快马扬鞭须努力! 612
上一篇: 3. SpringSecurity 自定义手机号登录
下一篇: OAuth2 协议及其四种授权模式
Earth_Programer
博客等级 码龄11年 18粉丝 17原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值