最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

SpringBoot使用過濾器、攔截器和監(jiān)聽器的案例代碼(Springboot搭建java項目)

 更新時間:2023年02月02日 10:54:06   作者:dreamer_0423  
這篇文章主要介紹了SpringBoot使用過濾器、攔截器和監(jiān)聽器(Springboot搭建java項目),本文是基于Springboot搭建java項目,結(jié)合案例代碼給大家介紹的非常詳細(xì),對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

SpringBoot使用過濾器、攔截器和監(jiān)聽器

一、SpringBoot使用過濾器

Spring boot過濾器的使用(兩種方式)

  • 使用spring boot提供的FilterRegistrationBean注冊Filter
  • 使用原生servlet注解定義Filter

兩種方式的本質(zhì)都是一樣的,都是去FilterRegistrationBean注冊自定義Filter

方式一:

第一步:先定義Filter。

import javax.servlet.*;
import java.io.IOException;
public class MyFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        // do something 處理request 或response
        System.out.println("filter1");
        // 調(diào)用filter鏈中的下一個filter
        filterChain.doFilter(servletRequest,servletResponse);
    }
    @Override
    public void destroy() {
    }
}

第二步:注冊自定義Filter

@Configuration
public class FilterConfig {
    @Bean
    public FilterRegistrationBean registrationBean() {
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new MyFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.setOrder(1);//定義過濾器的執(zhí)行先后順序  值越小越先執(zhí)行 不影響B(tài)ean的加載順序
        return filterRegistrationBean;
    }
}

方式二:

// 注入spring容器
@Order(1)//定義過濾器的執(zhí)行先后順序  值越小越先執(zhí)行 不影響B(tài)ean的加載順序
@Component
// 定義filterName 和過濾的url
@WebFilter(filterName = "my2Filter" ,urlPatterns = "/*")
public class My2Filter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("filter2");
    }
    @Override
    public void destroy() {
    }
}

二、SpringBoot使用攔截器

第一步:定義攔截器

public class MyInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}

第二步:配置攔截器

@Configuration
public class InterceptorConfig implements WebMvcConfigurer {
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new MyInterceptor());
    }
}

三、過濾器和攔截器的執(zhí)行順序

過濾器的執(zhí)行順序是安裝@Order注解中的值,或者是setOrder()中值的進(jìn)行執(zhí)行順序排序的,值越小就越靠前。

攔截器則是先聲明的攔截器 preHandle() 方法先執(zhí)行,而postHandle()方法反而會后執(zhí)行。也即是:postHandle() 方法被調(diào)用的順序跟 preHandle() 居然是相反的。如果實際開發(fā)中嚴(yán)格要求執(zhí)行順序,那就需要特別注意這一點。

四、SpringBoot使用監(jiān)聽器

1、統(tǒng)計網(wǎng)站最多在線人數(shù)監(jiān)聽器的例子

/**
 * 上下文監(jiān)聽器,在服務(wù)器啟動時初始化onLineCount和maxOnLineCount兩個變量,
 * 并將其置于服務(wù)器上下文(ServletContext)中,其初始值都是0。
 */
@WebListener
public class InitListener implements ServletContextListener {
    public void contextDestroyed(ServletContextEvent evt) {
    }
    public void contextInitialized(ServletContextEvent evt) {
        evt.getServletContext().setAttribute("onLineCount", 0);
        evt.getServletContext().setAttribute("maxOnLineCount", 0);
    }
}
/**
 * 會話監(jiān)聽器,在用戶會話創(chuàng)建和銷毀的時候根據(jù)情況修改onLineCount和maxOnLineCount的值。
 */
@WebListener
public class MaxCountListener implements HttpSessionListener {
    public void sessionCreated(HttpSessionEvent event) {
        ServletContext ctx = event.getSession().getServletContext();
        int count = Integer.parseInt(ctx.getAttribute("onLineCount").toString());
        count++;
        ctx.setAttribute("onLineCount", count);
        int maxOnLineCount = Integer.parseInt(ctx.getAttribute("maxOnLineCount").toString());
        if (count > maxOnLineCount) {
            ctx.setAttribute("maxOnLineCount", count);
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            ctx.setAttribute("date", df.format(new Date()));
        }
    }
    public void sessionDestroyed(HttpSessionEvent event) {
        ServletContext app = event.getSession().getServletContext();
        int count = Integer.parseInt(app.getAttribute("onLineCount").toString());
        count--;
        app.setAttribute("onLineCount", count);
    }
}

新建一個servlet處理

@WebServlet(name = "SessionServlet",value = "/sessionCount")
public class SessionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        //獲取上下文對象
        ServletContext servletContext = this.getServletContext();
        Integer onLineCount = (Integer) servletContext.getAttribute("onLineCount");
        System.out.println("invoke doGet");
        PrintWriter out = resp.getWriter();
        out.println("<html><body>");
        out.println("<h1>" + onLineCount + "</h1>");
        out.println("</body></html>");
    }
}

2、springboot監(jiān)聽器的使用(以實現(xiàn)異步Event監(jiān)聽為例子)

定義事件類 Event

創(chuàng)建一個類,繼承ApplicationEvent,并重寫構(gòu)造函數(shù)。ApplicationEvent是Spring提供的所有應(yīng)用程序事件擴(kuò)展類。

public class Event extends ApplicationEvent {
    private static final long serialVersionUID = 1L;
    private String msg ;
    private static final Logger logger=LoggerFactory.getLogger(Event.class);
    public Event(String msg) {
        super(msg);
        this.msg = msg;
        logger.info("add event success! message: {}", msg);
    }
    public String getMsg() {
        return msg;
    }
    public void setMsg(String msg) {
        this.msg = msg;
    }
}

