温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

springboot过滤器和拦截器以及监听器的代码怎么写

发布时间:2021-10-20 15:39:36 来源:亿速云 阅读:139 作者:柒染 栏目:大数据

springboot过滤器和拦截器以及监听器的代码怎么写,相信很多没有经验的人对此束手无策,为此本文总结了问题出现的原因和解决方法,通过这篇文章希望你能解决这个问题。

简单的springboot 过滤器,拦截器,监听器 使用

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>sp</groupId>
  <artifactId>spboot</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0.4.RELEASE</version>
</parent>

<dependencies>
   <!-- 导入Spirng Boot  web 所需的jar包 -->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>
  <!-- 这个插件,可以将应用打包成一个可执行的jar包;-->
<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>
</project>

过滤器,使用的servlet3 规范

package com.soft.m;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@WebFilter(filterName="MyFilter",urlPatterns="/*")
public class MyFilter implements Filter {
    private static Logger LOG = LoggerFactory.getLogger(MyFilter.class);
    public void init(FilterConfig filterConfig) throws ServletException {
        LOG.info("初始化过滤器");
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
          HttpServletRequest req = (HttpServletRequest) request;
            String requestURI = req.getRequestURI();
            LOG.info("过滤到的请求--->"+requestURI);
            chain.doFilter(request, response);
           
    }

    public void destroy() {
        LOG.info("destroy过滤器");
    }
}
监听器 也是servlet 规范 

servletContextListener 监听

package com.soft.m;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

@Component
@WebListener("WebListener")
@ServletComponentScan("com.soft.m")
public class MyListener implements ServletContextListener {
      private static Logger LOG = LoggerFactory.getLogger(MyListener.class);
        public void contextInitialized(ServletContextEvent sce) {
            ;
            LOG.info("init:"+sce.getSource().getClass().toString());        
    }
        public void contextDestroyed(ServletContextEvent sce) {
            // TODO Auto-generated method stub
            LOG.info("contextDestroyed");        
    
        }

 
}
session监听器

package com.soft.m;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@WebListener
public class MySessionListener implements HttpSessionListener {
      private static Logger LOG = LoggerFactory.getLogger(MySessionListener.class);

    public void sessionCreated(HttpSessionEvent se) {
        LOG.info("sessionCreated:"+se.getSession().getId());

    }

    public void sessionDestroyed(HttpSessionEvent se) {
        LOG.info("sessionDestroyed:"+se.getSession().getId());

    }

}
servlet拦截器

package com.soft.m;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class MyInterceptor implements HandlerInterceptor {
    private static Logger logger = LoggerFactory.getLogger(MyFilter.class);
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HandlerMethod m=(HandlerMethod)handler;
        
        logger.info("preHandle:"+ m.getBeanType().toString());
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
            ModelAndView modelAndView) throws Exception {
        // TODO Auto-generated method stub
        logger.info("postHandle");
 
     }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        logger.info("afterCompletion");

    }

}
拦截起配置

package com.soft.m;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MyWebMvcConfigurerAdapter implements  WebMvcConfigurer {

    public void addInterceptors(InterceptorRegistry registry) {
        // TODO Auto-generated method stub
        registry.addInterceptor(new MyInterceptor()).addPathPatterns("/*");
      }

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        //registry.addResourceHandler("/*.ico");
         
    }

}
springboot 启动的类

package com.soft.m;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication 
public class MApplication {
     public static void main(String[] args) {
            SpringApplication.run(MApplication.class, args);
     }
}
controler 类例子

package com.soft.m;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@ResponseBody
public class HelloController {
       @RequestMapping("/hello")
       public String hello(){
           return "HelloController中的hello方法";
       }
       @RequestMapping("/create")
       public String create(HttpServletRequest request){
           request.getSession().setAttribute("aaa", "234");
           return "HelloController中的create方法";
       }
       @RequestMapping("/destory")
       public String destory(HttpServletRequest request){
           request.getSession().invalidate();
           return "HelloController中的destory方法";
       }

}
 

看完上述内容,你们掌握springboot过滤器和拦截器以及监听器的代码怎么写的方法了吗?如果还想学到更多技能或想了解更多相关内容,欢迎关注亿速云行业资讯频道,感谢各位的阅读!

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI