application等对象的使用及监听器过滤器
监听器的使用实例:
public class SessionListener implements HttpSessionListener {
public void sessionCreated(HttpSessionEvent arg0)
{
// TODO Auto-generated method stub
ServletContext application=arg0.getSession().getServletContext();
int count=0;
if(application.getAttribute("count")!=null)
{
count=Integer.parseInt(String.valueOf(application.getAttribute("count")))+1;
}
else
{
count++;
}
application.setAttribute("count", count);
}
public void sessionDestroyed(HttpSessionEvent arg0) {
// TODO Auto-generated method stub
}
}
过滤器类的实现:
public class CharFilter implements Filter {
public void destroy()
{
// TODO Auto-generated method stub
System.out.println("public void destroy() ");
}
public void doFilter(ServletRequest arg0, ServletResponse arg1,
FilterChain arg2) throws IOException, ServletException
{
// TODO Auto-generated method stub
arg0.setCharacterEncoding("utf-8"); //请求发送给服务器需要先经过这步
System.out.println("------------------");
arg2.doFilter(arg0, arg1); //服务器处理
请求
System.out.println("******************");
arg1.setContentType("text/html; charset=utf-8"); //服务器把处理结果返回给请求发送方需要经过
这步
}
public void init(FilterConfig arg0) throws ServletException //服务器启动时调用
{
// TODO Auto-generated method stub
System.out.println("public void init(FilterConfig arg0) throws ServletException");
}
}
过滤器在web.xml文件的配置实例;
<filter>
<filter-name>charFilter</filter-name>
<filter-class>com.xasxt.comm.CharFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>charFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapp