Tomcat与web开发技术详解读书笔记(2)过滤器
1.简介
过滤器能够在Servlet、JSP或HTML等web组件被调用之前检查ServletRequest对象,修改请求头和请求正文的内容或者对请求进行预处理操作能够在Servlet、JSP或HTML等web组件被调用之后检查ServletReponse对象,修改响应头和响应正文。利用包装类ServletRequestWrapper和ServletResponseWrapper来修改ServletRequest对象和ServletResponse对象。2.如何创建过滤器?
必须实现javax.servlet.Filter接口。
init(FilterConfig config):过滤器初始化方法。Web应用启动时,Servlet容器首先创建FilterConfig对象(包含过滤器配置信息),然后创建Filter对象,接着调用Filter对象的init(FilterConfig config)方法,读取web.xml中的配置参数。??
Xml代码??web开发中常用的字符集编码过滤器
- <filter>??
- ????????<filter-name>loginFilter</filter-name>??
- ????????<filter-class>com.flyer.filter.LoginFilter</filter-class>??
- ????????<init-param>??
- ????????????<param-name>username</param-name>??
- ????????????<param-value>flyer</param-value>??
- ????????</init-param>??
- ????</filter>??
- ????<filter-mapping>??
- ????????<filter-name>loginFilter</filter-name>??
- ????????<url-pattern>??
- ????????????/*??
- ????????</url-pattern>??
- ????</filter-mapping>??
?
?
Xml代码??补充:Servlet监听器 ??类似与Swing界面应用开发,Servlet也可以创建监听器,以对Servlet容器,或Servlet中以象的事件做出反应。Servlet监听器主要有以下几种: ServletRequestListener ,ServletRequestAttributeListener, HttpSessionActivationListener ,HttpSessionBindingListener , HttpSessionAttributeListener,HttpSessionListener, ServletContextListener等等。 ??这些监听器主要用来监听session,request,application这三个对象里存取数据的变化。?
- <filter>??
- ????????<filter-name>encodingFilter</filter-name>??
- ????????<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>??
- ????????<init-param>??
- ????????????<param-name>encoding</param-name>??
- ????????????<param-value>??
- ????????????????UTF-8??
- ????????????</param-value>??
- ????????</init-param>??
- ????</filter>??
- ????<!--?过滤器能为所有的url过滤?-->??
- ????<filter-mapping>??
- ????????<filter-name>encodingFilter</filter-name>??
- ????????<url-pattern>??
- ????????????/*??
- ????????</url-pattern>??
- ????</filter-mapping>??
?