1、利用filter对一些不变的数据进行简单缓存,例如图片
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse res = (HttpServletResponse)response; //时间可以也可以配到初始化参数中 res.setHeader("Cache-control", "max-age=5000"); chain.doFilter(request, response); }配置文件
<filter> <filter-name>WebCacheFilter</filter-name> <filter-class>com.jialin.drp.util.WebCacheFilter</filter-class> </filter>
<filter-mapping> <filter-name>WebCacheFilter</filter-name> <url-pattern>*.gif</url-pattern> </filter-mapping>
<filter-mapping> <filter-name>WebCacheFilter</filter-name> <url-pattern>*.jpg</url-pattern> </filter-mapping>
<filter-mapping> <filter-name>WebCacheFilter</filter-name> <url-pattern>*.js</url-pattern> </filter-mapping>
<filter-mapping> <filter-name>WebCacheFilter</filter-name> <url-pattern>*.css</url-pattern> </filter-mapping>
2、判断用户是否已登录(除去登录界面和登录界面验证码的servlet)
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest)request; HttpServletResponse res = (HttpServletResponse)response; //获取登录URI String requestURI = req.getRequestURI().substring(req.getRequestURI().indexOf("/", 1), req.getRequestURI().length()); //登录界面和登录界面用到的验证码servlet不验证 if (!"/login.jsp".equals(requestURI) && !"/servlet/AuthImageServlet".equals(requestURI)) { HttpSession session = req.getSession(false); if (session == null || session.getAttribute("user_info") == null) { res.sendRedirect(req.getContextPath() + "/login.jsp"); return; } } //继续访问其他资源 chain.doFilter(req, res); }
配置文件
<filter> <filter-name>AuthFilter</filter-name> <filter-class>com.jialin.drp.util.AuthFilter</filter-class> </filter> <filter-mapping> <filter-name>AuthFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>AuthFilter</filter-name> <url-pattern>/servlet/*</url-pattern> </filter-mapping>
3、控制编码的filter
@Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //设置编码 request.setCharacterEncoding(encoding); chain.doFilter(request, response); } @Override public void init(FilterConfig filterConfig) throws ServletException { //获取filter初始化参数信息 this.encoding=filterConfig.getInitParameter("encoding"); }
配置文件
<filter> <filter-name>CharsetEncodingFilter</filter-name> <filter-class>com.jialin.drp.util.filter.CharsetEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>GBK</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharsetEncodingFilter</filter-name> <url-pattern>*.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>CharsetEncodingFilter</filter-name> <url-pattern>/servlet/*</url-pattern> </filter-mapping>