一、过滤器简介

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 中进行配置

二、处理乱码的过滤器

  1. public class CharaFilter implements Filter{
  2. private String encoding="iso8859-1"; //默认
  3.  
  4. public void destroy() {}
  5.  
  6. @Override
  7. public void doFilter(ServletRequest request, ServletResponse response,
  8. FilterChain chain) throws IOException, ServletException {
  9. System.out.println("----过滤器起作用了----");
  10.  
  11. request.setCharacterEncoding(encoding);
  12. //response.setCharacterEncoding(encoding);
  13.  
  14. chain.doFilter(request, response);
  15. }
  16.  
  17. @Override
  18. public void init(FilterConfig config) throws ServletException {
  19. String confEncoding=config.getInitParameter("encoding"); //取得Filter配置文件中的初始化参数
  20. if(confEncoding!=null){
  21. encoding=confEncoding;
  22. }
  23. }
  24. }
  1. //配置文件设置
  2. <filter>
  3. <filter-name>CharaFilter</filter-name>
  4. <filter-class>filter.CharaFilter</filter-class>
  5.  
  6. <init-param>
  7. <param-name>encoding</param-name>
  8. <param-value>UTF-8</param-value>
  9. </init-param>
  10. </filter>
  11. <filter-mapping>
  12. <filter-name>CharaFilter</filter-name>
  13. <url-pattern>/*</url-pattern>
  14. </filter-mapping>

三、验证是否有Session 的过滤器

  1. public void doFilter(ServletRequest request, ServletResponse response,
  2. FilterChain chain) throws IOException, ServletException {
  3.  
  4. HttpServletRequest req=(HttpServletRequest)request;
  5. HttpServletResponse rep=(HttpServletResponse)response;
  6.  
  7. if(req.getSession().getAttribute("userInfo")==null){
  8.  
  9. req.getRequestDispatcher("/login.jsp").forward(request, response);
  10.  
  11. /*
  12. //这里的 / 代表当前web应用的根路径 /Lession49
  13. req.getRequestDispatcher("/xxxx").forward(request, response);
  14.  
  15. //这里代表当前web服务器的根路径 ... 8080/
  16. rep.sendRedirect("/xxxx");
  17.  
  18. //如果想让sendRedirect准确
  19. rep.sendRedirect(req.getContextPath()+"/"+"xxxx"); //这里的getContextPath取得的是 web应的根路径 /Lession49
  20. */
  21.  
  22. }else{
  23. chain.doFilter(request, response);
  24. }
  25. }
  26. //配置文件的设置
  27. <filter>
  28. <filter-name>sessionFilter</filter-name>
  29. <filter-class>filter.SessionFilter</filter-class>
  30. </filter>
  31.  
  32. <filter-mapping>
  33. <filter-name>sessionFilter</filter-name>
  34. <url-pattern>/Admin/*</url-pattern>
  35. </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接口的方法:

  1. void contextInitialized(ServletContextEvent sce) //通知正在接受的对象,应用程序已经被加载及初始化。
  2.  
  3. void contextDestroyed(ServletContextEvent sce) // 通知正在接受的对象,应用程序已经被载出。

--ServletContextEvent中的方法:

  1. ServletContext getServletContext() // 取得ServletContext对象 (application)

4.2 ServletContextAttributeListener

用于监听WEB应用属性改变的事件,包括:增加属性、删除属性、修改属性,监听器类需要实现javax.servlet.ServletContextAttributeListener接口。

--ServletContextAttributeListener接口方法:

  1. void attributeAdded(ServletContextAttributeEvent scab)//若有对象加入Application的范围,通知正在收听的对象
  2. void attributeRemoved(ServletContextAttributeEvent scab) // 若有对象从Application的范围移除,通知正在收听的对象
  3. 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. //例一
  2. 1) 创建一个类,实现某个监听器接口
  3. public class MyListener implements ServletContextListener{
  4. public void contextDestroyed(ServletContextEvent arg0) {
  5. System.out.println("上下文销毁了"); //网站关闭
  6. }
  7.  
  8. public void contextInitialized(ServletContextEvent arg0) {
  9. System.out.println("上下文创建了"); //网站启动的时候
  10. }
  11. }
  12.  
  13. 2) web.xml 这个配置文件中进行配置
  14. <listener>
  15. <listener-class>cat.listener.MyListener</listener-class>
  16. </listener>
  1. //例二 通过实现 MySessionListener 接口, 做一个简单在线人数计数器
  2.  
  3. public class MyListener implements ServletContextListener{
  4.  
  5. public void contextDestroyed(ServletContextEvent arg0) {
  6. System.out.println("上下文销毁了"); //网站关闭
  7. }
  8.  
  9. public void contextInitialized(ServletContextEvent arg0) {
  10. System.out.println("上下文创建了"); //网站启动的时候
  11. }
  12. }
  13.  
  14. //配置文件的设置
  15. <listener>
  16. <listener-class>cat.listener.MySessionListener</listener-class>
  17. </listener>
  18.  
  19. //index.jsp设置
  20. <% out.println("当前在线人数:"+ MySessionListener.getSessioCount()); %>

Java基础——Servlet(七)过滤器&监听器 相关的更多相关文章

  1. Java实习生常规技术面试题每日十题Java基础(七)

    目录 1. Java设计模式有哪些? 2.GC是什么?为什么要有GC? 3. Java中是如何支持正则表达式. 4.比较一下Java和JavaSciprt. 5.Math.round(11.5) 等于 ...

  2. Java基础——Servlet

    什么是Servlet Servlet是Java Web的三大组件之一,它属于动态资源.Servlet的作用是处理请求,服务器会把接收到的请求交给Servlet来处理,在Servlet中通常需要: l  ...

  3. Java基础——Servlet(六)分页相关

    前面写了Servlet(一)到(五),主要是在网上搜罗的视频.对分页这块还是不太清楚.于是有找到一些视频,重新学习了一下.主要是对分页的认识和设计思路.也是为了方便我以后回忆一下.. 一.分页常识 p ...

  4. Java基础——Servlet(八)文件上传下载

    一.简单的文件上传常见的组件Smartupload , Apache 的 commons FileUploadSmartupload上传的步骤: 1.初始化上传上下文 2.准备上传 3.保存文件 &l ...

  5. Java基础——Servlet(一)

    在学习Servlet之前,需要首先学习一些关联性的知识. 一.动态网页程序 动态网页:它是网页中的偏功能性的部分也是最重要的部分.它不是我们平时所看见的页面特效,展示的效果.而是,一种交互行为.比如, ...

  6. java中拦截器 过滤器 监听器都有什么区别

    过滤器,是在java web中,你传入的request,response提前过滤掉一些信息,或者提前设置一些参数,然后再传入servlet或者struts2的action进行业务逻辑,比如过滤掉非法u ...

  7. Java基础——Servlet(五)

    哈哈哈...学习Servlet学了半个多月,因为中间有比较灰心的时候,有几天是啥都不学了的状态,看了好几部励志的电影.呃~还是得继续吧.本来计划是好好夯实这里的基础,结果在网找到了介绍比较全面的视频, ...

  8. 构造方法,重载,static,math类(java基础知识七)

    1.构造方法概述和格式 * A:构造方法概述和作用     * 给对象的数据(属性)进行初始化 * B:构造方法格式特点     * a:方法名与类名相同(大小也要与类名一致)     * b:没有返 ...

  9. jar,war,ear区别及java基础杂七八

    jar,war,earqu区别 这三种文件都可以看作是java的压缩格式,其实质是实现了不同的封装: jar--封装类war--封装web站点ear--封装ejb.它们的关系具体为:jar:      ...

随机推荐

  1. Unity、C#读取XML

    有如下XML文件: <?xml version="1.0" encoding="UTF-8"?> <DataNode> <prov ...

  2. Codeforces Round #486 (Div. 3) A. Diverse Team

    Codeforces Round #486 (Div. 3) A. Diverse Team 题目连接: http://codeforces.com/contest/988/problem/A Des ...

  3. Visual C++.NET设计

    首先,创建对应的工程,VS2010以及以前的版本,创建项目时都可以在CLR下找到“Windows窗体应用程序”的项目模板,但是VS2012以后的版本就没这么方便了.可以通过打开旧版本的项目来修改,也可 ...

  4. hive 语法 case when 语法

    ' then '精选' else null end as sale_type 注意: end不能少

  5. 谈谈最近的想法和 Thoughtworks 的 Offer

    最近笔者一直没有记录博客,原因是因为卷入了面试,离职,谈判,思考等一系列事件中.不过可以先说明一下的是, 笔者最后还是拒绝了 Thoughtworks 的 Offer,继续留在目前的公司. 去年毕业后 ...

  6. [Project] MiniSearch文本检索简介

    1. 预处理过程 预处理主要用来事先生成程序在运行过程中可能用到的数据,以便加速处理时间. 预处理的过程主要生成程序所需的三个文件:网页库文件,网页位置信息文件和倒排索引文件. 网页库文件 其中网页库 ...

  7. 背水一战 Windows 10 (67) - 控件(控件基类): DependencyObject - CoreDispatcher, 依赖属性的设置与获取, 依赖属性的变化回调

    [源码下载] 背水一战 Windows 10 (67) - 控件(控件基类): DependencyObject - CoreDispatcher, 依赖属性的设置与获取, 依赖属性的变化回调 作者: ...

  8. GC垃圾回收机制,iOS内存管理。

    问题: MRC中通过调用静态方法创建的新对象,不再使用时需要对其发送release消息吗? 不需要,因为约定静态方法创建的对象会自动将其放入自动释放池,即已对其发送autorelease消息,因此不可 ...

  9. php安装扩展的几种方法

    转自:http://doc3.workerman.net/appendices/install-extension.html 安装扩展 注意 与Apache+PHP或者Nginx+PHP的运行模式不同 ...

  10. 简单的基于矩阵分解的推荐算法-PMF, NMF

    介绍: 推荐系统中最为主流与经典的技术之一是协同过滤技术(Collaborative Filtering),它是基于这样的假设:用户如果在过去对某些项目产生过兴趣,那么将来他很可能依然对其保持热忱.其 ...