Filter案例2_过滤敏感词汇实现、Listener监听器
Filter案例2_过滤敏感词汇实现
案例:
public class SensitivWordsFilter implements Filter {
private List<String> list = new ArrayList<String>();//敏感词汇集合
public void init(FilterConfig filterConfig) throws ServletException {
try{
//获取文件真实路径
ServletContext servletContext = filterConfig.getServletContext();
String realPath = servletContext.getRealPath("D:\\IDEA项目\\day_06\\src\\敏感词汇.txt");
//读取文件
BufferedReader br = new BufferedReader(new FileReader(realPath));
//将文件的每一行添加到list中
String line=null;
while ((line = br.readLine())!=null){
list.add(line);
}
br.close();
System.out.println(list);
}catch(Exception e){
e.printStackTrace();
}
}
public void doFilter(final ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
ServletRequest proxy_lenovo = (ServletRequest) Proxy.newProxyInstance(servletRequest.getClass().getClassLoader(), servletRequest.getClass().getInterfaces(), new InvocationHandler() {
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//增强getParameter方法
//判断是否是getParameter方法
if (method.getName().equals("getParameter")){
//增强返回值
//获取返回值
String value = (String) method.invoke(servletRequest, args);
if (value!=null){
for (String str : list) {
if (value.contains(str)){
value=value.replaceAll(str,"***");
}
}
}
return value;
}
return method.invoke(servletRequest,args);
}
});
//放行
filterChain.doFilter(servletRequest,servletResponse);
}
public void destroy() {
}
Listener监听器
概念:
web 的三大组件之一
事件:一件事情
事件源:事件发生的地方
监听器:一个对象
注册监听:将事件,事件源,监听器绑定到一起,当事件发生子在某个事件后,执行监听器
ServletContextListener
void contextDestroyed(servletcontextEvent sce)
void contextInitialized(servletcontextEvent sce)