MVC设计模式+过滤器与监听器
admin
2024-03-14 21:18:10
0

MVC设计模式+过滤器与监听器

一、MVC设计模式

1.概念 - 代码的分层

字母表示理解
MModle模型层业务的具体实现
VView视图层展示数据
CController控制器层控制业务流程

2.细化理解层数

View:视图层,用于存放前端页面

Controller:控制器层,用于存放Servlet(属于中间商)

Modle-Biz/Service:逻辑业务层,用于存放业务具体的实现

Modle-Dao/Mapper:数据持久层,用于存放操作数据的实现

3.优缺点

缺点:使用MVC不能减少代码量, 增加系统结构和实现的复杂性

优点:整个项目结构清晰,业务逻辑清晰,降低了代码的耦合性,代码的重用性高

4.各层的命名规范

Controller控制器层:controller/servlet/action/web

Modle-Biz 逻辑业务层:service/biz

Modle-Dao 数据持久层:dao/persist/mapper

二、Filter过滤器

1.简介

Filter:过滤器,通过Filter可以拦截访问web资源的请求与响应操作。

Servlet API中提供了一个Filter接口,开发web应用时,如果编写的Java类实现了这个接口,则把这个java类称之为过滤器。他可以拦截Jsp、Servlet、 静态图片文件、静态 html文件等,从而实现一些特殊的功能。

例如:实现URL级别的权限访问控制、过滤敏感词汇、压缩响应信息等一些高级功能。

2.创建步骤

javax.servlet.Filter接口中的方法介绍:

方法描述
init(FilterConfig fConfig)初始化方法
doFilter(ServletRequest request, ServletResponse response, FilterChain chain)过滤方法
destroy()销毁方法

1.创建过滤器类并实现Filter接口

public class Filter01 implements Filter {public Filter01() {}public void init(FilterConfig fConfig) throws ServletException {}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {//chain过滤器链//注意:如果拦截后不调用doFilter(),请求将无法传到下一个过滤器或服务器里//chain.doFilter(request, response);//放行}public void destroy() {}
}

2.在web.xml配置文件中配置过滤器信息

