1.过滤器
a.定义:是一个中间组件,用于拦截源数据和目的数据之间的消息,并过滤二者之间传递的数据
b.步骤:
①建class继承Filter实现抽象方法
public class EncodingFilter implements Filter{
@Override
public void doFilter(ServletRequest req , ServletResponse resp , FilterChain chain){ req.setCharacterEncode("utf-8");
resp.setCharacterEncode("utf-8"); //放行(过滤链)
chain.doFilter(req , resp); }
}
②配置xml文件
<filter>
<filter-name>encoding</filter-name>
<filter-class>com.filter.EncodingFilter</filter-class>
</filter> <filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
2.监听器
a.application监听器
①建class继承ServletContextListener实现抽象方法
public class ApplicationListener implements ServletContextListener{
@Override
public void contextDestroyed(ServletContextEvent sce){
} @Override
public void contextInitialized(ServletContextEvent sce){
} }
②配置xml文件
<listener>
<listener-class>com.listener.ApplicationListener</listener-class>
</listener>
b.application属性监听器
①建class继承ServletContextAttributeListener实现抽象方法
②配置xml文件(同上)
c.session监听器、request监听器 与 application监听器类似