“J2EE高级编程”笔记(六)

Filter

一个检测用户是否登录的过滤器:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
import java.io.*;
import java.servlet.*;
import java.servlet.http.*;
public class FirstFilter implements Filter {
private FilterConfig config;
public void destroy() {}
public void init(FilterConfig config) {
}
//主要操作都在这里进行
public void doFilter(ServletRequest arg0,
ServletRespond arg1, FilterChain arg2)
throws ServletException, IOException {
HttpServletRequest request =
(HttpServletRequest) arg0;
//会话
HttpSession session = request.getSession();
String s = (String) session.getAttrible("login");
if (s == null) {
request.getRequsetDispatcher("/login.html");
return;
}
if (s.equals("true")) {
arg2.doFilter(arg0, arg1);
} else {
request.getRequestDispatcher("/login.html");
}
}
}

一个用于检测程序运行时间的过滤器:

1
2
3
4
5
6
7
8
9
…………
public void doFilter(ServletRequest req, ServletRequest res,
FilterChain chain) throws ... {
long start = System.currentTimeMillis();
chain.doFilter(req, res);
long end = System.currentTimeMillis();
System.out.println("cost:" + (end-start));
}
…………

注意过滤器也要在web.xml里注册:

<filter-mapping>
<filter-name>f4</filter-name>
<servlet-name>DownloadServlet</servlet-name>
</filter-mapping>

<filter-mapping>
<filter-name>f4</filter-name>
<url-pattern>/servlet/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>

DispatcherType共有五种:ASYNC, ERROR, FORWARD, INCLUDE, REQUEST。各个Type的含义请参考文档。

关于web.xml里各节点的含义,可以参考菜鸟教程-Servlet编写过滤器


Listener

每个Listener对应一个Event。

以下是一个访问数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//监听Context的创建与销毁
public class InitConnectionListener
implements ServletContextListener {
//初始化context时调用。在这里用来建立数据库连接
public void contextInitialized(ServletContextEvent e) {
//以下代码属于JavaSE的内容。
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost/test",
"java",
"java12345"
);
ServletContext context = e.getServletContext();
//设置connextion,这样才能再销毁时获取连接
context.setAttribute("connection", con);
}
//销毁context时调用
public void contextDestroyed(ServletContextEvent e) {
//销毁数据库连接
Connection con = (Connection) e.getServletContext
.getAttribute("connection");
con.close();
}
}

这一节老师讲得并不完整,更详细的内容可以参见监听器Listener详解