资讯专栏INFORMATION COLUMN

Spring Boot之 Servlet、Fiter、Listener的使用

Simon_Zhou / 816人阅读

摘要:生长速度越快的树木,其致密度就越低,生命往往也越短暂而松树柏树胡杨等树种,要上百年才能成材,用起来却可千年不朽。

Spring Boot之 Servlet、Fiter、Listener的使用

新建项目:http://start.spring.io/

Servlet的使用

新建MyServlet类

package com.adagio.chat.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(
        name = "myservlet",
        urlPatterns = {"/myservlet1", "/myservlet2"}
)
public class MyServlet extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
        
        Writer writer = response.getWriter();
        writer.write("Hello World");
    }
}

启动类添加注解 @ServletComponentScan(basePackages = {"com.adagio.chat.servlet"})

启动运行访问:http://localhost:8080/myservlet1和http://localhost:8080/myservlet2

servlet的使用很简单:

添加注解 @WebServlet

配置name,可以不用配置

配置路径,urlPatterns 可以配置多值

Filter的使用

使用方式和Servlet十分类似

package com.adagio.chat.servlet;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.filter.OncePerRequestFilter;

//@WebFilter(servletNames = "myservlet")
@WebFilter(urlPatterns = "/myservlet1")
public class MyFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        ServletContext servletContext = getServletContext();
        servletContext.log("url myservlet was filter");
        
        filterChain.doFilter(request, response);
    }

}

可以直接使用servletNames过滤,如@WebFilter(servletNames = "myservlet"),访问http://localhost:8080/myservlet1和http://localhost:8080/myservlet2都会在控制台打印日志

也可以使用@WebFilter(urlPatterns = "/myservlet1"),访问上面两个链接,只有访问http://localhost:8080/myservlet1这个地址才会打印日志

Listener的使用

使用方式也是类似的

package com.adagio.chat.servlet;

import javax.servlet.ServletContext;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpServletRequest;

@WebListener
public class MyListener implements ServletRequestListener {

    @Override
    public void requestDestroyed(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest)sre.getServletRequest();
        
        ServletContext servletContext = request.getServletContext();
        servletContext.log("request was destroyed");
    }

    @Override
    public void requestInitialized(ServletRequestEvent sre) {
        HttpServletRequest request = (HttpServletRequest)sre.getServletRequest();
        
        ServletContext servletContext = request.getServletContext();
        servletContext.log("request was initialized");
    }

}

访问http://localhost:8080/myservlet2 观察控制台

执行顺序
2017-09-10 16:11:18.247  INFO 7692 --- [io-8080-exec-10] o.a.c.c.C.[Tomcat].[localhost].[/]       : request was initialized
2017-09-10 16:11:18.271  INFO 7692 --- [io-8080-exec-10] o.a.c.c.C.[Tomcat].[localhost].[/]       : url myservlet was filter
2017-09-10 16:11:18.271  INFO 7692 --- [io-8080-exec-10] o.a.c.c.C.[Tomcat].[localhost].[/]       : servlet was doGet
2017-09-10 16:11:18.275  INFO 7692 --- [io-8080-exec-10] o.a.c.c.C.[Tomcat].[localhost].[/]       : request was destroyed

先监听器的初始化,再经过滤器,然后执行doGet方法,最后执行监听器的消亡

使用注入的方式注册

效果和上面的方式一样的,具体实现见代码

package com.adagio.chat.spring.boot;

import java.io.IOException;

import javax.servlet.FilterChain;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.filter.OncePerRequestFilter;

public class MyFilter2 extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
//        ServletContext servletContext = getServletContext();
//        
//        //动态获取URI
//        String requestURI = request.getRequestURI();
//        
//        servletContext.log("url "+requestURI+" was filter from MyFilter2");
        
        doSomething();
        filterChain.doFilter(request, response);
    }
    
    /**
     * 当没有request的时候,可以使用这种方式获取request
     */
    public void doSomething(){
        
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)requestAttributes;
        
        HttpServletRequest request = servletRequestAttributes.getRequest();
        ServletContext servletContext = getServletContext();
        
        //动态获取URI
        String requestURI = request.getRequestURI();
        
        servletContext.log("url "+requestURI+" was filter from MyFilter2");
        
    }

}
package com.adagio.chat.spring.boot;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class MyServlet2 extends HttpServlet {

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException{
        
        ServletContext servletContext = request.getServletContext();
        servletContext.log("servlet2 was doGet");
        
        Writer writer = response.getWriter();
        writer.write("Hello World From MyServlet2");
    }
}
package com.adagio.chat;