創(chuàng)建一個用于監(jiān)聽指定事件的類,需要實現(xiàn)ApplicationListener接口,說明它是一個應(yīng)用程序事件的監(jiān)聽類。注意這里需要加上@Component注解,將其注入Spring容器中。

@Component
public class MyListener implements ApplicationListener<Event>{
    private static final Logger logger= LoggerFactory.getLogger(MyListener.class);
    @Override
    public void onApplicationEvent(Event event) {
        logger.info("listener get event,sleep 2 second...");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        logger.info("event msg is:{}",event.getMsg());
    }
}

事件發(fā)布
事件發(fā)布很簡單,只需要使用Spring 提供的ApplicationEventPublisher來發(fā)布自定義事件

@Autowired 注入ApplicationEventPublisher

@RequestMapping("/notice/{msg}")
    public void notice(@PathVariable String msg){
        logger.info("begin>>>>>");
        applicationEventPublisher.publishEvent(new Event(msg));
        logger.info("end<<<<<<<");
    }

到此這篇關(guān)于SpringBoot使用過濾器、攔截器和監(jiān)聽器(Springboot搭建java項目)的文章就介紹到這了,更多相關(guān)SpringBoot使用過濾器、攔截器和監(jiān)聽器內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • Java多線程中線程的兩種創(chuàng)建方式及比較代碼示例

    Java多線程中線程的兩種創(chuàng)建方式及比較代碼示例

    這篇文章主要介紹了Java多線程中線程的兩種創(chuàng)建方式及比較代碼示例,簡單介紹了線程的概念,并行與并發(fā)等,然后通過實例代碼向大家展示了線程的創(chuàng)建,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • 可視化Swing中JTable控件綁定SQL數(shù)據(jù)源的兩種方法深入解析

    可視化Swing中JTable控件綁定SQL數(shù)據(jù)源的兩種方法深入解析

    以下是對可視化Swing中JTable控件綁定SQL數(shù)據(jù)源的兩種方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友可以過來參考一下
    2013-07-07
  • Java?JWT實現(xiàn)跨域身份驗證方法詳解

    Java?JWT實現(xiàn)跨域身份驗證方法詳解

    JWT(JSON?Web?Token)是目前流行的跨域認(rèn)證解決方案,是一個開放標(biāo)準(zhǔn)(RFC?7519),它定義了一種緊湊的、自包含的方式,用于作為JSON對象在各方之間安全地傳輸信息。本文將介紹JWT如何實現(xiàn)跨域身份驗證,感興趣的可以學(xué)習(xí)一下
    2022-01-01
  • springMVC詳細(xì)介紹

    springMVC詳細(xì)介紹

    下面小編就為大家?guī)硪黄赟pring MVC 詳細(xì)介紹。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2021-07-07
  • spring 定時任務(wù)@Scheduled詳解

    spring 定時任務(wù)@Scheduled詳解

    這篇文章主要介紹了spring 定時任務(wù)@Scheduled的相關(guān)資料,文中通過示例代碼介紹的很詳細(xì),相信對大家的理解和學(xué)習(xí)具有一定的參考借鑒價值,有需要的朋友們下面來一起看看吧。
    2017-01-01
  • Maven?項目用Assembly打包可執(zhí)行jar包的方法

    Maven?項目用Assembly打包可執(zhí)行jar包的方法

    這篇文章主要介紹了Maven?項目用Assembly打包可執(zhí)行jar包的方法,該方法只可打包非spring項目的可執(zhí)行jar包,需要的朋友可以參考下
    2023-03-03
  • Java?方法的重載與參數(shù)傳遞詳解

    Java?方法的重載與參數(shù)傳遞詳解

    在java中,方法就是用來完成解決某件事情或?qū)崿F(xiàn)某個功能的辦法。方法實現(xiàn)的過程中,會包含很多條語句用于完成某些有意義的功能——通常是處理文本,控制輸入或計算數(shù)值,這篇文章我們來探究一下方法的重載與傳參
    2022-04-04
  • SpringBoot整合Redis之編寫RedisConfig

    SpringBoot整合Redis之編寫RedisConfig

    RedisConfig需要對redis提供的兩個Template的序列化配置,所以本文為大家詳細(xì)介紹了SpringBoot整合Redis如何編寫RedisConfig,需要的可以參考下
    2022-06-06
  • 為什么rest接口返回json建議采用下劃線形式,不要用駝峰

    為什么rest接口返回json建議采用下劃線形式,不要用駝峰

    為什么rest接口返回json建議采用下劃線形式,不要用駝峰?今天小編就來為大家說明一下原因,還等什么?一起跟隨小編過來看看吧
    2020-09-09
  • idea mybatis配置log4j打印sql語句的示例

    idea mybatis配置log4j打印sql語句的示例

    本篇文章主要介紹了idea mybatis配置log4j打印sql語句的示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2018-01-01

最新評論

中江县| 白河县| 建瓯市| 嵊泗县| 调兵山市| 丁青县| 道真| 泌阳县| 辉县市| 永顺县| 汤阴县| 庐江县| 聊城市| 南丰县| 方山县| 宽城| 丰台区| 大石桥市| 湟中县| 贵定县| 邹城市| 商丘市| 临夏市| 铜川市| 即墨市| 清水河县| 米泉市| 闽侯县| 锡林浩特市| 樟树市| 凌海市| 象州县| 大安市| 察雅县| 昌黎县| 浦北县| 武夷山市| 肃北| 江油市| 木里| 竹山县|