第9章 过滤器和监听器
9.1 Servlet过滤器
9.1.1 什么的过滤器
9.1.2 过滤器核心对象
- Filter 接口
public class LogFilter implements Filter {}
方法声明 | 说明 |
---|---|
public void init(FilterConfig config) throws ServletException |
过滤器初始化方法,该方法在过滤器初始化时调用 |
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain) throws IOException,ServletException |
对请求进行过滤处理 |
public void destory |
销毁方法以便释放资源 |
*FilterConfig 接口
方法声明 | 说明 |
---|---|
public String getFilterName() |
获取过滤器名字 |
public ServletContext getServletContext |
或是 Servlet上下文 |
public String getInitParameter(String arg0) |
获取过滤器初始化参数值 |
public Enumeration getInitParameterNames() |
获取过滤器所有初始化参数 |
- FilterChain 接口
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
}
9.1.3 过滤器创建和配置
- 创建
public class MyFilter implements Filter{
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
}
@Override
public void init(FilterConfig arg0) throws ServletException {
}
}
- 配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<filter>
<filter-name>LogFilter</filter-name>
<filter-class>com.runoob.test.LogFilter</filter-class>
<init-param>
<param-name>Site</param-name>
<param-value>菜鸟教程</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>LogFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
示例代码
统计站点访问次数,初始化访问值为5000
*MyFilter.java
package com.hwp.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
public class MyFilter implements Filter{
private int count;
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException {
//访问量自增
count++;
HttpServletRequest httpServletRequest=(HttpServletRequest)arg0;
ServletContext context= httpServletRequest.getSession().getServletContext();
//将来访数量传递到 ServletContext中
context.setAttribute("count", count);
//向下传递过滤器
arg2.doFilter(arg0, arg1);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
//初始化参数
String param=arg0.getInitParameter("count");
//将字符串转换为 int
count=Integer.valueOf(param);
}
}
-
web.xml
配置
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<filter>
<filter-name>MyFilter</filter-name>
<filter-class>com.hwp.filter.MyFilter</filter-class>
<init-param>
<param-name>count</param-name>
<param-value>5000</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
web.xml配置各节点说明
- <filter>指定一个过滤器。
- <filter-name>用于为过滤器指定一个名字,该元素的内容不能为空。
- <filter-class>元素用于指定过滤器的完整的限定类名。
- <init-param>元素用于为过滤器指定初始化参数,它的子元素<param-name>指定参数的名字,<param-value>指定参数的值。
在过滤器中,可以使用FilterConfig接口对象来访问初始化参数。
- <filter-mapping>元素用于设置一个 Filter 所负责拦截的资源。一个Filter拦截的资源可通过两种方式来指定:Servlet 名称和资源访问的请求路径
- <filter-name>子元素用于设置filter的注册名称。该值必须是在<filter>元素中声明过的过滤器的名字
- <url-pattern>设置 filter 所拦截的请求路径(过滤器关联的URL样式)
- <servlet-name>指定过滤器所拦截的Servlet名称。
- <dispatcher>指定过滤器所拦截的资源被 Servlet 容器调用的方式,可以是REQUEST,INCLUDE,FORWARD和ERROR之一,默认REQUEST。用户可以设置多个<dispatcher>子元素用来指定 Filter 对资源的多种调用方式进行拦截。
- <dispatcher>子元素可以设置的值及其意义
- REQUEST:当用户直接访问页面时,Web容器将会调用过滤器。如果目标资源是通过RequestDispatcher的include()或forward()方法访问时,那么该过滤器就不会被调用。
- INCLUDE:如果目标资源是通过RequestDispatcher的include()方法访问时,那么该过滤器将被调用。除此之外,该过滤器不会被调用。
- FORWARD:如果目标资源是通过RequestDispatcher的forward()方法访问时,那么该过滤器将被调用,除此之外,该过滤器不会被调用。
- ERROR:如果目标资源是通过声明式异常处理机制调用时,那么该过滤器将被调用。除此之外,过滤器不会被调用。
*index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
</head>
<body>
<h2>
您是本站第<%= application.getAttribute("count")%>位访客!
</h2>
</html>
9.1.4 字符编码过滤器
index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>图书添加</title>
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<form action="BookServlet" method="post">
<table border="1" bordercolor="#66B3FF">
<tr >
<td align="center" colspan="2">图书添加信息</td>
</tr>
<tr>
<td>图书编号:</td>
<td><input type="text" name="num"/></td>
</tr>
<tr>
<td>图书名称:</td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>作者:</td>
<td><input type="text" name="author"/></td>
</tr>
<tr>
<td>价格:</td>
<td><input type="text" name="price"/></td>
</tr>
<tr>
<td align="center" colspan="2"><input type="submit" value="添加"/></td>
</tr>
</table>
</form>
</body>
</html>
BookServlet.jsva
package com.hwp;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class BookServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public BookServlet() {
super();
}
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter printWriter = response.getWriter();
String num=request.getParameter("num");
String name=request.getParameter("name");
String author=request.getParameter("author");
String price=request.getParameter("price");
printWriter.print("<h2>图书信息添加成功</h2><hr>");
printWriter.print("图书编号:"+num+"<br>");
printWriter.print("书名:"+name+"<br>");
printWriter.print("作者:"+author+"<br>");
printWriter.print("价格:"+price+"<br>");
printWriter.flush();
printWriter.close();
}
public void init() throws ServletException {
}
}
*AddFilter.java
package com.hwp;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public class AddFilter implements Filter {
String encoding = null;
public void destroy() {
encoding = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain arg2) throws IOException, ServletException {
if (encoding != null) {
request.setCharacterEncoding(encoding);
response.setContentType("text/html; charset=" + encoding);
}
arg2.doFilter(request, response);
}
@Override
public void init(FilterConfig arg0) throws ServletException {
encoding = arg0.getInitParameter("encoding");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
<web-app>
<filter>
<filter-name>AddFilter</filter-name>
<filter-class>com.hwp.AddFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>AddFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>BookServlet</servlet-name>
<display-name>This is the display name of my J2EE component</display-name>
<description>This is the description of my J2EE component</description>
<servlet-class>com.hwp.BookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookServlet</servlet-name>
<url-pattern>/BookServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
9.2 Servlet监听器
9.2.1 Servlet监听器简介
- Listener
序号 | 接口 |
---|---|
1 | ServletContextListener |
2 | ServletContextAttributeListener |
3 | HttpSessionListener |
4 | HttpSessionActivationListener |
5 | HttpSessionAttributrListener |
6 | HttpSessionBindingListener |
7 | ServletRequestListener |
8 | ServletRequestAttributeListener |
- Event
序号 | 接口 |
---|---|
1 | ServletContextEvent |
2 | ServletContextAttributeEvent |
3 | HttpSessionEvent |
4 | HttpSessionRequestEvent |
5 | HttpSessionAttributeEvent |
6 | HttpSessionBindingEvent |
9.2.2 Servlet监听器原理
9.2.3 Servlet上下文监听
public class MyListener implements ServletContextListener {
//通知正在收听的对象,应用程序已经被载出,即关闭
@Override
public void contextDestroyed(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
//通知正在收听的对象,应用程序已经被加载,即初始化
@Override
public void contextInitialized(ServletContextEvent arg0) {
// TODO Auto-generated method stub
}
}
-
web.xml
配置监听器才有用
<listener>
<listener-class>com.hwp.MyListener</listener-class>
</listener>
网友评论