spring-intercepter自定义拦截请求

如果不想将冗长的逻辑处理给到框架内部处理,或者不想使用原生处理,可以试用spring-intercepter进行请求捕捉,然后自定义Filter进行处理。

这样的好处是,整个逻辑看起来很立体,可以满足自己特定的业务需求,摸清了框架内部的套路,再也不是将相应的请求扔到内部,而自己只是写一堆正则表达式就完事了。

在springmvc中定义:

    <!-- 自定义普通用户拦截器 -->
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/**"/>
            <!-- 不需要拦截的请求 -->
            <mvc:exclude-mapping path="/login"/>
            <!-- 自定义Filter -->
            <bean class="org.liao.filter.AutoLoginFilter" />
        </mvc:interceptor>
    </mvc:interceptors>

在自定义Filter中实现HandlerInterceptor,然后重写相关的方法,在preHandle()中编写相应的逻辑代码。

类似:

public class ManageLoginFilter implements HandlerInterceptor {

    @Resource
    private UserService userService;

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

    }

    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object o) throws Exception {

        Cookie[] cookies = request.getCookies();
        int isAuto = -1;
        User temp = new User();

        for (Cookie c:cookies) {
            if (c.getName().equals("autoLoginUser")) {

                temp = userService.findByUserName(c.getValue());
                isAuto = 1;

            }
        }

        System.out.println(isAuto+","+temp.getIsAdmin());
        if (isAuto == -1 || temp.getIsAdmin() != 1) {

            //请用管理员用户重新登录
            //退出到登录页面
            response.sendRedirect(request.getContextPath()+"/login");
            return false;
        }

        for (Cookie c:cookies) {
            if (c.getName().equals("sessionId")) {
                if (!c.getValue().equals(temp.getSessionId())) {
                    //退出到登录页面
                    response.sendRedirect(request.getContextPath()+"/login");
                    return false;
                }
            }
        }
        return true;
    }

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

    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,860评论 18 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 173,018评论 25 708
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,936评论 6 342
  • 什么是Spring Spring是一个开源的Java EE开发框架。Spring框架的核心功能可以应用在任何Jav...
    jemmm阅读 16,543评论 1 133
  • 一直以来的偏见,所持有的看法。突然有一天,有人告诉我都是错的,把真相血淋淋的摆在我面前,才发觉自己多么幼稚可笑,自...
    胖鱼007阅读 160评论 0 1