过滤器可以截取和修改进入一个servlet或者是jsp页面的请求
配置:
Set Character Encoding
com.util.setCharacterEncodingFilter
类:
package com.util;
import javax.servlet.*;
import java.io.IOException;
public class SetCharacterEncodingFilter implements Filter{
protected String encoding=null;
protected FilterConfig filterConfig=null;
protected boolean ignore=true;
public void init(FilterConfig filterConfig)throws ServletException{
this.filterConfig=filterConfig;
this.encoding=filterConfig.getInitParameter("encoding");
String value=filterConfig.getInitParameter("ignore");
if(value==null)
this.ingore=true;
else if(value.equalsIgnoreCase("true"))
this.ignore=true;
else if(value.equalsIgnoreCase("yes"))
this.ignore=true;
else
this.ignore=false;
}
public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws IOException,ServletException{
if(ignore||(request.getCharacterEncoding())==null){
String encoding=selectEncoding(request);
if(encoding!=null)
request.setCharacterEncoding(encoding);
}
chain.doFilter(request,response);
}
protected String selectEncoding(ServletRequest request){
return (this.encoding);
}
public void destory(){
this.encoding=null;
this.filterConfig=null;
}
}
映射:
Set Character Encoding
SomeServlet
///*
监听器:是建立或者修改servlet环境或会话对象时通知的类
配置:
listeners.SessionListener
类:
package listener;
inport javax.servlet.http.*;
import javax.servlet.*;
public class SessionListener implements HttpSessionListener,ServletContextListener,ServletContextAttributeListener{
private static int count;
private ServletContect context=null;
public SessionListener(){
count=0;
}
//创建一个session时激发
public void sessionCreate(HttpSessionEvent se){
count++;
setContext(se);
}
public void sessionDestroyed(HttpSessionEvent se){
if(count>0)
count--;
setContext(se);
}
//设置context的属性,它将激发attributeReplaced或attibuteAdded方法
public void setContext(HttpSessionEvent se){
se.getSession().getServletContext().setAttribute("onLine",new Integer(count));
}
//增加一个新的属性时触发
public void attributeAdded(ServletContextAttributeEvent event){}
//替换一个属性时触发
public void attributeReplaced(ServletContextAttributeEvent event){}
//删除一个属性时触发
public void attributeRemoved(ServletContextAttributeEvent event){}
//context删除时触发
public void contextDestroyed(ServletContextAttributeEvent event){
this.context=null;
}
//context初始化时激发
public void contextInitialized(ServeltContextEvent event){
this.event=event.getServletContext();
}
}
阅读(899) | 评论(0) | 转发(0) |