登录拦截器

最近做了很多的工作,时间久了都忘记了,随手记录一下

这里是一个登录拦截器,我做的比较怪异,按照正常情况下,应该使用权限管理来完成,由于各种问题,一切从简

首先实现HandlerInterceptor,重写里面的方法,设置拦截内容


/**
 * 后台系统身份验证拦截器
 *

 */
@Component
public class AdminLoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        String uri = request.getRequestURI();
        if (uri.startsWith("/admin") && null == request.getSession().getAttribute("admin_name")) {
            request.getSession().setAttribute("errorMsgAdmin", "请重新登陆");
            response.sendRedirect(request.getContextPath() + "/admin/login");
            return false;
        } else {
            request.getSession().removeAttribute("errorMsgAdmin");
            return true;
        }
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }
}

  拦截器配置,继承WebMvcConfigurer类,添加需要拦截的路径和允许访问的路径

/**
 * @program: sunflower
 * @description
 * @author: liyu
 * @create: 2020-03-01 00:16
 **/
/*
 * 文件上传路径映射配置类
 * 登陆拦截配置
 * WebMvcConfigurer 用来配置springmvc中的一些配置信息
 * */
@Configuration//配置类注解
public class WebAppConfig implements WebMvcConfigurer {

    @Autowired
    private AdminLoginInterceptor adminLoginInterceptor;
    @Autowired
    private StudentLoginInterceptor studentLoginInterceptor;
    @Autowired
    private TeacherLoginInterceptor teacherLoginInterceptor;
    public void addInterceptors(InterceptorRegistry registry) {
        // 添加一个拦截器,拦截以/admin为前缀的url路径
        registry.addInterceptor(adminLoginInterceptor).addPathPatterns("/admin/**").excludePathPatterns("/admin/login").excludePathPatterns("/admin/static/**");
        registry.addInterceptor(studentLoginInterceptor).addPathPatterns("/student/**").excludePathPatterns("/student/login").excludePathPatterns("/student/register");
        registry.addInterceptor(teacherLoginInterceptor).addPathPatterns("/teacher/**").excludePathPatterns("/teacher/register").excludePathPatterns("/teacher/login");
    }
    @Value("${uploadpath}")
    private String uploadpath;

    @Value("${vpath}")
    private String vpath;


    //添加资源映射
    /*
     * ResourceHandlers 相当于springmvc配置resource配置项
     * */
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler(vpath + "**")//指定请求URL
                //"file:D:/upload"
                .addResourceLocations("file:" + uploadpath);//指定映射到的资源

    }


}

随手记

你可能感兴趣的:(web,springboot)