• springboot:mvc配置原理


    如果想diy一些定制化的功能,只要写个组件,让后将它交给springboot,springboot就将他自动装配了

    1.实现diy视图解析器
    //如果想diy一些定制化的功能,只要写个组件,让后将它交给springboot,springboot就将他自动装配了
    //扩展springmvc dispatchservlet
    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer {
    
        //ViewResovler 实现了视图解析器接口的类,就可以把他看作接口的类,组件,调用diy
        @Bean
        public ViewResolver myViewResolver(){
            return new MyViewResolver();
        }
    
        //实现视图解析器接口类,diy一个视图解析器
        public static class MyViewResolver implements ViewResolver{
    
            @Override
            public View resolveViewName(String s, Locale locale) throws Exception {
                    return null;
            }
        }
    }
     
    2,自定义拦截器,

      实现拦截器之前首先要去WebMvcConfigurer接口去重写addInterceptors方法,作用:去声明要拦截的路径,和过滤掉不拦截的资源(静态资源)

        使用springboot的拦截器首先要实现HandlerInterceptor的实现类,用来配置拦截后的操作(拦截后是要给提示?还是转发页面)


    2.1,WebMvcConfigurer接口实现(增加拦截器)

    @Configuration
    public class MyMvcConfig implements WebMvcConfigurer {
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
    
            registry.addInterceptor(new LoginHandlerInterceptor())
                    //addPathPatterns拦截的请求,//排除的请求
                    .addPathPatterns("/**")
                    .excludePathPatterns("/index.html","/","/user/login","/css/**","/js/**","/img/**");
        }

    2.2,实现拦截器接口

    public class LoginHandlerInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            //登录成功后,应该有用户的session
            Object loginUser = request.getSession().getAttribute("loginUser");
            if (loginUser==null){
                //没有登录
                request.setAttribute("msg","没有权限请先登录");
                request.getRequestDispatcher("/index.html").forward(request,response);
                return false;
            }else {
                return true;
            }
    
        }
    }
  • 相关阅读:
    使用Pandas groupby连接来自多行的字符串
    Pandas数据分析介绍
    SQL Server 32位数据源与64位数据源区别
    SQL Server install
    windows 远程提示CredSSP
    linux 终端下以图形界面打开当前文件夹
    Linux g++ include link
    undefined reference to symbol 'pthread_create@@GLIBC_2.2.5'
    Linux下的库操作工具-nm、ar、ldd、ldconfig和ld.so
    git update
  • 原文地址:https://www.cnblogs.com/CL-King/p/14052726.html
Copyright © 2020-2023  润新知