zoukankan      html  css  js  c++  java
  • SpringBoot入门六(整合之SpringMVC拦截器)

    官网的一段话:

    如果你想要保持Spring Boot的一些默认MVC特征,同时又想自定义一些MVC配置(包括:拦截器,格式化器,
    视图控制器,消息转换器等等),你应该让一个类实现WebMvcConfigurer,并且添加@Configuration注解,但是
    ,千万不要加@EnableWebMvc注解,如果你想要自定义HandlerMapping,HandlerAdapter,ExceptionResolver等组件,
    你可以创建一个WebMvcRegistrationsAdapter实例 来提供以上组件。

    如果你想要完全自定义SpringMVC,不保留SpringBoot提供的一些特征,你可以自定义类并且添加@Configuration注解
    和@EnableWebMvc注解

    步骤:
    1.编写拦截器(在学习MVC时知道要实现HandlerInterceptor接口)接口里面有三个方法(前置后置完成时)

    2.编写配置类实现WebMvcConfigurer,在类中添加各种组件

    3.测试

    =============

    1.编写拦截器

    package com.cc8w.interceptor;
    
    
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    
    public class MyInterceptor implements HandlerInterceptor {
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
            System.out.println("前置...");
            return true;
        }
    
        @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 {
    
        }
    }

    2.编写配置类实现WebMvcConfigurer,在类中添加各种组件

    package com.cc8w.config;
    
    import com.cc8w.interceptor.MyInterceptor;
    import org.springframework.context.annotation.Bean;
    import org.springframework.context.annotation.Configuration;
    import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
    
    @Configuration
    public class MvcConfig implements WebMvcConfigurer {
    
    
        //1.注册拦截器
        @Bean
        public MyInterceptor myInterceptor(){
            return new MyInterceptor();
        }
        //2.添加拦截器到Spring Mvc拦截器链
        @Override
        public void addInterceptors(InterceptorRegistry registry) {
            registry.addInterceptor(myInterceptor()).addPathPatterns("/*");//对所有路径生效
        }
    }

    3.目录或测试

  • 相关阅读:
    PHP设计模式——观察者模式
    TRIZ系列-创新原理-34-抛弃和再生部件原理
    玩转Android Camera开发(三):国内首发---使用GLSurfaceView预览Camera 基础拍照demo
    高速排序算法C++实现
    crm操作报价单实体
    CSS3 网格布局(grid-layout)基础知识
    shadowOffset 具体解释
    [软件人生]关于此次抄袭事件的一个对话
    SpringMVC接收复杂集合对象(参数)代码示例
    Spring MVC同时接收一个对象与List集合对象
  • 原文地址:https://www.cnblogs.com/fps2tao/p/13820881.html
Copyright © 2011-2022 走看看