• JAVA应用场景拦截器、过滤器、监听器


    一、mybatis--拦截器--Interceptor

    1、应用场景:对特定SQL语句-赋值权限操作。

    例如:对于有自定义注解权限的查询。做限制

    2、自定义MyDataInterceptor 实现Interceptor接口

    3、添加@Intercepts注解。标识该类为拦截类。

    4、自定义注解

    5、代码

           原理:利用反射得到类和注解。给符合特定注解的方法。修改原SQL。构建新SQL

    1. @Intercepts({@Signature(type = Executor.class, method = "query", args = {MappedStatement.class, Object.class, RowBounds.class, ResultHandler.class})})
    2. public class MyDataInterceptor implements Interceptor {
    3. public Object intercept(Invocation invocation) throws Throwable {
    4. Object[] args = invocation.getArgs();
    5. MappedStatement statement = (MappedStatement) args[0];
    6. System.out.println("进入拦截");
    7. Method method = invocation.getMethod();
    8. System.out.println("方法为" + method.getName());
    9. String id = statement.getId();
    10. String substring = id.substring(0, id.lastIndexOf("."));
    11. String substring1 = id.substring(id.lastIndexOf(".") + 1);
    12. Class<?> aClass = Class.forName(substring);
    13. boolean flag = false;
    14. Method[] declaredMethods = aClass.getDeclaredMethods();
    15. String myAnnotation = null;
    16. for (Method declaredMethod : declaredMethods) {
    17. Annotation[] declaredAnnotations = declaredMethod.getDeclaredAnnotations();
    18. for (Annotation declaredAnnotation : declaredAnnotations) {
    19. System.out.println(declaredAnnotation.annotationType().getTypeName());
    20. //TODO 可以做到数据库配置。也可以写枚举类
    21. if ("com.mybatisplus.config.MyAnnotation".equals(declaredAnnotation.annotationType().getTypeName())) {
    22. MyAnnotation annotation = declaredMethod.getAnnotation(MyAnnotation.class);
    23. StatusEnum[] statusEnums = annotation.value();
    24. for (StatusEnum statusEnum : statusEnums) {
    25. System.out.println(statusEnum.getAce());
    26. }
    27. flag = true;
    28. }
    29. System.out.println("注解为" + declaredAnnotation.annotationType().getSimpleName());
    30. myAnnotation = declaredAnnotation.annotationType().getSimpleName();
    31. }
    32. }
    33. Annotation[] annotations = method.getDeclaredAnnotations();
    34. //MyAnnotation myAnnotation = method.getAnnotation(MyAnnotation.class);
    35. ParameterMap parameterMap = statement.getParameterMap();
    36. SqlSource sqlSource = statement.getSqlSource();
    37. BoundSql boundSql = statement.getBoundSql(args[1]);
    38. String sql = boundSql.getSql();
    39. if (flag) {
    40. sql = sql + " and 1=0";
    41. } else {
    42. return invocation.proceed();
    43. }
    44. BoundSql boundSqlnew = new BoundSql(statement.getConfiguration(), sql, boundSql.getParameterMappings(), boundSql.getParameterObject());
    45. BoundSqlSqlSource source = new BoundSqlSqlSource(boundSqlnew);
    46. MappedStatement statement1 = newMappedStatement(statement, source);
    47. Object[] queryArgs = invocation.getArgs();
    48. queryArgs[0] = statement1;
    49. Object target = invocation.getTarget();
    50. return invocation.proceed();
    51. }
    52. /**
    53. * 定义一个内部辅助类,作用是包装 SQL
    54. */
    55. static class BoundSqlSqlSource implements SqlSource {
    56. private final BoundSql boundSql;
    57. public BoundSqlSqlSource(BoundSql boundSql) {
    58. this.boundSql = boundSql;
    59. }
    60. @Override
    61. public BoundSql getBoundSql(Object parameterObject) {
    62. return boundSql;
    63. }
    64. }
    65. private static MappedStatement newMappedStatement(MappedStatement ms, SqlSource newSqlSource) {
    66. /**
    67. * Configuration configuration, String id, SqlSource sqlSource, SqlCommandType sqlCommandType
    68. */
    69. MappedStatement.Builder mst = new MappedStatement.Builder(ms.getConfiguration(), ms.getId(), newSqlSource, ms.getSqlCommandType());
    70. mst.resource(ms.getResource());
    71. mst.fetchSize(ms.getFetchSize());
    72. mst.statementType(ms.getStatementType());
    73. mst.keyGenerator(ms.getKeyGenerator());
    74. if (ms.getKeyProperties() != null && ms.getKeyProperties().length > 0) {
    75. mst.keyProperty(ms.getKeyProperties()[0]);
    76. }
    77. mst.timeout(ms.getTimeout());
    78. mst.parameterMap(ms.getParameterMap());
    79. mst.resultMaps(ms.getResultMaps());
    80. mst.resultSetType(ms.getResultSetType());
    81. mst.cache(ms.getCache());
    82. mst.flushCacheRequired(ms.isFlushCacheRequired());
    83. mst.useCache(ms.isUseCache());
    84. return mst.build();
    85. }
    86. //DbType.MYSQL
    87. }

    二、webMvc拦截器

    1、应用场景登录拦截或者访问拦截。

    2、自定义拦截类MyHandlerInterceptor实现HandlerInterceptor接口

    3、自定义mvc配置类MyMvcConfig(添加@Configuration)实现WebMvcConfigurer接口。并实现

    addInterceptors方法

    4、代码:

          原理:还是对原生的HttpServletRequest,HttpServletResponse进行处理

    1. @Component
    2. public class MyHandlerInterceptor implements HandlerInterceptor {
    3. /**
    4. * 前置处理器
    5. * @param request
    6. * @param response
    7. * @param handler
    8. * @return
    9. * @throws Exception
    10. */
    11. @Override
    12. public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    13. System.out.println("我是前置处理器");
    14. return true;
    15. }
    16. /**
    17. * 执行器
    18. * @param request
    19. * @param response
    20. * @param handler
    21. * @param modelAndView
    22. * @throws Exception
    23. */
    24. @Override
    25. public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
    26. System.out.println("我是业务后置处理器");
    27. }
    28. /**
    29. * 后置处理器
    30. * @param request
    31. * @param response
    32. * @param handler
    33. * @param ex
    34. * @throws Exception
    35. */
    36. @Override
    37. public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
    38. System.out.println("我是后置处理器");
    39. }
    40. }
    1. @Configuration
    2. public class MyMvcConfig implements WebMvcConfigurer {
    3. @Resource
    4. private MyHandlerInterceptor interceptor;
    5. /**
    6. * 添加自定义拦截器
    7. * @param registry
    8. */
    9. @Override
    10. public void addInterceptors(InterceptorRegistry registry) {
    11. System.out.println("拦截所有");
    12. registry.addInterceptor(interceptor).addPathPatterns("/*");
    13. }
    14. }

    三、过滤器

  • 相关阅读:
    629. K个逆序对数组
    如何用windows上架ios到苹果商城
    centos编译安装opencv,生成opencv-2413.jar
    EtherCAT主站IgH解析(二)-- 如何将Igh移植到Linux/Windows/RTOS等多操作系统
    【软件测试毕业设计】网上订餐系统_自动化测试程序代码及报告
    SBT安装与配置
    用同一棵红黑树实现map和set【STL】
    MyBatis-Plus-扩展操作(3)
    Breakpad Windows 集成概述
    金融数智转型如何利用图谱迈出关键一步?创邻携手普适大咖为您解答
  • 原文地址:https://blog.csdn.net/CB_Beginner/article/details/125386026