SpringBoot使用过滤器、 * 和 * 的案例代码(Springboot搭建java项目)
作者:dreamer_0423 发布时间:2022-11-21 06:08:54
标签:SpringBoot,过滤器, , , ,
SpringBoot使用过滤器、 * 和 *
一、SpringBoot使用过滤器
Spring boot过滤器的使用(两种方式)
使用spring boot提供的FilterRegistrationBean注册Filter
使用原生servlet注解定义Filter
两种方式的本质都是一样的,都是去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");
// 调用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);//定义过滤器的执行先后顺序 值越小越先执行 不影响Bean的加载顺序
return filterRegistrationBean;
}
}
方式二:
// 注入spring容器
@Order(1)//定义过滤器的执行先后顺序 值越小越先执行 不影响Bean的加载顺序
@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());
}
}
三、过滤器和 * 的执行顺序
过滤器的执行顺序是安装@Order注解中的值,或者是setOrder()中值的进行执行顺序排序的,值越小就越靠前。
* 则是先声明的 * preHandle() 方法先执行,而postHandle()方法反而会后执行。也即是:postHandle() 方法被调用的顺序跟 preHandle() 居然是相反的。如果实际开发中严格要求执行顺序,那就需要特别注意这一点。
四、SpringBoot使用 *
1、统计网站最多在线人数 * 的例子
/**
* 上下文 * ,在服务器启动时初始化onLineCount和maxOnLineCount两个变量,
* 并将其置于服务器上下文(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);
}
}
/**
* 会话 * ,在用户会话创建和销毁的时候根据情况修改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 * 的使用(以实现异步Event监听为例子)
定义事件类 Event
创建一个类,继承ApplicationEvent,并重写构造函数。ApplicationEvent是Spring提供的所有应用程序事件扩展类。
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;
}
}
创建一个用于监听指定事件的类,需要实现ApplicationListener接口,说明它是一个应用程序事件的监听类。注意这里需要加上@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());
}
}
事件发布
事件发布很简单,只需要使用Spring 提供的ApplicationEventPublisher来发布自定义事件
@Autowired 注入ApplicationEventPublisher
@RequestMapping("/notice/{msg}")
public void notice(@PathVariable String msg){
logger.info("begin>>>>>");
applicationEventPublisher.publishEvent(new Event(msg));
logger.info("end<<<<<<<");
}
来源:https://blog.csdn.net/m0_46616045/article/details/128823964


猜你喜欢
- 一 概述:最近一直致力于Android自定义VIew的学习,主要在看《android群英传》,还有CSDN博客鸿洋大神和wing
- 为什么要限流在保证可用的情况下尽可能多增加进入的人数,其余的人在排队等待,或者返回友好提示,保证里面的进行系统的用户可以正常使用,防止系统雪
- 说起垃圾收集(Garbage Collection,GC),大部分人都把这项技术当做Java语言的伴生产物。事实上,GC的历史远比Java久
- 程序如下:View Code /* * Hanoi塔游戏 问题描述: * 汉诺塔:汉诺塔(又称河内塔)问
- 我就废话不多说了,大家还是直接看代码吧~import java.io.UnsupportedEncodingException;import
- 一、时区的基本概念GMT(Greenwich Mean Time),即格林威治标准时,是东西经零度的地方。人们将地球人为的分为24等份,每一
- 类似普通对象,通过new创建字符串对象。String str = new String("Hello"); 内存图如下图
- 学过C#的人应该都知道抽象方法与虚拟方法,而很多初学者对二者之间的区别并不是很了解。今天本文就来分析一下二者之间的区别。并附上实例加以说明。
- 一、项目概述本次项目主要实现了天气预报功能。通过调用天气预报接口来获得天气数据,用LIstView和GridView来搭建每个界面,将查询的
- 同时使用and和or的查询UserServiceImpl 类,service实现类import org.springframework.be
- 1、目录结构Application属性文件,按优先级排序,位置高的将覆盖位置当前项目目录下的一个/config子目录当前项目目录项目的res
- 打开ITerm终端进入命令输入,sudo su,输入密码创建.bash_profile文件touch .bash_profile打开.bas
- 前言在一个 Web 请求中,参数我们无非就是放在地址栏或者请求体中,个别请求可能放在请求头中。放在地址栏中,我们可以通过如下方式获取参数:S
- 详解HDFS多文件Join操作的实例最近在做HDFS文件处理之时,遇到了多文件Join操作,其中包括:All Join以及常用的Left J
- 在工作过程中,需要将一个文件夹生成压缩文件,然后提供给用户下载。所以自己写了一个压缩文件的工具类。该工具类支持单个文件和文件夹压缩。放代码:
- 前言Android的编辑框控件EditText在平常编程时会经常用到,有时候会对编辑框增加某些限制,如限制只能输入数字,最大输入的文字个数,
- 举例说明:1、有一个200*200像素的窗口,想要把它放在800*600像素的屏幕中间,屏幕的位置应是(800/2,600/2)=(400,
- 添加jar包这里的Scala不是maven工程所以要找到项目结构(快捷键:同时按住Ctrl+shift+Alt+s)在模块里面添加添加MyS
- 一、栈1.1 概述Java为什么要有集合类: 临时存储数据。链表的本质: 对象间通过持有和引用关系互相关联起来。线性表: 普通线性表, 操作
- 网上关于下拉刷新的文章也不少,不过都太长了。恰好发现了官方的下拉刷新库,而且效果还是不错的,简洁美观,用得也挺方便。下面是效果图:我的好友原