springboot中定制自己的servlet filter listener

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xdy3008/article/details/84454516

知识回顾:

servlet主要负责处理请求

filter主要负责拦截请求,和放行

listener可以监听web服务器中某一个执行动作,并根据其要求作出相应的响应。 比如:spring 的总监听器 会在服务器启动的时候实例化我们配置的bean对象

public class ContextLoaderListener extends ContextLoader implements ServletContextListener {
    public ContextLoaderListener() {
    }

    public ContextLoaderListener(WebApplicationContext context) {
        super(context);
    }

    public void contextInitialized(ServletContextEvent event) {
        this.initWebApplicationContext(event.getServletContext());
    }

    public void contextDestroyed(ServletContextEvent event) {
        this.closeWebApplicationContext(event.getServletContext());
        ContextCleanupListener.cleanupAttributes(event.getServletContext());
    }
}

servlet应用场景:

Servlet是一种服务器端的Java应用程序,具有独立于平台和协议的特性,可以生成动态的Web页面。 它担当客户请求(Web浏览器或其他HTTP客户程序)与服务器响应(HTTP服务器上的数据库或应用程序)的中间层。 Servlet是位于Web 服务器内部的服务器端的Java应用程序,与传统的从命令行启动的Java应用程序不同,Servlet由Web服务器进行加载,该Web服务器必须包含支持Servlet的Java虚拟机

比如:针对特定的登录人,导航到特定的页面

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    if(req.getSession("loginRole").equals("boss")){
        req.setAttribute("WelcomeMsg", "Hello Boss!!! ");
        .....
    }
    resp.getWriter().write("Hello MyServlet");
}

Filter应用场景:

1、使浏览器不缓存页面的过滤器

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException   
{   
    ((HttpServletResponse) response).setHeader("Cache-Control","no-cache");   
    ((HttpServletResponse) response).setHeader("Pragma","no-cache");   
    ((HttpServletResponse) response).setDateHeader ("Expires", -1);   
    filterChain.doFilter(request, response);   
}   

2、检测用户是否登陆的过滤器

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException   
{   
    HttpServletRequest request = (HttpServletRequest) servletRequest;   
    HttpServletResponse response = (HttpServletResponse) servletResponse;   
    
     HttpSession session = request.getSession();   
   if(sessionKey == null)   
    {   
     filterChain.doFilter(request, response);   
    return;   
    }   
   if((!checkRequestURIIntNotFilterList(request)) && session.getAttribute(sessionKey) == null)   
    {   
     response.sendRedirect(request.getContextPath() + redirectURL);   
    return;   
    }   
    filterChain.doFilter(servletRequest, servletResponse);   
}   

3、字符编码的过滤器

public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException    
14 {    
15          if(encoding != null)    
16            servletRequest.setCharacterEncoding("utf-8");    
17           filterChain.doFilter(servletRequest, servletResponse);    
18 }    
19    

那么springboot中,如何把自定义的servlet filter lisenter加载到内置的Tomcat容器中呢 ?

public class MyServlet extends HttpServlet {

    //处理get请求
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.getWriter().write("Hello MyServlet");
    }
}

public class MyFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        System.out.println("MyFilter process...");
        chain.doFilter(request, response);

    }

    @Override
    public void destroy() {

    }
}

public class MyListener implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("contextInitialized...web应用启动");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("contextDestroyed...当前web项目销毁");
    }
}



import com.atguigu.springboot.filter.MyFilter;
import com.atguigu.springboot.listener.MyListener;
import com.atguigu.springboot.servlet.MyServlet;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletListenerRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.Arrays;

@Configuration
public class MyServerConfig {

    //注册三大组件
    @Bean
    public ServletRegistrationBean myServlet() {
        ServletRegistrationBean registrationBean = new ServletRegistrationBean(new MyServlet(), "/myServlet");
        registrationBean.setLoadOnStartup(1);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean myFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(new MyFilter());
        registrationBean.setUrlPatterns(Arrays.asList("/hello", "/myServlet"));
        return registrationBean;
    }

    @Bean
    public ServletListenerRegistrationBean myListener() {
        ServletListenerRegistrationBean<MyListener> registrationBean = new ServletListenerRegistrationBean<>(new MyListener());
        return registrationBean;
    }


    //配置嵌入式的Servlet容器, 定制跟server有关的配置项, 这种方法跟在appliccation.properties中配置效果一样
    @Bean
    public EmbeddedServletContainerCustomizer embeddedServletContainerCustomizer() {
        return new EmbeddedServletContainerCustomizer() {

            //定制嵌入式的Servlet容器相关的规则
            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                container.setPort(8083);
            }
        };
    }

}

猜你喜欢

转载自blog.csdn.net/xdy3008/article/details/84454516
今日推荐