成都网站建设设计

将想法与焦点和您一起共享

MVC设计模式+过滤器与监听器-创新互联

MVC设计模式+过滤器与监听器 一、MVC设计模式 1.概念 - 代码的分层
字母表示理解
MModle模型层业务的具体实现
VView视图层展示数据
CController控制器层控制业务流程
2.细化理解层数

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

成都创新互联公司于2013年成立,先为鱼台等服务建站,鱼台等地企业,进行企业商务咨询服务。为鱼台企业网站制作PC+手机+微官网三网同步一站式服务解决您的所有建站问题。

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

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

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

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

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

}
案例:统计网站在线人数
@WebListener
public class ApplicationListener implements ServletContextListener{@Override
	public void contextInitialized(ServletContextEvent event) {//项目启动,向application对象中存一个变量,初始值0
		ServletContext application = event.getServletContext();  
		application.setAttribute("count", 0);
	}
	@Override
	public void contextDestroyed(ServletContextEvent event) {}
}

@WebListener
public class SessionListener implements HttpSessionListener {@Override
	public void sessionCreated(HttpSessionEvent event) {// 有人访问了 count++
		HttpSession session = event.getSession();
		ServletContext application = session.getServletContext();

		int count =(Integer) application.getAttribute("count");
		count++;
		application.setAttribute("count", count);
	}
	@Override
	public 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上下文对象新增值的时候被调用
	@Override
	public void attributeAdded(ServletContextAttributeEvent event) {String str = "Servlet上下文对象中添加了属性:"+event.getName()
            +",属性值是:"+event.getValue();
		System.out.println(str);
	}
 	//Servlet上下文对象删除值的时候被调用
	@Override
	public void attributeRemoved(ServletContextAttributeEvent event) {String str = "Servlet上下文对象中删除了属性:"+event.getName()
            +",属性值是:"+event.getValue();
		System.out.println(str);
	}
	//Servlet上下文对象替换值的时候被调用
	@Override
	public 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;
	}
	//钝化
	@Override
	public void sessionWillPassivate(HttpSessionEvent event) {System.out.println("对象被钝化......." + event.getSource());
	}
	//活化
	@Override
	public 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 都建立一个文件。

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


网站标题:MVC设计模式+过滤器与监听器-创新互联
网站URL:http://chengdu.cdxwcx.cn/article/hgjij.html