036.sprintBoot 登陆& 拦截器

时间:2019-02-16
本文章向大家介绍036.sprintBoot 登陆& 拦截器,主要包括036.sprintBoot 登陆& 拦截器使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

开发时可禁用模板缓存

登陆

开发期间模板引擎页面修改以后,要实时生效

1)、禁用模板引擎的缓存

在application.properties中加入

# 禁用缓存
spring.thymeleaf.cache=false

2)、页面修改完成以后ctrl+f9:重新编译

 

 

登陆错误消息的显示

在登陆页面中加入

<p style="color: red" th:text="${msg}" th:if="${not #strings.isEmpty(msg)}"></p>

拦截器进行登陆检查

拦截器类  LoginHandlerInterceptor  (实现)HandlerInterceptor接口

public class LoginHandlerInterceptor implements HandlerInterceptor {

    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if(user!=null){
            //已经登录
            return true;
        }
        //未经过验证
        request.setAttribute("msg", "没权限请先登录");
        request.getRequestDispatcher("/index.html").forward(request, response);

        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

 

 

 

注册拦截器

是SpringMVC的自动配置吧

配置类  MyMvcConfig  实现  WebMvcConfigurerAdapter (接口)
@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    //所有的webMvcConfigurerAdapter组件会一起起作用
    @Bean //註冊到容器去
    public WebMvcConfigurerAdapter webMvcConfigurerAdapter(){
        WebMvcConfigurerAdapter adapter = new WebMvcConfigurerAdapter() {
            @Override
            public void addViewControllers(ViewControllerRegistry registry) {
                registry.addViewController("/").setViewName("login");
                registry.addViewController("/index.html").setViewName("login");         //将页面输入值进行指定页面显示
                registry.addViewController("/main.html").setViewName("Dashboard");
            }
            //注册拦截器
            @Override
            public void addInterceptors(InterceptorRegistry registry) {
                //静态资源 css js 已经做好了静态资源映射
                registry.addInterceptor(new LoginHandlerInterceptor()).addPathPatterns("/**").
                        excludePathPatterns("/index.html","/","/user/login");
            }
        };
        return adapter;
    }

    @Bean
    public LocaleResolver localeResolver(){
        return new MyLocalResolver();
    }
}