字母 | 表示 | 层 | 理解 |
---|---|---|---|
M | Modle | 模型层 | 业务的具体实现 |
V | View | 视图层 | 展示数据 |
C | Controller | 控制器层 | 控制业务流程 |
View:视图层,用于存放前端页面
Controller:控制器层,用于存放Servlet(属于中间商)
Modle-Biz/Service:逻辑业务层,用于存放业务具体的实现
Modle-Dao/Mapper:数据持久层,用于存放操作数据的实现
缺点:使用MVC不能减少代码量, 增加系统结构和实现的复杂性
优点:整个项目结构清晰,业务逻辑清晰,降低了代码的耦合性,代码的重用性高
Controller控制器层:controller/servlet/action/web
Modle-Biz 逻辑业务层:service/biz
Modle-Dao 数据持久层:dao/persist/mapper
Filter:过滤器,通过Filter可以拦截访问web资源的请求与响应操作。
Servlet API中提供了一个Filter接口,开发web应用时,如果编写的Java类实现了这个接口,则把这个java类称之为过滤器。他可以拦截Jsp、Servlet、 静态图片文件、静态 html文件等,从而实现一些特殊的功能。
例如:实现URL级别的权限访问控制、过滤敏感词汇、压缩响应信息等一些高级功能。
javax.servlet.Filter接口中的方法介绍:
方法 描述 init(FilterConfig fConfig) 初始化方法 doFilter(ServletRequest request, ServletResponse response, FilterChain chain) 过滤方法 destroy() 销毁方法
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() {}
}
Filter01 com.dream.filter.Filter01 Filter01 /*
客户端对服务器请求之后,服务器在调用Servlet之前,会执行一组过滤器(多个过滤器),那么这组过滤器就称为一条过滤器链。
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配置文件中配置过滤器信息
Filter01 com.dream.filter.Filter01 Filter01 /*
创建顺序:创建顺序无序
执行顺序:按照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配置文件中配置过滤器信息
Filter01 com.dream.filter.Filter01 Filter01 /* Filter02 com.dream.filter.Filter02 Filter02 /* Filter03 com.dream.filter.Filter03 Filter03 /*
解决请求和响应乱码问题
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() {}
}
EncodeFilter com.dream.filter.EncodeFilter encode UTF-8 EncodeFilter /*
解决权限的统一控制问题,没有登录,就不能直接跳转到其他详情页面
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() {}
}
LoginFilter com.dream.filter.LoginFilter LoginFilter /*
解决文档内的一个敏感词汇
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;}}
}
SensitiveWordsFilter com.dream.filter.SensitiveWordsFilter SensitiveWordsFilter /*
@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 {...
}
监听器用于监听web应用中某些对象信息的创建、销毁、增加,修改,删除等动作的
发生,然后作出相应的响应处理。当范围对象的状态发生变化的时候,服务器自动调用
监听器对象中的方法。
常用于统计在线人数和在线用户,系统加载时进行信息初始化,统计网站的访问量等。
- 创建类
- 实现指定的监听器接口中的方法
- 在web.xml文件中配置监听/在类上标注@WebListener 注解
监听域对象 创建与销毁的监听器
监听器接口 | 描述 |
---|---|
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);}
}
监听域对象属性变化的监听器
监听器接口 | 描述 |
---|---|
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);}
}
前两类监听器是作用在 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文件
钝化:当服务器正常关闭时,还存活着的session(在设置时间内没有销毁) 会随着服务器的关闭被以文件(“SESSIONS.ser”)的形式存储在tomcat 的work 目录下,这个过程叫做Session 的钝化。
活化:当服务器再次正常开启时,服务器会找到之前的“SESSIONS.ser” 文件,从中恢复之前保存起来的Session 对象,这个过程叫做Session的活化。
注意事项
- 想要随着Session 被钝化、活化的对象它的类必须实现Serializable 接口,还有的是只有在服务器正常关闭的条件下,还未超时的Session 才会被钝化成文件。当Session 超时、调用invalidate方法或者服务器在非正常情况下关闭时,Session 都不会被钝化,因此也就不存在活化。
- 在被钝化成“SESSIONS.ser” 文件时,不会因为超过Session 过期时间而消失,这个文件会一直存在,等到下一次服务器开启时消失。
- 当多个Session 被钝化时,这些被钝化的Session 都被保存在一个文件中,并不会为每个Session 都建立一个文件。
上一篇:分水果(冬季每日一题 21)
下一篇:c语言编程函数名:b开头