• SpringMVC 拦截器


    类似于Servlet开发中的过滤器Filter,用于对处理器进行预处理和后处理.

    常用场景:

    1、日志记录:记录请求信息的日志,以便进行信息监控、信息统计、计算PV(Page View)等。

    2、权限检查:如登录检测,进入处理器检测检测是否登录,如果没有直接返回到登录页面;

    3、性能监控:有时候系统在某段时间莫名其妙的慢,可以通过拦截器在进入处理器之前记录开始时间,在处理完后记录结束时间,从而得到该请求的处理时间(如果有反向代理,如apache可以自动记录);

    4、通用行为:读取cookie得到用户信息并将用户对象放入请求,从而方便后续流程使用,还有如提取Locale、Theme信息等,只要是多个处理器都需要的即可使用拦截器实现。

    5、OpenSessionInView:如Hibernate,在进入处理器打开Session,在完成后关闭Session。

    …………本质也是AOP(面向切面编程),也就是说符合横切关注点的所有功能都可以放入拦截器实现。

    package org.springframework.web.servlet;
    public interface HandlerInterceptor {
        boolean preHandle(
                HttpServletRequest request, HttpServletResponse response, 
                Object handler) 
                throws Exception;
    
        void postHandle(
                HttpServletRequest request, HttpServletResponse response, 
                Object handler, ModelAndView modelAndView) 
                throws Exception;
    
        void afterCompletion(
                HttpServletRequest request, HttpServletResponse response, 
                Object handler, Exception ex)
                throws Exception;
    }

    preHandle预处理回调方法,实现处理器的预处理(如登录检查),第三个参数为响应的处理器(如我们上一章的Controller实现);

         返回值:true表示继续流程(如调用下一个拦截器或处理器);

                 false表示流程中断(如登录检查失败),不会继续调用其他的拦截器或处理器,此时我们需要通过response来产生响应;

    postHandle后处理回调方法,实现处理器的后处理(但在渲染视图之前),此时我们可以通过modelAndView(模型和视图对象)对模型数据进行处理或对视图进行处理,modelAndView也可能为null。

    afterCompletion整个请求处理完毕回调方法,即在视图渲染完毕时回调,如性能监控中我们可以在此记录结束时间并输出消耗时间,还可以进行一些资源清理,类似于try-catch-finally中的finally,但仅调用处理器执行链中preHandle返回true的拦截器的afterCompletion

    登陆检测Demo:

    处理拦截器,拦截检测除了/login之外所有url是否登陆,未登录都将其跳转到/login

    package com.test.interceptor;
    
    import java.util.List;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    
    public class UserSecurityInterceptor implements HandlerInterceptor{
    
        private List<String> excludedUrls;
        
        @Override
        public void afterCompletion(HttpServletRequest arg0,
                HttpServletResponse arg1, Object arg2, Exception arg3)
                throws Exception {
            // TODO Auto-generated method stub
            
        }
    
        public List<String> getExcludedUrls() {
            return excludedUrls;
        }
    
        public void setExcludedUrls(List<String> excludedUrls) {
            this.excludedUrls = excludedUrls;
        }
    
        @Override
        public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
                Object arg2, ModelAndView arg3) throws Exception {
            // TODO Auto-generated method stub
            
        }
    
        @Override
        public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1,
                Object arg2) throws Exception {
            
            String requestUri = arg0.getRequestURI();
            for (String url : excludedUrls) {
                if (requestUri.endsWith(url)) {
                    return true;
                }
            }
            
            HttpSession session = arg0.getSession();
            if (session.getAttribute("user") == null) {
                System.out.println(arg0.getContextPath());
                arg1.sendRedirect(arg0.getContextPath() + "/login");
            }
            return false;
        }
    
    }
    excludedUrls是要放行的url,在spring配置.此外要注意一些类似jpg,css,js静态文件被拦截的处理
    <?xml version="1.0" encoding="UTF-8"?>
    <beans
    xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.0.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
            
        <!-- 自动扫描的包名 -->
        <context:component-scan base-package="com.test.controller" /> 
        <!-- 默认的注解映射的支持 -->
        <mvc:annotation-driven />
        
        <!-- 配置资源文件,防止被拦截 -->
        <mvc:resources location="/WEB-INF/view/image/" mapping="/image/**"/>  
        <mvc:resources location="/WEB-INF/view/js/" mapping="/js/**"/>  
        <mvc:resources location="/WEB-INF/view/css/" mapping="/css/**"/>
    
        <!-- 拦截器 -->
        <mvc:interceptors>
            <mvc:interceptor>
                <mvc:mapping path="/*" />
                <bean class="com.test.interceptor.UserSecurityInterceptor">
                    <property name="excludedUrls">
                        <list>
                            <value>/login</value>
                        </list>
                    </property>
                </bean>
            </mvc:interceptor>
        </mvc:interceptors>
    
        <!-- 视图解释类 -->
        <bean id="viewResolver"
            class="org.springframework.web.servlet.view.UrlBasedViewResolver">
            <property name="viewClass"
                value="org.springframework.web.servlet.view.JstlView" />
            <property name="prefix" value="/WEB-INF/view/" />
            <property name="suffix" value=".jsp" />
        </bean>
    </beans>
  • 相关阅读:
    【题解】Luogu p2016 战略游戏 (最小点覆盖)
    【模板】Linux下输出文件的对比
    【题解】Luogu P3052 【USACO12】摩天大楼里的奶牛Cows in a Skyscraper
    【题解】滑雪 luogu1434 记忆化搜索
    【题解】Luogu P3110 [USACO14DEC]驮运Piggy Back
    【题解】Luogu P3123 [USACO15OPEN]贝茜说哞Bessie Goes Moo
    【题解】Luogu P2214 [USACO14MAR]哞哞哞Mooo Moo
    【题解】Luogu P2327 [SCOI2005]扫雷
    【题解】Luogu P1011 车站
    【题解】Luogu P2889 [USACO07NOV]挤奶的时间Milking Time
  • 原文地址:https://www.cnblogs.com/lishupeng/p/7343096.html
Copyright © 2020-2023  润新知