码迷,mamicode.com
首页 > 编程语言 > 详细

spring 中 filter listener servlet 配置

时间:2018-01-06 23:20:01      阅读:223      评论:0      收藏:0      [点我收藏+]

标签:spring   art   图片   实现   res   port   exce   注解   names   

创建 三个类 

分别实现 Filter  ServletContextListener  HttpServlet

在springboot 启动类中@bean加入

技术分享图片

技术分享图片

2 ,实现 ServletContextIntializer接口 

@SpringBootApplication
public class DemoApplication implements ServletContextInitializer{

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
    
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        servletContext.addServlet("customServlet", new CustomServlet()).addMapping("/root");
        servletContext.addFilter("customfilter", new CustomFilter())
                        .addMappingForServletNames(EnumSet.of(DispatcherType.REQUEST), true, "customServlet");
        servletContext.addListener(new CustomListener());
    }
}

3. 注解方式  主类加上@ServletComponentScan     给三个分别加上注解   

@WebServlet(urlPatterns="/index", name="customServlet")
public class CustomServlet extends HttpServlet{
   ....
}

@WebListener
public class CustomListener implements ServletContextListener{
   ....  
}

@WebFilter(urlPatterns="/*")
public class CustomFilter implements Filter{
  ...  
}

 

4.   自定义注解 实现  主类上加上此注解

@Target(value = {ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(value = {FirstFilterConfiguration.class})
public @interface EnableFirstFilter {

}

注册配置的bean(

FirstFilterConfiguration.class

public class FirstFilterConfiguration {

    public static final Integer ORDER = Integer.MIN_VALUE;    
    
    @Bean
    public FilterRegistrationBean firstFilter(){
        FilterRegistrationBean registration = new FilterRegistrationBean();
        registration.setFilter(new FirstFilter());
        registration.addUrlPatterns("/*");
        registration.setName("firstFilter");
        registration.setOrder(ORDER);
        return registration;
    }
}
public class FirstFilter implements Filter {

    @Override
    public void destroy() {
        
    }

    @Override
    public void doFilter(ServletRequest srst, ServletResponse srsp, FilterChain chain)
            throws IOException, ServletException {
        chain.doFilter(srst, srsp);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        
    }

}

 

spring 中 filter listener servlet 配置

标签:spring   art   图片   实现   res   port   exce   注解   names   

原文地址:https://www.cnblogs.com/mxz1994/p/8215393.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!