<filter> <filter-name>UsersFilter</filter-name> <filter-class>com.web.UsersFilter</filter-class> </filter> <filter-mapping> <filter-name>UsersFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
package com.web; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class UsersFilter implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // 設置請求的字符編碼 request.setCharacterEncoding("UTF-8"); // 設置返回請求的字符編碼 response.setCharacterEncoding("UTF-8"); // 轉換ServletRequest為 HttpServletRequest HttpServletRequest req = (HttpServletRequest) request; // 轉換ServletResponse為HttpServletRequest HttpServletResponse res = (HttpServletResponse) response; // 獲取Session HttpSession session = req.getSession(); // 獲取Session中存儲的對象 Object o = session.getAttribute("user"); // 獲取當前請求的URI String url = req.getRequestURI(); // 判斷Session中的對象是否為空;判斷請求的URI是否為不允許過濾的URI if (o==null && url.indexOf("test.jsp")<0 && url.indexOf("comment.jsp")<0 && url.indexOf("link.jsp")<0) { chain.doFilter(request, response); res.setHeader("Cache-Control","no-store"); res.setDateHeader("Expires",0); res.setHeader("Pragma","no-cache"); res.flushBuffer(); } } public void destroy() { // TODO Auto-generated method stub } public void init(FilterConfig arg0) throws ServletException { // TODO Auto-generated method stub } }
****************************************************************************************