import javax.servlet.DispatcherType;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;

import com.adagio.chat.servlet.MyListener;
import com.adagio.chat.spring.boot.MyFilter2;
import com.adagio.chat.spring.boot.MyServlet2;

@SpringBootApplication
@ServletComponentScan(basePackages = {"com.adagio.chat.servlet"})
public class ChatApplication {

    public static void main(String[] args) {
        SpringApplication.run(ChatApplication.class, args);
    }
    
    @Bean
    public static ServletRegistrationBean servletRegistrationBean(){
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        
        servletRegistrationBean.setServlet(new MyServlet2());
        servletRegistrationBean.addUrlMappings("/spring/boot/myservelt2");
        servletRegistrationBean.setName("myservlet2");
        
        return servletRegistrationBean;
    }
    
    @Bean
    public static FilterRegistrationBean filterRegistrationBean(){
        FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean();
        
        filterRegistrationBean.setFilter(new MyFilter2());
//        filterRegistrationBean.addUrlPatterns("/spring/boot/myservelt2");
        filterRegistrationBean.addServletNames("myservlet2");
        filterRegistrationBean.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD, DispatcherType.INCLUDE);
        
        return filterRegistrationBean;
    }
    
    /**
     * 监听器会监听所有请求
     * 可以重复注册监听器
     * @return
     */
    @Bean
    public static ServletListenerRegistrationBean servletListenerRegistrationBean(){
        ServletListenerRegistrationBean servletListenerRegistrationBean = new ServletListenerRegistrationBean<>(new MyListener());
        return servletListenerRegistrationBean;
    }
    
}

急事慢做:成长是长时间努力、积累和进步的结果,是水到渠成的事情,绝不是心急就能做到的。
生长速度越快的树木,其致密度就越低,生命往往也越短暂;而松树、柏树、胡杨等树种,要上百年才能成材,用起来却可千年不朽。 - 俞敏洪

文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

转载请注明本文地址:https://www.ucloud.cn/yun/70385.html

相关文章

  • 【图片抓取】003-JAVA WEB(上)

    摘要:图片抓取上本项目主要讲述项目的搭建和启动过程,为以后继续图片抓取的业务展示做基础。用于处理请求和响应的拦截处理。这样相比容器直接发到处理,大大减少了代码重复工作而且方便统一管理。上下文关系从上图可以看出主要在和两部分做工作。 【图片抓取】003-JAVA WEB(上) 本项目主要讲述java web项目的搭建和启动过程,为以后继续图片抓取的业务展示做基础。项目中采用tomcat+spr...

    jiekechoo 评论0 收藏0
  • 第二十七章:SpringBoot使用ApplicationEvent&Listener完成业

    摘要:实体代码如下所示恒宇少年码云用户名密码创建内添加一个注册方法,该方法只是实现注册事件发布功能,代码如下所示恒宇少年码云用户注册方法省略其他逻辑发布事件事件发布是由对象管控的,我们发布事件前需要注入对象调用方法完成事件发布。 ApplicationEvent以及Listener是Spring为我们提供的一个事件监听、订阅的实现,内部实现原理是观察者设计模式,设计初衷也是为了系统业务逻辑之...

    Reducto 评论0 收藏0
  • SpringBoot

    摘要:基于,支持后面的版本二基本使用网页生成访问生成项目并下载。这里的配置项可以自动提示。数据配置文件配置四整合映射跟之前一样注册注册拦截器五整合基本整合使用映射文件映射文件和注解同时存在注解引入配置文件增加事务六自动配置自动原理配置项 一、SpringBoot简介 1. 使用SSM开发项目的时候有什么不足之处 创建ssm项目比较麻烦 配置比较麻烦 依赖的配置比较多比较麻烦 手动集成第三方...

    mykurisu 评论0 收藏0
  • 慕课网_《RabbitMQ消息中间件极速入门与实战》学习总结

    摘要:慕课网消息中间件极速入门与实战学习总结时间年月日星期三说明本文部分内容均来自慕课网。 慕课网《RabbitMQ消息中间件极速入门与实战》学习总结 时间:2018年09月05日星期三 说明:本文部分内容均来自慕课网。@慕课网:https://www.imooc.com 教学源码:无 学习源码:https://github.com/zccodere/s... 第一章:RabbitM...

    mykurisu 评论0 收藏0

发表评论

0条评论

最新活动
阅读需要支付1元查看
<