美文网首页
spring boot中session的使用

spring boot中session的使用

作者: 先生_吕 | 来源:发表于2017-05-27 17:19 被阅读5337次

    springboot中默认session时长是60s,根据业务需求,可以在主程序ApplicationMain.java中配置

    /**
     * Created by Jarno on 16/4/27.
     *
     */
    @Configuration//配置控制
    @ComponentScan(basePackages = {"cn.com.hisee.hdta.configcenter","cn.com.hisee.common"})
    @ImportResource(value = {"classpath:configcenter-dao.xml", "classpath:configcenter-domain.xml"})
    @EnableAutoConfiguration//启用自动配置
    @SpringBootApplication
    public class ApplicationMain extends SpringBootServletInitializer {
    
        private static final Logger logger = LoggerFactory.getLogger(ApplicationMain.class);
    
        @Override
        protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
            return builder.sources(this.getClass());
        }
    
        public static void main(String[] args) throws Exception {
            //启动Spring Boot项目的唯一入口
            SpringApplication.run(ApplicationMain.class, args);
        }
    
    
        /**
         * 编码设置
         * @return
         */
        @Bean
        public FilterRegistrationBean filterRegistrationBean() {
            FilterRegistrationBean registrationBean = new FilterRegistrationBean();
            CharacterEncodingFilter characterEncodingFilter = new CharacterEncodingFilter();
            characterEncodingFilter.setEncoding("UTF-8");
            registrationBean.setFilter(characterEncodingFilter);
            return registrationBean;
        }
    
        /**
         * session时长设置
         * @return
         */
        @Bean
        public EmbeddedServletContainerCustomizer containerCustomizer(){
            return new EmbeddedServletContainerCustomizer() {
                @Override
                public void customize(ConfigurableEmbeddedServletContainer Container) {
    
                    Container.setSessionTimeout(12*60*60);//单位为S
                }
            };
        }
    }
    

    模拟真实业务,一般用户登录后需要把用户id存入session
    以下是实例代码

    【用户session类:UserSession】

    /**
     * Created by mis on 2016/7/27.
     */
    @Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
    @Component
    public class UserSession implements Serializable{
    
        private static final long serialVersionUID = 9120765714832970813L;
        //id
        private Integer userId;
        //账号
        private String username;
        
        //getter  setter 方法
    }
    
    这里注意@Scope注解:
        @Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)这个是说在每次注入的时候回自动创建一个新的bean实例
        @Scope(value=ConfigurableBeanFactory.SCOPE_SINGLETON)单例模式,在整个应用中只能创建一个实例
        @Scope(value=WebApplicationContext.SCOPE_GLOBAL_SESSION)全局session中的一般不常用
        @Scope(value=WebApplicationContext.SCOPE_APPLICATION)在一个web应用中只创建一个实例
        @Scope(value=WebApplicationContext.SCOPE_REQUEST)在一个请求中创建一个实例
        @Scope(value=WebApplicationContext.SCOPE_SESSION)每次创建一个会话中创建一个实例
    里面还有个属性
        proxyMode=ScopedProxyMode.INTERFACES创建一个JDK代理模式
        proxyMode=ScopedProxyMode.TARGET_CLASS基于类的代理模式
        proxyMode=ScopedProxyMode.NO(默认)不进行代理
    

    【业务类userService】

    public class UserService{
    
      /**
         * 用户登录
         * @return
         */
        public CallResult login(){
            String username = userParam.getUsername();
            String password = userParam.getPassword();
    
            //密码数据库对比
            UserInfo userInfo = this.userDomainRepository.findUserInfoByUsername(username);
    
            //将用户session
            this.addSession(userInfo);
    
            System.out.println("username  : "+userInfo.getUsername()+" 登录-----");
    
            return CallResult.success(userInfo.getId());
        }
    
        /**
         * 用户退出
         * @return
         */
        public CallResult exit(){
            userSession.setUsername(null);
            userSession.setUserId(null);
            return CallResult.success();
        }
    
        /**
         * 将登录的用户存入session
         * @param userInfoModel
         */
        public void addSession(UserInfo userInfo){
            userSession.setUserId(userInfo.getId());
            userSession.setUsername(userInfo.getUsername());
        }
    }
    
    

    以上是将用户对象存储在ioc容器中,为session域,以下为获取session(即getBean方式)

    SpringUtil.java

    @Component
    public class SpringUtil implements ApplicationContextAware {
    
        private static ApplicationContext applicationContext = null;
    
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            if(SpringUtil.applicationContext == null){
                SpringUtil.applicationContext  = applicationContext;
            }
        }
        //获取applicationContext
        public static ApplicationContext getApplicationContext() {
            return applicationContext;
        }
        //通过name获取 Bean.
        public static Object getBean(String name){
            return getApplicationContext().getBean(name);
        }
        //通过class获取Bean.
        public static <T> T getBean(Class<T> clazz){
            return getApplicationContext().getBean(clazz);
        }
        //通过name,以及Clazz返回指定的Bean
        public static <T> T getBean(String name,Class<T> clazz){
            return getApplicationContext().getBean(name, clazz);
        }
    }
    

    获取userSession

    //获取session用户
    UserSession userSession = SpringUtil.getBean(UserSession.class);
    
    2017-05-27_171822.png

    相关文章

      网友评论

          本文标题:spring boot中session的使用

          本文链接:https://www.haomeiwen.com/subject/umuqfxtx.html