springboot添加对listener,servlet,filter的支持

比较常用的方式就是使用注解来添加对 监听器,过滤器,servlet的支持。

1.首先在启动类上添加  @ServletComponentScan  开启 对监听器,过滤器,servlet的注解扫描。

分别创建过滤器,拦截器,servlet

package com.example.demo.filter;

import java.io.IOException;

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

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

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

}

  

package com.example.demo.listener;

import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
@WebListener(value="MySessionListener")
public class MySessionListener implements HttpSessionListener {

	@Override
	public void sessionCreated(HttpSessionEvent se) {
		HttpSessionListener.super.sessionCreated(se);
		System.out.println("session create...");
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent se) {
		HttpSessionListener.super.sessionDestroyed(se);
	}

	
}

  

package com.example.demo.servlet;

import java.io.IOException;

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(urlPatterns="/my1",name="my1")
public class MyServlet extends HttpServlet {

	private static final long serialVersionUID = 4322324790077226450L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("MyServlet.....");
		req.getSession().setAttribute("aa", "bb");
	}

	@Override
	protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doPut(req, resp);
	}

	

}

  访问servlet结果如下:

my filter....
MyServlet.....
session create...

posted @ 2019-02-12 16:12  xfma  阅读(335)  评论(0编辑  收藏  举报