06 Listener,Filter,BeanUtils
Listener
监听器,监听某一个事件的发生。 状态的改变。
内部机制其实就是接口回调.
接口回调
需求:A在执行循环,当循环到5的时候, 通知B。
事先先把一个对象传递给 A , 当A 执行到5的时候,通过这个对象,来调用B中的方法。 但是注意,不是直接传递B的实例,而是传递一个接口的实例过去。
Web监听器
总共有8个 划分成三种类型
1. 定义一个类,实现接口
2. 注册 | 配置监听器
监听三个作用域创建和销毁
request ---httpServletRequest
session ---httpSession
application --- ServletContext
1. ServletContextListener
servletcontext创建:
1. 启动服务器的时候
servletContext销毁:
2. 关闭服务器. 从服务器移除项目
2. ServletRequestListener
request创建:
访问服务器上的任意资源都会有请求出现。
访问 html: 会
访问 jsp: 会
访问 servlet : 会
request销毁:
服务器已经对这次请求作出了响应。
public class MyRequestListener implements ServletRequestListener {
@Override
public void requestDestroyed(ServletRequestEvent sre) {
System.out.println("servletrequest 销毁了");
}
@Override
public void requestInitialized(ServletRequestEvent sre) {
System.out.println("servletrequest 初始化了");
}
}
<listener>
<listener-
class>com.itheima.listener.MyRequestListener</listener-class>
</listener>
3. HttpSessionListener
session的创建
## 只要调用getSession html: 不会
jsp: 会 getSession();
servlet: 会 session的销毁
超时 30分钟 非正常关闭 销毁 正常关闭服务器(序列化) public class MySessionListener implements HttpSessionListener { @Override
public void sessionCreated(HttpSessionEvent se) {
System.out.println("创建session了");
} @Override
public void sessionDestroyed(HttpSessionEvent se) {
System.out.println("销毁session了");
}
}
作用:
ServletContextListener
利用它来,在servletcontext创建的时候,
1. 完成自己想要的初始化工作
2. 执行自定义任务调度。 执行某一个任务。 Timer
HttpSessionListener 统计在线人数.
监听三个作用域属性状态变更:
可以监听在作用域中值 添加 | 替换 | 移除的动作。
servletContext --- ServletContextAttributeListener
request --- ServletRequestAttributeListener
session --- HttpSessionAttributeListener
监听httpSession里面存值的状态变更
这一类监听器不用注册。
* HttpSessionBindingListener
监听对象与session 绑定和解除绑定 的动作
1. 让javaBean 实现该接口即可
//添加
@Override
public void valueBound(HttpSessionBindingEvent event) {
System.out.println("对象被绑定进来了");
}
//移除
@Override
public void valueUnbound(HttpSessionBindingEvent event) {
System.out.println("对象被解除绑定");
}
* HttpSessionActivationListener
用于监听现在session的值 是 钝化 (序列化)还是活化 (反序列化)的动作 钝化 (序列化) 把内存中的数据 存储到硬盘上 活化 (反序列化) 把硬盘中的数据读取到内存中。
session的钝化活化的意义:
session中的值可能会很多, 并且我们有很长一段时间不使用这个内存中的值, 那么可以考虑把session的值可以存储到硬盘上【钝化】,等下一次在使用的时候,在从硬盘上提取出来。 【活化】
如何让session的在一定时间内钝化:
做配置即可
1. 在tomcat里面 conf/context.xml 里面配置
对所有的运行在这个服务器的项目生效
2. 在conf/Catalina/localhost/context.xml 配置
对 localhost生效。 localhost:8080
3. 在自己的web工程项目中的 META-INF/context.xml
只对当前的工程生效。
maxIdleSwap : 1分钟不用就钝化
directory : 钝化后的那个文件存放的目录位置。 D:\tomcat\apache-tomcat-7.0.52\work\Catalina\localhost\项目名\配置 指定的目录 <Context>
<Manager className="org.apache.catalina.session.PersistentManager" maxIdleSwap="1">
<Store className="org.apache.catalina.session.FileStore" directory="配置指定的目录"/>
</Manager>
</Context>
Filter
过滤器 ,其实就是对客户端发出来的请求进行过滤。 浏览器发出, 然后服务器派servlet处理。 在中间就可以过滤, 其实过滤器起到的是拦截的作用。
作用
1. 对一些敏感词汇进行过滤
2. 统一设置编码
3. 自动登录
...
使用Filter
1. 定义一个类, 实现Filter
public class FilterDemo implements Filter {
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse
response, FilterChain chain) throws IOException, ServletException {
System.out.println("来到过虑器了。。。");
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
2. 注册过滤器
在web.xml里面注册,注册的手法与servlet基本一样。
<filter>
<display-name>FilterDemo</display-name>
<filter-name>FilterDemo</filter-name>
<filter-class>com.itheima.filter.FilterDemo</filter-class>
</filter>
<filter-mapping>
<filter-name>FilterDemo</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Filter的生命周期
* 创建 在服务器启动的时候就创建。
* 销毁 服务器停止的时候。
Filter执行顺序
1. 客户端发出请求,先经过过滤器, 如果过滤器放行,那么才能到servlet
2. 如果有多个过滤器, 那么他们会按照注册的映射顺序 来 排队。 只要有一个过滤器, 不放行,那么后面排队的过滤器以及咱们的servlet都不会收到请求。
Filter注意细节:
1. init方法的参数 FilterConfig , 可以用于获取filter在注册的名字 以及初始化参数。 其实这里的设计的初衷与ServletConfig是一样的。
2. 如果想放行,那么在doFilter 方法里面操作,使用参数 chain
chain.doFilter(request, response); 放行, 让请求到达下一个目标。
3. <url-pattern>/*</url-pattern> 写法格式与servlet一样。
1. 全路径匹配 以 / 开始
/LoginServlet
2. 以目录匹配 以 / 开始 以 * 结束
/demo01/*
3. 以后缀名匹配 以 * 开始 以后缀名结束
*.jsp *.html *.do
4. 配置中dispatcher字段的 设置
REQUEST : 只要是请求过来,都拦截,默认就是REQUEST
FORWARD : 只要是转发都拦截。
ERROR : 页面出错发生跳转
INCLUDE : 包含页面的时候就拦截。
自动登录示例:
登录servlet代码cookie有中文
request.setCharacterEncoding("utf-8");
try {
String username = request.getParameter("username");
String password = request.getParameter("password");
String autologin = request.getParameter("autologin");
System.out.println(username+password);
UserBean user = new UserBean();
user.setUsername(username);
user.setPassword(password);
UserDaoImpl daoImpl = new UserDaoImpl();
UserBean userBean = daoImpl.login(user);
if (userBean!=null) {
if ("on".equals(autologin)) {
Cookie cookie = new Cookie("autologin",
URLEncoder.encode(username+"#"+password, "utf-8"));
cookie.setMaxAge(60*60*24*7);
cookie.setPath("/FilterDemo");
response.addCookie(cookie);
}
request.getSession().setAttribute
("userBean",userBean);
response.sendRedirect("index.jsp");
}else {
request.getRequestDispatcher("login.jsp").forward
(request, response);
}
} catch (SQLException e) {
e.printStackTrace();
}
过滤器代码:
过滤器的核心不是完成拦截不给 , 还是放行显示。 它的核心是在放行之前,帮用户完成登录的功能。
思路:
1. 先判断session是否有效, 如果有效,就不用取cookie了,直接放行。
2. 如果session失效了,那么就取 cookie。
1. 没有cookie 放行
2. 有cookie
1. 取出来cookie的值,然后完成登录
2. 把这个用户的值存储到session中
3. 放行。
/**
* @see Filter#doFilter(ServletRequest, ServletResponse,
FilterChain)
*/
public void doFilter(ServletRequest req, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
try {
HttpServletRequest request = (HttpServletRequest) req;
//先判断,现在session中还有没有那个userBean.
UserBean userBean = (UserBean) request.getSession
().getAttribute("userBean");
//还有,有效。
if(userBean != null){
chain.doFilter(request, response);
}else{
//代表session失效了。
//2. 看cookie。
//1. 来请求的时候,先从请求里面取出cookie , 但是
cookie有很多的key-value
Cookie[] cookies = request.getCookies();
//2. 从一堆的cookie里面找出我们以前给浏览器发的那个
cookie
Cookie cookie = CookieUtil.findCookie(cookies,
"auto_login");
//第一次来
if(cookie == null){
chain.doFilter(request, response);
}else{
//不是第一次。
String value = cookie.getValue();
String username = value.split("#")[0];
String password = value.split("#")[1];
//完成登录
UserBean user = new UserBean();
user.setUsername(username);
user.setPassword(password);
UserDao dao = new UserDaoImpl();
userBean = dao.login(user);
//使用session存这个值到域中,方便下一次未过
期前还可以用。
request.getSession().setAttribute
("userBean", userBean);
chain.doFilter(request, response);
}
}
} catch (Exception e) {
e.printStackTrace();
chain.doFilter(req, response);
}
}
过滤器代码代码cookie有中文:
try {
HttpServletRequest req = (HttpServletRequest) request;
UserBean userBean = (UserBean) req.getSession
().getAttribute("userBean");
if (userBean!=null) {
chain.doFilter(request, response);
}else {
//session失效了
Cookie[] cookies = req.getCookies();
Cookie cookie = CookUtil.findCookie(cookies,
"autologin");
if (cookie==null) {
chain.doFilter(request, response);
}else {
String value = URLDecoder.decode
(cookie.getValue(), "utf-8");
String username = value.split("#")[0];
String password = value.split("#")[1];
UserBean bean = new UserBean();
bean.setUsername(username);
bean.setPassword(password);
UserDaoImpl daoImpl = new UserDaoImpl();
UserBean login = daoImpl.login(bean);
req.getSession().setAttribute("userBean",
login);
chain.doFilter(request, response);
}
}
} catch (Exception e) {
chain.doFilter(request, response);
e.printStackTrace();
}
BeanUtils的使用
BeanUtils.populate(bean, map);
//注册自己的日期转换器
ConvertUtils.register(new MyDateConverter(), Date.class);
//转化数据
Map map = request.getParameterMap();
UserBean bean = new UserBean();
转化map中的数据,放置到bean对象身上
BeanUtils.populate(bean, map);
总结
Listener
8个
三种类型
针对三个作用域的创建和销毁
针对三个作用域的值改变 【添加 | 替换 | 移除】
针对session中的值 【钝化 活化】 , 【绑定 解绑】
钝化 ( 序列化 )
内存中的对象存储到硬盘
超时失效。 session销毁了。
非正常关闭服务器, 钝化 。 正常关闭服务器 销毁
设置了session,多久时间。 context.xml
活化 (反序列化)
从硬盘里面读取到内存
ServletContextListner : 应用被部署的时候, 服务器加载这个项目的时候,做一些初始化工作, 任务调度。
HttpSessionListener : 统计在线人数
HttpSessionActivationListener : 钝化活化处理
Filter
1. 定义一个类,实现接口 Filter
2. 注册 . web.xml . 与servlet相似。
* 过滤器放行。
> chain.doFilter(request, response);
* 过滤器生命周期
创建: 服务器加载这个项目的时候创建实例,因为初始化可能有大量耗时工作
销毁: 关闭服务器或者从服务器中移除项目的时候。
06 Listener,Filter,BeanUtils的更多相关文章
- SpringBoot中使用Servlet,Filter,Listener
项目最近在替换之前陈旧的框架,改用SpringBoot进行重构,初接触,暂时还没有用到Servlet,Filter,Listener的地方,但在之前回顾Servlet的生命周期时,https://ww ...
- (八)map,filter,flatMap算子-Java&Python版Spark
map,filter,flatMap算子 视频教程: 1.优酷 2.YouTube 1.map map是将源JavaRDD的一个一个元素的传入call方法,并经过算法后一个一个的返回从而生成一个新的J ...
- python的map,filter,reduce学习
python2,python3中map,filter,reduce区别: 1,在python2 中,map,filter,reduce函数是直接输出结果. 2,在python3中做了些修改,输出前需要 ...
- Qt 事件系统浅析 (用 Windows API 描述,分析了QCoreApplication::exec()和QEventLoop::exec的源码)(比起新号槽,事件机制是更高级的抽象,拥有更多特性,比如 accept/ignore,filter,还是实现状态机等高级 API 的基础)
事件系统在 Qt 中扮演了十分重要的角色,不仅 GUI 的方方面面需要使用到事件系统,Signals/Slots 技术也离不开事件系统(多线程间).我们本文中暂且不描述 GUI 中的一些特殊情况,来说 ...
- python的 map,filter, reduce, enumerate
一, map #基本的map运用都可以用解析去替代,复杂的仍然需要定义函数,利用map去做 map(函数, 序列) 将序列的各项经过函数处理, 然后返回到一个新列表中. #itertools. ...
- JavaScript学习笔记(十)——高阶函数之map,reduce,filter,sort
在学习廖雪峰前辈的JavaScript教程中,遇到了一些需要注意的点,因此作为学习笔记列出来,提醒自己注意! 如果大家有需要,欢迎访问前辈的博客https://www.liaoxuefeng.com/ ...
- lambda表达式,filter,map,reduce,curry,打包与解包和
当然是函数式那一套黑魔法啦,且听我细细道来. lambda表达式 也就是匿名函数. 用法:lambda 参数列表 : 返回值 例: +1函数 f=lambda x:x+1 max函数(条件语句的写法如 ...
- Python 高阶函数map(),filter(),reduce()
map()函数,接收两个参数,一个是函数,一个是序列,map()把传入的函数依次作用于序列的每个元素,并把结果作为新的序列返回: aa = [1, 2, 3, 4, 5] print("ma ...
- Python3中高阶函数lambda,filter,map,reduce,zip的详细用法
在Python里有五大高阶函数,他们分别是lambda()匿名函数,filter()筛选函数,map()函数,reduce()函数,zip()函数.下面就让我们来详细的了解一下这五种函数的具体用法吧. ...
- python几个重要的函数(lambda,filter,reduce,map,zip)
一.匿名函数lambda lambda argument1,argument2,...argumentN :expression using arguments 1.lambda是一个表达式,而不是一 ...
随机推荐
- ubuntu12下安装eclipse+pydev +1搜索命令+kill指定进程
sudo apt-get install eclipse 下载pydev for eclipse 2.8,如果是jre6 解压. sudo nautilus 复制相应的文件夹到/usr/share/e ...
- 【SQL】glob 和 like 的区别
LIKE 和 GLOB 都可以用来匹配通配符指定模式的文本值.如果搜索表达式与模式表达式匹配,LIKE 运算符将返回真(true),也就是 1 区别: (1)使用的通配符不一样 like: 百分号( ...
- windows 常用dos命令
explorer目录 打开当前目录 explorer . 打开上级目录 explorer .. 打开任意目录 explorer dirname cls 命令 清屏屏幕,屏幕显示的所有字符信息都是存放在 ...
- learning ddr mode reigsters
For application flexibility, various functions, features, and modes are programmable in four Mode Re ...
- POJ 1837 Balance 水题, DP 难度:0
题目 http://poj.org/problem?id=1837 题意 单组数据,有一根杠杆,有R个钩子,其位置hi为整数且属于[-15,15],有C个重物,其质量wi为整数且属于[1,25],重物 ...
- Unity中物体碰撞后去掉相互之间的反弹力
最近自制了一个的角色控制器(没有重力的角色)时发现,角色碰撞到墙壁之后会有一个小小的反弹力导致角色有一个微弱的反弹位移,这样给人一种不好的感觉.研究了一下,除了限制坐标轴( Rigidbody---C ...
- SpringBoot技术点细解
SpringBoot(主流) SpringBoot简介核心点:1.敏捷开发,轻量级框架 , 弊端:封装太完美,不方便扩展 (但是高版本中的springboot是可以自定义的)2.无需tomcat (j ...
- vsts 管理 持续集成 跟自动化测试
1.代理池: 在服务器上,打开你的TFS Web站点,并转到管理页的代理池页面.如: https://www.cnblogs.com/atwind/p/5486881.html 低版本无法生成高版本. ...
- FPGA的GTP(aurora 协议)高速串行接口数据收发(转)
reference:https://blog.csdn.net/qq_40261818/article/details/83039829 PG046-Aurora 8B/10B Logicore I ...
- capjoint conversations with Chenweiwen
This event is quite small for teleseismic stations, which means it will be more strongly affected by ...