springboot学习笔记2(拦截器,redis,授权登录,读取yml配置文件)

Easter79
• 阅读 407

介绍一下springboot的一些自定义配置。自定义配置前,需要加入一些依赖,在学习笔记1中都要介绍

1.使用springboot自定义拦截器。

 首先自己一个拦截器:

public class MyInterceptor implements HandlerInterceptor {

    @Override 
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("interceptor is working now----");
        return true;
    }

    。。。。。省略其它
}

然后创建一个类继承 WebMvcConfigurerAdapter。

@Configuration
public class WebMvcConfigurer extends WebMvcConfigurerAdapter {

    @Override 
        public void addInterceptors(InterceptorRegistry registry) {
       //添加自定义拦截器,设置路径
    registry.addInterceptor(new CustomizeInterceptor()).addPathPatterns("/test/**");
    super.addInterceptors(registry);
    }
}

2.配置redistemplate

在使用redis 保存key会产生 \xac\xed\x00\x05t\x00这样的乱码,这是因为springboot中默认redistemplate使用的序列化key类不是StringRedisSerializer(),需要我们自己配置一下:

public static RedisTemplate<String, String> redisTemplate;

    @Autowired public RedisConfigurer(RedisTemplate redisTemplate) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        this.redisTemplate = redisTemplate;
    }

或者(@Configuration + @Bean  注解组合 等价于 xml配置 )

@Configuration
public class RedisTemplateUtil {

    @Bean
    public RedisTemplate<String, String> getRedisTemplate(
            RedisTemplate redisTemplate) {
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new StringRedisSerializer());
        redisTemplate.setConnectionFactory(getFactory());
        return redisTemplate;
    }
}

    我们配置的redistemplate bean会替换springboot默认创建的redistemplate。 这样直接调用redisTemplate,就会看到可以的乱码问题已经解决。但当我们通过redis-cli查看时,会发现中文value值显示也乱码,通过redis-cli --raw 进入cli,然后查看值就可解决显示问题,该方法值适用于linux系统,windows系统还是会乱码。

3.登陆授权配置:

对于有的web项目,需要用户登录才能授权访问,可以通过以下配置实现用户登录授权:

@EnableWebSecurity public class SecurityConfigurer extends WebSecurityConfigurerAdapter {

    @Override protected void configure(HttpSecurity http) throws Exception {
        //指定路径需要登录权限,对静态资源放行,无需授权即可访问
        http.authorizeRequests().antMatchers("/css/**", "/js/**", "/images/**",
               //请求路径包含order的,都需要去登陆
               "/login").permitAll().antMatchers("/order/**").hasRole(("USER")).and().
                formLogin();//在该处追加.loginPage("/tologin");
        http.csrf().disable();
        //单点登录。如果已经登录,其它登录会使当前登录session失效。进一步操作则需要再次登录
        http.sessionManagement().maximumSessions(1).expiredUrl("/login");
        //        BCryptPasswordEncoder 加密类
        //如果登出,使session无效
        http.logout().invalidateHttpSession(true);
    }

    @Autowired public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication()//全局默认用户
                .withUser("admin").password("admin").roles("USER");
    }

以上配置,会跳转到springboot的默认登陆页面,这种默认页面,缺少样式,不美观。如果需要自定义登陆,只需要Controller写一个处理方法(例如:“/tologin”),然后在在上述类上追加formLogin().loginPage("/tologin”)即可。用户访问的时候,会跳转到自己定义的处理方法。

4.获取配置文件属性:

springboot 提供一个工具类可以加载application.yml中的配置文件,如果要读取application.yml 以下参数:

spring:
    username: user
    password: pass
    role: 
        - admin
        - guest

首先要自定义个一个类,做如下设置。

@Component
@ConfigurationProperties(prefix = "spring")
public class PropertiesConfigurer {


 private String username;

 private String password;

 private List<String> role=new ArrayList<>();

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    public List<String> getRole() {
        return role;
    }
}

然后在使用的地方依赖注入:

@Autowired private PropertiesConfigurer propertiesConfigurer;
   
    public void () {
     
....省略

      String name=  propertiesConfigurer.getUsername();
     
 }
点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Wesley13 Wesley13
2年前
java将前端的json数组字符串转换为列表
记录下在前端通过ajax提交了一个json数组的字符串,在后端如何转换为列表。前端数据转化与请求varcontracts{id:'1',name:'yanggb合同1'},{id:'2',name:'yanggb合同2'},{id:'3',name:'yang
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
KVM调整cpu和内存
一.修改kvm虚拟机的配置1、virsheditcentos7找到“memory”和“vcpu”标签,将<namecentos7</name<uuid2220a6d1a36a4fbb8523e078b3dfe795</uuid
Easter79 Easter79
2年前
Twitter的分布式自增ID算法snowflake (Java版)
概述分布式系统中,有一些需要使用全局唯一ID的场景,这种时候为了防止ID冲突可以使用36位的UUID,但是UUID有一些缺点,首先他相对比较长,另外UUID一般是无序的。有些时候我们希望能使用一种简单一些的ID,并且希望ID能够按照时间有序生成。而twitter的snowflake解决了这种需求,最初Twitter把存储系统从MySQL迁移
Easter79 Easter79
2年前
SpringBoot使用RedisTemplate操作Redis时,key值出现 -xac-xed-x00-x05t-x00-tb
原因分析原因与RedisTemplate源码中的默认序列化方式有关defaultSerializernewJdkSerializationRedisSerializer(classLoader!null?classLoader:this.getClass().getClassLoader()
Stella981 Stella981
2年前
Spring Boot 优雅的配置拦截器方式
其实springboot拦截器的配置方式和springMVC差不多,只有一些小的改变需要注意下就ok了。下面主要介绍两种常用的拦截器:一、基于URL实现的拦截器:publicclassLoginInterceptorextendsHandlerInterceptorAdapter{/
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
Easter79
Easter79
Lv1
今生可爱与温柔,每一样都不能少。
文章
2.8k
粉丝
5
获赞
1.2k