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: ...
随机推荐
- Python开发——4.集合和字符串拼接
一.集合(set) 1.集合的特性: 不同元素组成.元素是无序排列的可hash值 2.集合转为列表 s1 = {11,"hechouzi",(11,22,33)} names = ...
- 从MATLAB到FPGA 视频和图像处理——讲座学习小结(视频地址https://ww2.mathworks.cn/videos/from-matlab-to-fpga-video-and-image-processing-102492.html)
1.HDLcoder产品介绍 图像处理分为两个部分: 这里主要讨论第一部分图像处理部分. 一般产品设计流程如下: 适用人群有以下两类: 这里先用一张slider来进行整体概括: 基于模型的设计的好处— ...
- array_filter()函数
用回调函数过滤数组中的值 array_filter(array,callbackfunction); 返回过滤后的数组
- Anton 上课题
Anton 上课题 Anton likes to play chess. Also he likes to do programming. No wonder that he decided to a ...
- 学习在dos下使用gcc来编译
这两年里,断断续续的学习和使用c,平时都是在CodeBlocks里写代码,编译程序,点一下按钮就行了.对整个编译过程是一点儿都不了解.相比当年学习java,真的是选择了两个不同的路,当年学习java的 ...
- 9.3 翻译系列:数据注解特性之Key【EF 6 Code-First 系列】
原文链接:http://www.entityframeworktutorial.net/code-first/key-dataannotations-attribute-in-code-first.a ...
- 583. Delete Operation for Two Strings
Given two words word1 and word2, find the minimum number of steps required to make word1 and word2 t ...
- GCD on Blackboard
题目大意:给你n个数,然后在这n个数中选一个数,选中的这个数可以变成任意的数,使这n个数的gcd(最大公约数)最大.打印这个最大的gcd. 思路:这题一看貌似很复杂,其实这题只要你知道前缀和 和 ...
- 第32节:Java中-构造函数,静态方法,继承,封装,多态,包
构造函数实例 class Cat{ // 设置私有的属性 name private String name; // 设置name的方法 public void setName(String Name) ...
- Maven - Tips
1- Maven的Settings http://maven.apache.org/settings.html 2- Maven设置代理 示例: <proxies> <proxy&g ...