  Filter01com.dream.filter.Filter01Filter01/*

3.过滤器链

客户端对服务器请求之后,服务器在调用Servlet之前,会执行一组过滤器(多个过滤器),那么这组过滤器就称为一条过滤器链。

4.生命周期 - 单个过滤器

1.单个过滤器的生命周期:

项目启动时创建Filter01对象,调用Filter01()、init()

  	2. 因为此过滤器配置的是所有请求拦截,所以发送请求时,调用doFilter()3. 项目更新或销毁时,调用destroy()

1.创建过滤器类并实现Filter接口

public class Filter01 implements Filter {public Filter01() {System.out.println("Filter01 - Filter01()");}public void init(FilterConfig fConfig) throws ServletException {System.out.println("Filter01 - init()");}//doFilter(请求,响应,过滤器链)public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {System.out.println("Filter01执行前");chain.doFilter(request, response);//放行System.out.println("Filter01执行后");}public void destroy() {System.out.println("Filter01 - destroy()");}
}

2.在web.xml配置文件中配置过滤器信息

  Filter01com.dream.filter.Filter01Filter01/*

5.生命周期 - 多个过滤器

创建顺序:创建顺序无序

执行顺序:按照web.xml中配置的顺序执行

1.创建过滤器类并实现Filter接口

//----------- Filter01 -----------------------
public class Filter01 implements Filter {public Filter01() {System.out.println("Filter01 - Filter01()");}public void init(FilterConfig fConfig) throws ServletException {System.out.println("Filter01 - init()");}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {System.out.println("Filter01执行前");chain.doFilter(request, response);//放行System.out.println("Filter01执行后");}public void destroy() { System.out.println("Filter01 - destroy()");}
}
//----------- Filter02 -----------------------
public class Filter02 implements Filter {public Filter02() {System.out.println("Filter02 - Filter02()");}public void init(FilterConfig fConfig) throws ServletException {System.out.println("Filter02 - init()");}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {System.out.println("Filter02执行前");chain.doFilter(request, response);//放行System.out.println("Filter02执行后");}public void destroy() { System.out.println("Filter02 - destroy()");}
}
//----------- Filter03 -----------------------
public class Filter03 implements Filter {public Filter03() {System.out.println("Filter03 - Filter03()");}public void init(FilterConfig fConfig) throws ServletException {System.out.println("Filter03 - init()");}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {System.out.println("Filter03执行前");chain.doFilter(request, response);//放行System.out.println("Filter03执行后");}public void destroy() { System.out.println("Filter03 - destroy()");}
}

2.在web.xml配置文件中配置过滤器信息

  Filter01com.dream.filter.Filter01Filter01/*Filter02com.dream.filter.Filter02Filter02/*Filter03com.dream.filter.Filter03Filter03/*

6.案例一:编码过滤器

解决请求和响应乱码问题

public class EncodeFilter implements Filter {private String encode;public void init(FilterConfig fConfig) throws ServletException {//获取web.xml中该过滤器的初始化属性encode = fConfig.getInitParameter("encode");}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request;HttpServletResponse resp = (HttpServletResponse) response;resp.setContentType("text/html;charset="+encode);req.setCharacterEncoding(encode);chain.doFilter(req, resp);}public void destroy() {}
}
  EncodeFiltercom.dream.filter.EncodeFilterencodeUTF-8EncodeFilter/*

7.案例二:登录权限过滤器

解决权限的统一控制问题,没有登录,就不能直接跳转到其他详情页面

   public class LoginFilter implements Filter {public void init(FilterConfig fConfig) throws ServletException {}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {HttpServletRequest req = (HttpServletRequest) request;HttpServletResponse resp = (HttpServletResponse) response;//获取请求地址String uri = req.getRequestURI();//获取请求链接的Get数据String queryString = request.getQueryString();if(queryString == null){queryString = "";}if(uri.contains("welcome.jsp") ||uri.contains("login.jsp") || uri.contains("register.jsp") || queryString.contains("action=login") || queryString.contains("action=register")){chain.doFilter(request, response);}else{HttpSession session = req.getSession();String user = (String) session.getAttribute("user");if(user == null){//没登录过resp.sendRedirect("login.jsp");}else{//登录过chain.doFilter(request, response);}}}public void destroy() {}
}
LoginFiltercom.dream.filter.LoginFilterLoginFilter/*

8.案例三:关键字过滤器

解决文档内的一个敏感词汇

public class SensitiveWordsFilter implements Filter {public void init(FilterConfig fConfig) throws ServletException {}public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {chain.doFilter(new MyHttpServletRequestWapper((HttpServletRequest) request), response);//放行}public void destroy() { }///请求包装类class MyHttpServletRequestWapper extends HttpServletRequestWrapper{public MyHttpServletRequestWapper(HttpServletRequest request) {super(request);}@Overridepublic String getParameter(String name) {String value = super.getParameter(name);value = value.replaceAll("傻逼", "**");//把尖括号替换成字符尖括号,替换后不会认为是html里的尖括号符号value = value.replaceAll("<", "<");value = value.replaceAll(">", ">");return value;}}
}
  SensitiveWordsFiltercom.dream.filter.SensitiveWordsFilterSensitiveWordsFilter/*

9.注解配置过滤器(简化配置)

@WebFilter(

​ value=“/*”,

​ initParams= {@WebInitParam(name = “encode”, value = “UTF-8”),

​ @WebInitParam(name = “name”, value = “java”)}

)

创建顺序:创建顺序无序

执行顺序:按照类名的顺序执行

@WebFilter(value="/*",initParams={@WebInitParam(name="encode",value="UTF-8")})
public class EncodeFilter implements Filter {...
}

三、监听器

1.概念

监听器用于监听web应用中某些对象信息的创建、销毁、增加,修改,删除等动作的

发生,然后作出相应的响应处理。当范围对象的状态发生变化的时候,服务器自动调用

监听器对象中的方法。

常用于统计在线人数和在线用户,系统加载时进行信息初始化,统计网站的访问量等。

2.创建步骤

  1. 创建类
  2. 实现指定的监听器接口中的方法
  3. 在web.xml文件中配置监听/在类上标注@WebListener 注解

3.第一类:域对象监听器

监听域对象 创建与销毁的监听器

监听器接口描述
ServletContextListener监听Servlet上下文对象的创建、销毁
HttpSessionListener监听会话对象的创建、销毁
ServletRequestListener监听请求对象的创建、销毁

Servlet上下文对象 创建和销毁的监听器

public class ApplicationListener implements ServletContextListener {	//Servlet上下文对象创建的时候被调用@Overridepublic void contextInitialized(ServletContextEvent contextEvent) {System.out.println("Servlet上下文对象被创建啦...");//项目一旦启动,此处代码运行!Timer timer=new Timer();//5秒钟之后开始执行,以后每间隔2秒发送一封邮件!timer.schedule(new TimerTask() {@Overridepublic void run() {//System.out.println("发邮件...."+new Date());}}, 5000, 2000);}//Servlet上下文对象销毁的时候被调用@Overridepublic void contextDestroyed(ServletContextEvent contextEvent) {System.out.println("Servlet上下文对象被销毁啦...");//服务器在停止的时候,要执行某些动作,那么就可以把代码写在这个位置!!!	}
}

com.dream.listener.ApplicationListener

会话对象 创建和销毁的监听器

@WebListener
public class SessionListener implements HttpSessionListener{@Overridepublic void sessionCreated(HttpSessionEvent event) {HttpSession session = event.getSession();System.out.println("session对象创建啦...."+session.getId());}@Overridepublic void sessionDestroyed(HttpSessionEvent event) {HttpSession session = event.getSession();System.out.println("session对象销毁啦...."+session.getId());}
}

请求对象的创建和销毁的监听器

@WebListener
public class RequestListener implements ServletRequestListener{@Overridepublic void requestInitialized(ServletRequestEvent event) {ServletRequest request = event.getServletRequest();System.out.println("Request对象的创建...."+request);}@Overridepublic void requestDestroyed(ServletRequestEvent event) {ServletRequest request = event.getServletRequest();System.out.println("Request对象的销毁...."+request);}}

案例:统计网站在线人数

@WebListener
public class ApplicationListener implements ServletContextListener{@Overridepublic void contextInitialized(ServletContextEvent event) {//项目启动,向application对象中存一个变量,初始值0ServletContext application = event.getServletContext();  application.setAttribute("count", 0);}@Overridepublic void contextDestroyed(ServletContextEvent event) {}
}@WebListener
public class SessionListener implements HttpSessionListener {@Overridepublic void sessionCreated(HttpSessionEvent event) {// 有人访问了 count++HttpSession session = event.getSession();ServletContext application = session.getServletContext();int count =(Integer) application.getAttribute("count");count++;application.setAttribute("count", count);}@Overridepublic void sessionDestroyed(HttpSessionEvent event) {// 有人离开了 count--HttpSession session = event.getSession();ServletContext application = session.getServletContext();Integer count =(Integer) application.getAttribute("count");count--;application.setAttribute("count", count);}
}

4.第二类:属性监听器

监听域对象属性变化的监听器

监听器接口描述
ServletContextAttributeListener监听Servlet上下文对象属性的创建、删除、替换
HttpSessionAttributeListener监听会话对象属性的创建、删除、替换
ServletRequestAttributeListener监听请求对象属性的创建、删除、替换

Servlet上下文对象属性变化的监听器

@WebListener
public class ApplicationAttributeListener implements ServletContextAttributeListener{//Servlet上下文对象新增值的时候被调用@Overridepublic void attributeAdded(ServletContextAttributeEvent event) {String str = "Servlet上下文对象中添加了属性:"+event.getName()+",属性值是:"+event.getValue();System.out.println(str);}//Servlet上下文对象删除值的时候被调用@Overridepublic void attributeRemoved(ServletContextAttributeEvent event) {String str = "Servlet上下文对象中删除了属性:"+event.getName()+",属性值是:"+event.getValue();System.out.println(str);}//Servlet上下文对象替换值的时候被调用@Overridepublic void attributeReplaced(ServletContextAttributeEvent event) {String str = "Servlet上下文对象中替换了属性:"+event.getName()+",属性值是:"+event.getValue();System.out.println(str);}
}

5.第三类:监听HttpSession中的对象(JavaBean)

前两类监听器是作用在 ServletContext HttpSession ServletRequest上

第三类监听器是作用在JavaBean上的。

注意:这类监听器不需要在web.xml中配置

监听器接口描述
HttpSessionBindingListener监听会话对象中JavaBean对象的绑定、删除
HttpSessionActivationListener监听会话对象中JavaBean对象的钝化、活化

会话对象中JavaBean对象的绑定和删除的监听器

实现了HttpSessionBindingListener接口的JavaBean对象可以感知自己被绑定到Session中和 Session中删除的事件

  • 当对象被绑定到HttpSession对象中时,web服务器调用该对象的

void valueBound(HttpSessionBindingEvent event)方法

  • 当对象从HttpSession对象中解除绑定时,web服务器调用该对象的

void valueUnbound(HttpSessionBindingEvent event)方法

public class User implements HttpSessionBindingListener {private int id;private String name;public User() {}public User(int id, String name) {this.id = id;this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}public void valueBound(HttpSessionBindingEvent event) {System.out.println("对象绑定到了Session中");}public void valueUnbound(HttpSessionBindingEvent event) {System.out.println("对象从Session中移除");}
}
<%@ page import="com.dream.vo.User"%>
<%@ page language="java" pageEncoding="UTF-8"%>



ServletContextAttributeListener监听器测试

<%User user = new User(1, "aaa");session.setAttribute("user", user);session.removeAttribute("user");%>

会话对象中JavaBean对象的钝化和活化的监听器

实现了HttpSessionActivationListener接口的JavaBean对象可以感知自己被活化(反序列化)和钝化(序列化)的事件

钝化(序列化):在内存中JavaBean对象通过Session存储硬盘的过程

活化(反序列化):从硬盘中通过Session取出JavaBean对象到内存的过程

  • javabean对象将要随Session对象被钝化(序列化)之前,web服务器调用该对象的

void sessionWillPassivate(HttpSessionEvent event) 方法

这样javabean对象就可以知道自己将要和Session对象一起被钝化到硬盘中

  • javabean对象将要随Session对象被活化(反序列化)之后,web服务器调用该对象的void sessionDidActive(HttpSessionEvent event)方法

这样javabean对象就可以知道自己将要和Session对象一起被活化回到内存中

注意: 想要随着Session 被钝化、活化的对象它的类必须实现Serializable 接口,放在

Session中没有实现Serilizable接口的对象,在Session钝化时,不会被序列化到磁盘上。

public class User implements Serializable, HttpSessionActivationListener{private static final long serialVersionUID = -1566395353697458460L;private int id;private String name;public User() {}public User(int id, String name) {this.id = id;this.name = name;}public int getId() {return id;}public void setId(int id) {this.id = id;}public String getName() {return name;}public void setName(String name) {this.name = name;}//钝化@Overridepublic void sessionWillPassivate(HttpSessionEvent event) {System.out.println("对象被钝化......." + event.getSource());}//活化@Overridepublic void sessionDidActivate(HttpSessionEvent event) {System.out.println("对象被活化......");}
}

在WebContent\META-INF文件夹下创建一个context.xml文件



	

6.面试题:Session 的钝化与活化

  • 钝化:当服务器正常关闭时,还存活着的session(在设置时间内没有销毁) 会随着服务器的关闭被以文件(“SESSIONS.ser”)的形式存储在tomcat 的work 目录下,这个过程叫做Session 的钝化。

  • 活化:当服务器再次正常开启时,服务器会找到之前的“SESSIONS.ser” 文件,从中恢复之前保存起来的Session 对象,这个过程叫做Session的活化。

  • 注意事项

  1. 想要随着Session 被钝化、活化的对象它的类必须实现Serializable 接口,还有的是只有在服务器正常关闭的条件下,还未超时的Session 才会被钝化成文件。当Session 超时、调用invalidate方法或者服务器在非正常情况下关闭时,Session 都不会被钝化,因此也就不存在活化。
  2. 在被钝化成“SESSIONS.ser” 文件时,不会因为超过Session 过期时间而消失,这个文件会一直存在,等到下一次服务器开启时消失。
  3. 当多个Session 被钝化时,这些被钝化的Session 都被保存在一个文件中,并不会为每个Session 都建立一个文件。

相关内容

热门资讯

原创 别... 在繁忙的都市生活中,我们常常渴望寻找一种简单而美味的点心来慰藉自己的心灵。今天,我将与大家分享一道简...
原创 到... 标题:到新开的饭馆吃饭,老板说吃完打七折,上菜后知道他为啥奸笑了! 在美食的世界里,每一次用餐都是...
年轻人为什么偏爱“市井小店”? 图为正在沣元春饼馆内用餐的消费者。 “我是冲着‘必吃榜’的名头过来的。这家店虽然位置隐蔽,七拐八拐才...
原创 1... 标题:1把韭菜1把粉条,做成饼,竟如此快手又好吃,早上不用只啃面包了。 在忙碌的早晨,我们总是渴望...
原创 吐... 吐司,这个看似简单的早餐选择,其实蕴含着无限的可能性。今天,我将带领大家探索一种无需手套膜也能拉丝的...
精彩的近义词。 精彩的近义词。精彩近义词:出色,漂亮
朵拉小羊在羊奶粉排行第几,请问... 朵拉小羊在羊奶粉排行第几,请问宝妈们这款奶粉怎么样?朵拉小羊在羊奶粉排行榜中的排名一直都挺靠前的,挺...
塞尔达传说荒野之息怎么获得武器... 塞尔达传说荒野之息怎么获得武器?前期武器入手方法一览《塞尔达传说:荒野之息》很多玩家都吐槽赠送武器坏...
口袋妖怪复刻精灵性格能改变吗? 口袋妖怪复刻精灵性格能改变吗?口袋妖怪复刻精灵性格能改变哦,后期可能通过进化来改变哦固定交换能哪来刷...
女人爱上一个人和男人爱上一个人... 女人爱上一个人和男人爱上一个人,有哪些不一样吗?男人和女人是两个完全不同的有机体,在思维、心理和行为...
《哆啦A梦》中哪个片段让你感动... 《哆啦A梦》中哪个片段让你感动?每一集都有精彩的一部分哆啦A 梦真的是陪伴了大雄很久哆啦A梦要回去的...
求不祥之刃符文选择 求不祥之刃符文选择红法穿,蓝减cd,黄成长血,精华法穿,不详前期qe技能陪和法术穿透是很强势的,应为...
超级教师是什么台播放的 超级教师是什么台播放的,乐视TV电视台放超级教师是乐视出品,只能在乐视TV看!
有什么搞笑好看的鬼片? 有什么搞笑好看的鬼片?韩国片主君的太阳!
摘橘子沈从文中夭夭是一个什么样... 摘橘子沈从文中夭夭是一个什么样的女孩摘橘子沈从文中夭夭是一个什么样的女孩?相关内容如下:夭夭是《边城...
作文题目:童心荟萃.主题;节水... 作文题目:童心荟萃.主题;节水。爱水。护水~~╮(╯▽╰)╭ ...
我可不可以和姐夫家的堂兄弟结婚... 我可不可以和姐夫家的堂兄弟结婚?这个是没问题的,不是三代内有血亲关系的都可以
原生家庭对人的影响很大,如何摆... 原生家庭对人的影响很大,如何摆脱原生家庭所造成的性格缺陷?在学校里好好学习,尽量不要被原生家庭的坏习...
你知道哪些珍惜时间的名人故事吗... 你知道哪些珍惜时间的名人故事吗?1、悬梁刺股东汉时候,有个人名叫孙敬,是著名的政治家。他年轻时勤奋好...
有一首歌,歌词里铿锵玫瑰,作何... 有一首歌,歌词里铿锵玫瑰,作何解释?铿 锵 玫 瑰"铿锵"意味着声音宏亮,节奏分明;"玫瑰"代表着美...