一、过滤器简介

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. spring boot2 集成Redis

    1. 引入依赖 <parent> <groupId>org.springframework.boot</groupId> <artifactId>spr ...

  2. VS2015离线安装NuGet Package

    在一些情况下,VS2015直接安装NuGet Package的时候,速度异常缓慢: 所以还是考虑直接离线安装: Step1: 下载相应的Package https://www.nuget.org/ 然 ...

  3. 一行代码实现自定义转场动画--iOS自定义转场动画集

    WXSTransition 这款非常不错,力推 这是作者源码简书地址: http://www.jianshu.com/p/fd3154946919 这是作者源码github地址 https://git ...

  4. Real World Parsec --- 一个简便易学的 解释器

    学习链接如下: http://bms.tratao.com/desktop/doc/0c3802e4ee404a71407f34996eff98ef 另外的解析器 ANTLR,学过一阵子,比较难,没应 ...

  5. [Unity插件]DOTween基础

    官方文档链接:http://dotween.demigiant.com/documentation.PHP#globalSettings 普通版下载地址:http://dotween.demigian ...

  6. kaldi的TIMIT实例二

    ============================================================================ MonoPhone Training & ...

  7. Request模块—数据解析工具

    一.爬虫基本步骤 指定URL信息 发起请求 获取响应数据 对响应数据进行数据解析 持久化存储 二.数据解析 1. 正则表达式 (1) 基本语法 1. 单字符: . : 除换行以外所有字符 [] :[a ...

  8. 使用广播-BroadcastReceiver最详细解析

    女孩:BroadcastReceiver是什么呀? 男孩:Broadcast是广播的意思,在Android中应用程序之间的传输信息的机制,BroadcastReceiver是接收广播通知的组件,广播和 ...

  9. Swift5 语言指南(十四) 下标

    类,结构和枚举可以定义下标,下标是用于访问集合,列表或序列的成员元素的快捷方式.您可以使用下标按索引设置和检索值,而无需单独的设置和检索方法.例如,您可以访问在元素Array实例作为someArray ...

  10. spring-boot(hello world)

    重拾程序,想不到从java开始,最近两周开搞web,从基本框架开始,仅做个人学习记录,遗漏之处望请海涵. 1.基本准备 开发环境win7: IDE  myeclipse Version: 2017 C ...