一、过滤器简介

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(七)过滤器&监听器 相关的更多相关文章

  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. Gitlab配置、备份、升级、迁移

    0.Gitlab安装 1.安装和配置必要的依赖关系 在CentOS7,下面的命令将在系统防火墙打开HTTP和SSH访问. yum install curl openssh-server postfix ...

  2. C# Thread、ThreadPool、Task、Invoke、BeginInvoke、async、await 汇总

    本文将主要通过"同步调用"."异步调用"."异步回调"三个示例来讲解在用委托执行同一个"加法类"的时候的的区别和利弊. ...

  3. 请教:WCF速度似乎比Remoting慢

    两段极为相似的代码,主要想看看过输与序列化过程两者的用时差异,结果10000次的调用,WCF用了11秒多,remoting用了5秒不到!这是测试的源代码 Remoting的服务端 public cla ...

  4. Javascript高级编程学习笔记(10)—— 作用域、作用域链

    昨天介绍了,JS中函数的作用域 什么词法环境之类的,可能很多小伙伴不太明白. 在今天的内容开始之前,先做个简短的声明: 词法环境这一概念是在ES5中提出的,因为词法环境主要用于保存let.const声 ...

  5. mybatis 控制台打印sql语句

    其实很简单,打印SQL只需要加一个setting就可以了.亲测可用. mybatis-config.xml: <settings>        <setting name=&quo ...

  6. vscode 集成 cygwin 的注意事项

    vscode 集成 cygwin vscode 现在是我的主力开发编辑器,它自带 terminal 不需要我各种切换,我还想要在 windows 下执行一些简单的 .sh 文件.所以,我希望有一款工具 ...

  7. [Swift]正则表达式工具类

    正则表达式工具类 import Foundation //基于NSRegularExpression api 的正则处理工具类 public struct Regex { private let re ...

  8. 写你的shell,其实很简单[架构篇]

    引语:我本人以前并没有写过shell脚本,也许是因为懒,也许是没有被逼到要去写shell的地步.但是,前段时间,工作需求,要求重新跑几个月的脚本,这些脚本是每天定时进行跑的,而且每天是好几个脚本一起关 ...

  9. shell 中的三种引号的作用

    1. 单引号(' ') 单引号里的任何字符都会原样输出,单引号字符串中的变量是无效的: 单引号字串中不能出现单独一个的单引号(对单引号使用转义符后也不行),但可成对出现,作为字符串拼接使用. 2. 双 ...

  10. 详谈再论JAVA获取本机IP地址

    首先,你如果搜索“JAVA获取本机IP地址”,基本上搜到的资料全是无用的.比如这篇:http://www.cnblogs.com/zrui-xyu/p/5039551.html实际上的代码在复杂环境下 ...