Filter
过滤器
完成通用的操作
案例:登录验证
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
// 强制转换
HttpServletRequest request = (HttpServletRequest) req;
// 获取资源请求路径
String uri = request.getRequestURI();
// 判断是否包含登录的相关资源路径
if (uri.contains("/login.jsp") || uri.contains("/loginServlet") || uri.contains("/css/") || uri.contains("/js/") || uri.contains("/fonts/") || uri.contains("/checkCode")) {
chain.doFilter(req, resp);
} else{
// 要登录,需验证
Object user = request.getSession().getAttribute("user");
if (user != null) {
// 有数据,放行
chain.doFilter(req,resp);
} else {
// 没有数据,跳转页面
request.setAttribute("login_msg","你尚未登录,请登录!");
request.getRequestDispatcher("/login.jsp").forward(request,resp);
}
}
}
案例:敏感字符过滤
增强对象功能:
设计模式:1.装饰模式,2.代理模式
下面代码演示代理模式
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
// 创建代理商对象
ServletRequest proxy_req = (ServletRequest) Proxy.newProxyInstance(req.getClass().getClassLoader(), req.getClass().getInterfaces(), new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
// 增强getParameter方法
// 判断是否是getParameter方法
if (method.getName().equals("getParameter")) {
String value = (String) method.invoke(req,args);
if (value != null) {
for (String str : list) {
if (value.contains(str)) {
value = value.replaceAll(str,"***");
}
}
}
return value;
}
// 如果不是,照常执行
return method.invoke(req,args);
}
});
chain.doFilter(proxy_req, resp);
}
先加载
private List<String> list = new ArrayList<String>();
public void init(FilterConfig config) throws ServletException {
try {
// 获取文件真实路径
ServletContext servletContext = config.getServletContext();
String realPath = servletContext.getRealPath("/WEB-INF/classes/敏感词汇.txt");
// 读取文件
BufferedReader br = new BufferedReader(new FileReader(realPath));
String line = null;
while ((line = br.readLine())!=null) {
list.add(line);
}
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Listener
监听器
注册监听:事件源上发生某件事件后,执行监听器代码
ServletContextListener
@WebListener
public class ContextLoaderListener implements ServletContextListener {
@Override
public void contextInitialized(ServletContextEvent sce) {
ServletContext servletContext = sce.getServletContext();
// 加载资源文件
String initParameter = servletContext.getInitParameter("con");
// 获取真实路径
String realPath = servletContext.getRealPath(initParameter);
try {
//加载进内存
FileInputStream fis = new FileInputStream(realPath);
}catch (Exception e) {
e.printStackTrace();
}
}