Java基础——Servlet(七)过滤器&监听器 相关
一、过滤器简介
Filter 位于客户端和请求资源之间,请求的资源可以是 Servlet Jsp html (img,javascript,css)等。用于拦截浏览器发给服务器的请求(Request)和服务器返回给浏览器的内容(Response)。一言以蔽之:过滤器是用来筛选请求的。

* 怎么实现一个过滤器? 思路如下:
1) 编写一个类, 实现javax.servlet.Filter 接口
-- destory();
-- init(FilterConfig config);
-- doFilter(ServletRequest req,ServletResponse resp, FilterChain chain);
2) 在 web.xml 中进行配置
二、处理乱码的过滤器
public class CharaFilter implements Filter{
private String encoding="iso8859-1"; //默认
public void destroy() {}
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
System.out.println("----过滤器起作用了----");
request.setCharacterEncoding(encoding);
//response.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig config) throws ServletException {
String confEncoding=config.getInitParameter("encoding"); //取得Filter配置文件中的初始化参数
if(confEncoding!=null){
encoding=confEncoding;
}
}
}
//配置文件设置
<filter>
<filter-name>CharaFilter</filter-name>
<filter-class>filter.CharaFilter</filter-class> <init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharaFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
三、验证是否有Session 的过滤器
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException { HttpServletRequest req=(HttpServletRequest)request;
HttpServletResponse rep=(HttpServletResponse)response; if(req.getSession().getAttribute("userInfo")==null){ req.getRequestDispatcher("/login.jsp").forward(request, response); /*
//这里的 / 代表当前web应用的根路径 /Lession49
req.getRequestDispatcher("/xxxx").forward(request, response); //这里代表当前web服务器的根路径 ... 8080/
rep.sendRedirect("/xxxx"); //如果想让sendRedirect准确
rep.sendRedirect(req.getContextPath()+"/"+"xxxx"); //这里的getContextPath取得的是 web应的根路径 /Lession49
*/ }else{
chain.doFilter(request, response);
}
}
//配置文件的设置
<filter>
<filter-name>sessionFilter</filter-name>
<filter-class>filter.SessionFilter</filter-class>
</filter> <filter-mapping>
<filter-name>sessionFilter</filter-name>
<url-pattern>/Admin/*</url-pattern>
</filter-mapping>
四、servlet监听器
servlet监听的对象:
它负责监听ServletContext、HttpSession、ServletRequest对象的生命周期时间,以及属性改变事件。用于监听一些重要事件的发生,监听器对象可以在事情发生前、发生后可以做一些必要的处理
Listener是Servlet的监听器,它可以监听客户端的请求、服务端的操作等。通过监听器,可以自动激发一些操作,比如监听在线的用户的数量。当增加一个HttpSession时,就激发sessionCreated(HttpSessionEvent se)方法,目前Servlet2.4和JSP2.0总共有8个监听器接口和6个Event类。
| Listener接口 | Event类 |
| ServletContextListener | ServletContextEvent |
| ServletContextAttributeListener | ServletContextAttributeEvent |
| HttpSessionListener | HttpSessionEvent |
| HttpSessionActivationListener | 同上 |
| HttpSessionAttributeListener | HttpSessionBindingEvent //用于监听session中何时添加、删除或替换了某种类型的属性 |
| HttpSessionBindingListener | 同上 //由属性自身来实现,以便属性知道它什么时候被添加到一个session中,或者什么时候从session中删除。 |
| ServletRequestListener | ServletRequestEvent |
4.1 ServletContextListener
用于监听W EB 应用启动和销毁的事件,监听器类需要实现javax.servlet.ServletContextListener 接口。
ServletContextListener 是 ServletContext 的监听者,如果 ServletContext 发生变化,如服务器启动时 ServletContext 被创建,服务器关闭时 ServletContext 将要被销毁。
--ServletContextListener接口的方法:
void contextInitialized(ServletContextEvent sce) //通知正在接受的对象,应用程序已经被加载及初始化。 void contextDestroyed(ServletContextEvent sce) // 通知正在接受的对象,应用程序已经被载出。
--ServletContextEvent中的方法:
ServletContext getServletContext() // 取得ServletContext对象 (application)
4.2 ServletContextAttributeListener
用于监听WEB应用属性改变的事件,包括:增加属性、删除属性、修改属性,监听器类需要实现javax.servlet.ServletContextAttributeListener接口。
--ServletContextAttributeListener接口方法:
void attributeAdded(ServletContextAttributeEvent scab)//若有对象加入Application的范围,通知正在收听的对象
void attributeRemoved(ServletContextAttributeEvent scab) // 若有对象从Application的范围移除,通知正在收听的对象
void attributeReplaced(ServletContextAttributeEvent scab)//若在Application的范围中,有对象取代另一个对象时,通知正在收听的对象
--ServletContextAttributeEvent中的方法:
java.lang.String getName() 回传属性的名称
java.lang.Object getValue() 回传属性的值
4.3 HttpSessionListener
HttpSessionListener 监听HttpSession的操作。当创建一个Session时,激发session Created(HttpSessionEvent se)方法;当销毁一个Session时,激发sessionDestroyed (HttpSessionEvent se)方法。
4.4 HttpSessionActivationListener
主要用于同一个Session转移至不同的JVM的情形,用于监听Http会话active、passivate情况。。
HttpSessionAttributeListener
4.5 HttpSessionAttributeListener监听HttpSession中的属性的操作。
当在 Session 增加一个属性时,激发attributeAdded(HttpSessionBindingEvent se) 方法;
当在Session删除一个属性时,激发attributeRemoved(HttpSessionBindingEvent se)方法;
当在Session属性被重新设置时,激发attributeReplaced(HttpSessionBindingEvent se) 方法。
这和ServletContextAttributeListener比较类似
4.6 HttpSessionBindingListener
注意:HttpSessionBindingListener接口是唯一不需要再web.xml中设定的Listener
当我们的类实现了HttpSessionBindingListener接口后,只要对象加入Session范围
(即调用HttpSession对象的 setAttribute方法的时候)或从Session范围中移出
(即调用HttpSession对象的removeAttribute方法的时候或 Session Time out的时候)时,容器分别会自动调用下列两个方法:
-- void valueBound(HttpSessionBindingEvent event)
-- void valueUnbound(HttpSessionBindingEvent event)
4.7 ServletRequestListener
它和ServletContextListener接口类似的,这里由ServletContext改为ServletRequest。
4.8 ServletRequestAttributeListener
它和ServletContextListener接口类似的,这里由ServletContext改为ServletRequest。
五、servlet监听器实例
//例一
1) 创建一个类,实现某个监听器接口
public class MyListener implements ServletContextListener{
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("上下文销毁了"); //网站关闭
} public void contextInitialized(ServletContextEvent arg0) {
System.out.println("上下文创建了"); //网站启动的时候
}
} 2) 在web.xml 这个配置文件中进行配置
<listener>
<listener-class>cat.listener.MyListener</listener-class>
</listener>
//例二 通过实现 MySessionListener 接口, 做一个简单在线人数计数器
public class MyListener implements ServletContextListener{
public void contextDestroyed(ServletContextEvent arg0) {
System.out.println("上下文销毁了"); //网站关闭
}
public void contextInitialized(ServletContextEvent arg0) {
System.out.println("上下文创建了"); //网站启动的时候
}
}
//配置文件的设置
<listener>
<listener-class>cat.listener.MySessionListener</listener-class>
</listener>
//index.jsp设置
<% out.println("当前在线人数:"+ MySessionListener.getSessioCount()); %>
Java基础——Servlet(七)过滤器&监听器 相关的更多相关文章
- Java实习生常规技术面试题每日十题Java基础(七)
目录 1. Java设计模式有哪些? 2.GC是什么?为什么要有GC? 3. Java中是如何支持正则表达式. 4.比较一下Java和JavaSciprt. 5.Math.round(11.5) 等于 ...
- Java基础——Servlet
什么是Servlet Servlet是Java Web的三大组件之一,它属于动态资源.Servlet的作用是处理请求,服务器会把接收到的请求交给Servlet来处理,在Servlet中通常需要: l ...
- Java基础——Servlet(六)分页相关
前面写了Servlet(一)到(五),主要是在网上搜罗的视频.对分页这块还是不太清楚.于是有找到一些视频,重新学习了一下.主要是对分页的认识和设计思路.也是为了方便我以后回忆一下.. 一.分页常识 p ...
- Java基础——Servlet(八)文件上传下载
一.简单的文件上传常见的组件Smartupload , Apache 的 commons FileUploadSmartupload上传的步骤: 1.初始化上传上下文 2.准备上传 3.保存文件 &l ...
- Java基础——Servlet(一)
在学习Servlet之前,需要首先学习一些关联性的知识. 一.动态网页程序 动态网页:它是网页中的偏功能性的部分也是最重要的部分.它不是我们平时所看见的页面特效,展示的效果.而是,一种交互行为.比如, ...
- java中拦截器 过滤器 监听器都有什么区别
过滤器,是在java web中,你传入的request,response提前过滤掉一些信息,或者提前设置一些参数,然后再传入servlet或者struts2的action进行业务逻辑,比如过滤掉非法u ...
- Java基础——Servlet(五)
哈哈哈...学习Servlet学了半个多月,因为中间有比较灰心的时候,有几天是啥都不学了的状态,看了好几部励志的电影.呃~还是得继续吧.本来计划是好好夯实这里的基础,结果在网找到了介绍比较全面的视频, ...
- 构造方法,重载,static,math类(java基础知识七)
1.构造方法概述和格式 * A:构造方法概述和作用 * 给对象的数据(属性)进行初始化 * B:构造方法格式特点 * a:方法名与类名相同(大小也要与类名一致) * b:没有返 ...
- jar,war,ear区别及java基础杂七八
jar,war,earqu区别 这三种文件都可以看作是java的压缩格式,其实质是实现了不同的封装: jar--封装类war--封装web站点ear--封装ejb.它们的关系具体为:jar: ...
随机推荐
- dom4j 创建一个带命名空间的pom.xml 文件
http://xml.apache.org/xalan-j/index.html 需要的jar包 <dependencies> <dependency> <groupId ...
- 内置函数_range()
range() range()语法格式为 range([start,] stop [,step])# 有三种用法range(stop)range(start,stop)range(start,stop ...
- 几种String对象方法的区别
1.在String对象方法中,发现.slice()方法和.substring()方法的作用几乎相同,都是根据起始索引返回截取得到的字符串.经过查阅资料和实测得到区别: 正常情况下索引都为正值,返回值为 ...
- Python之旅Day3 文件操作 函数(递归|匿名|嵌套|高阶)函数式编程 内置方法
知识回顾 常见五大数据类型分类小结:数字.字符串.列表.元组.字典 按存值个数区分:容器类型(列表.字典.元组) 标量原子(数字.字符串) 按是否可变区分:可变(列表.字典) 不可变(数字.字符串.元 ...
- Servlet的补充知识
ServletContextAware是获取ServletContext一个接口.只需要实现此接口重写里面的setServletContext方法,spring在初始化的时候通过xmlClasspat ...
- 进程控制(Note for apue and csapp)
1. Introduction We now turn to the process control provided by the UNIX System. This includes the cr ...
- 「WC2018」州区划分(FWT)
「WC2018」州区划分(FWT) 我去弄了一个升级版的博客主题,比以前好看多了.感谢 @Wider 不过我有阅读模式的话不知为何 \(\text{LATEX}\) 不能用,所以我就把这个功能删掉了. ...
- tk.mybatis通用工具采坑记
tk.mybatis通用工具pom <!--mybatis依赖--> <dependency> <groupId>org.mybatis.spring.boot&l ...
- kill 结束进程
kill 支持的信号 kill -1 重启进程 kill -9 终止进程 pkill 和 killall 的区别在于pkill 可以踢终端用户 pkill -9 -t tty1
- django rest framework mixins小结
本篇对drf中的mixins进行简要的分析总结. from rest_framework import viewsets 在这个viewsets中,只有5类Minxin,他们与http方法对应如下: ...