自己总结的:
package cn.com.**.**.personalCenter.filter; import java.io.IOException; import java.io.PrintWriter; 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.HttpSession; public class SessionFilter implements Filter{ private static final int NOT_VALID = -1; @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpRequest = (HttpServletRequest) request; httpRequest.setCharacterEncoding("UTF-8"); HttpSession session = httpRequest.getSession(); String oneOfLoginUrl = "http://localhost:8020/ecenter/views/ecenterClub/loginRegisterNew/newloginClub.jsp"; String requestURI = httpRequest.getRequestURI(); // String path = url.substring(url.lastIndexOf("/")); // boolean isLogin = requestURI.indexOf("login.jsp") != NOT_VALID || requestURI.indexOf("newloginClub.jsp") != NOT_VALID;//这个对loginRegisterNew中的文件会失效 boolean isLogin = requestURI.indexOf("login") != NOT_VALID;//这样不会过滤部分样式和js文件就能正常显示了 //超时处理,ajax请求超时设置超时状态,页面请求超时则返回提示并重定向 // if((path.indexOf(".jsp") != -1) && (session.getAttribute("entryId") == null) && (path.equals("/login.jsp") == false)){ if(!isLogin && (session.getAttribute("entryId") == null || "".equals(session.getAttribute("entryId")))){ //判断是否为ajax请求 // if(httpRequest.getHeader("x-requested-with") != null && httpRequest.getHeader("x-requested-with").equalsIgnoreCase("XMLHttpRequest")){ // httpResponse.addHeader("sessionStatus", "timeOut"); // httpResponse.addHeader("loginPath", oneOfLoginUrl); // } else { String str = "<script type='text/javascript'> alert('回话过期,请重新登录');" + "window.top.location.href='" + oneOfLoginUrl + "';</script>"; response.setContentType("text/html;charset=UTF-8");//解决中文乱码 try{ //response到请求页 PrintWriter writer = response.getWriter(); writer.write(str); writer.flush(); writer.close(); } catch (Exception e){ e.printStackTrace(); } // } } else { chain.doFilter(request, response); } } @Override public void destroy() { // TODO Auto-generated method stub } }
response.setContentType(
"text/html;charset=UTF-8"
);
// 解决中文乱码
后边加上
response.setHeader("Pragma","No-cache"); response.setHeader("Cache-Control","no-cache"); response.setHeader("Cache-Control", "no-store"); response.setDateHeader("Expires",0);
实际项目:
package cn.com.**.**.utils; import java.io.IOException; import java.util.ArrayList; import java.util.List; 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.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @SuppressWarnings("serial") public class SecurityFilter extends HttpServlet implements Filter{ Logger logger = LoggerFactory.getLogger(SecurityFilter.class); @Override public void init(FilterConfig filterConfig) throws ServletException { // TODO Auto-generated method stub } @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest _request=(HttpServletRequest)request; HttpServletResponse _response =(HttpServletResponse) response; HttpSession session = _request.getSession(true); String entryId = (String)session.getAttribute("entryId");//登录人 logger.info("[个人中心过滤器]:entryId登录用户:" + entryId); String url=_request.getRequestURI(); String href = request.getParameter("h"); logger.info("[个人中心过滤器]url==="+url+",href==="+href+",_request.getContextPath()==="+_request.getContextPath()); if(!"".equals(CheckNull.check(href)) && !href.startsWith("http://www.epicc.com.cn")&&!href.startsWith("http://11.207.58.71:8100")&&!href.startsWith("http://11.201.1.18")&&!href.startsWith("http://11.207.58.72:8000") &&!href.startsWith("http://11.207.58.75:8000")&&!href.startsWith("http://11.207.58.72:8300")){ logger.info("[个人中心过滤器]不在规定的地址范围内,跳转到登录页面"); _response.sendRedirect(_request.getContextPath() + "/views/ecenterClub/loginRegisterNew/login.jsp"); } //单点登录过滤 // if(url.indexOf(";jsessionid")>-1){ // // _response.sendRedirect(url.substring(0,url.indexOf(";jsessionid"))); // } if(entryId == null || "".equals(entryId)) { //判断获取的路径不为空且不是访问登录页面或执行登录操作时跳转 proposalModule/proposal/queryProposalInfo //1.不过滤资源文件 2.不过滤登陆注册模块 3 不过滤投保单详情和保单详情 if(url.indexOf("claimIndex.jsp")>0){ _response.sendRedirect(_request.getContextPath() + "/views/ecenterClub/loginRegisterNew/login.jsp"); } if(!isValided(url)) { logger.info("[个人中心过滤器]isValided(url)===false"); _response.sendRedirect(_request.getContextPath() + "/views/ecenterClub/loginRegisterNew/login.jsp"); logger.info(_request.getContextPath() + "/views/ecenterClub/loginRegisterNew/login.jsp"); return ; } } chain.doFilter(request, response); return; } /** * 校验url是否被登陆过滤器拦截 * @param url * @return */ private boolean isValided(String url){ boolean urlValue = false; if(url==null||"".equals(url)){ urlValue = false; } List<String> urlLi = new ArrayList<String>(); urlLi.add("/ecenter/loginRegister"); urlLi.add("login"); urlLi.add(".css"); urlLi.add(".jpg"); urlLi.add("CreateImage"); urlLi.add(".js"); urlLi.add(".png"); urlLi.add(".gif"); urlLi.add("bindEmail"); urlLi.add("searchOrdersDetail"); urlLi.add("ecenterController/ecenterService"); urlLi.add("/wapcustomer/validEmail"); urlLi.add("/proposalModule/proposal/queryProposalInfo"); urlLi.add("/ecenter/views/loginRegister/support/loginForOther.jsp"); urlLi.add("insurAndClaimsforIndex"); urlLi.add("/ecenter/policyModule/Policy/carPolicyDetail"); urlLi.add("/ecenter/policyModule/Policy/ebsPolicyDetail"); urlLi.add("/ecenter/loginRegister/longinByYaHooEmail"); urlLi.add("/ecenter/insuringAndClaims/PolicyClaimCheck/policyClaim/carClaim"); urlLi.add("/ecenter/insuringAndClaims/PolicyClaimCheck/policyClaim/noCarEbsClaim"); urlLi.add("/ecenter/insuringAndClaims/PolicyClaimCheck/policyClaim/noCarPolicy"); urlLi.add("/ecenter/insuringAndClaims/PolicyClaimCheck/policyClaim/getClaimList"); urlLi.add("/ecenter/insuringAndClaims/PolicyClaimCheck/policyClaim/getClaimDetail"); urlLi.add("/ecenter/orderModule/order/getCarOrderInfo"); urlLi.add("/catchPac"); urlLi.add("/ecenter/views/policyModule"); urlLi.add("/ecenter/personalInfo/customerInfo/saveCarSecretary"); urlLi.add("/ecenter/personalInfo/customerInfo/sendCarVaildCode"); urlLi.add("/ecenter/personalInfo/customerInfo/checkVaildCode"); urlLi.add("/ecenter/personalInfo/customerInfo/getLandEno"); urlLi.add("/ecenter/personalInfo/customerInfo/carSecretary"); urlLi.add("/ecenter/orderModule/order/getCarOrderInfoShow"); urlLi.add("/ecenter/servicesModule/consultation"); urlLi.add("/ecenter/orderModule/order/getErrorOrderInfo"); urlLi.add("/ecenter/policyModule/Policy/getEpolicyInfo"); urlLi.add("/ecenter/policyModule/Policy/getfeicheEpolicyInfo"); urlLi.add("My97DatePicker.htm"); urlLi.add("/ecenter/orderModule/order/getErrorYingyeInfo"); urlLi.add("/ecenter/insuringAndClaims/PolicyClaimCheck/policyClaim/YingXiaoDetail"); urlLi.add("/ecenter/policyModule/Policy/ebsPolicyDetail"); urlLi.add("/ecenter/views/errorPages/error404.html"); urlLi.add("/ecenter/policyModule/Policy/validateRand"); urlLi.add("/ecenter/policyDownload/Download/policyDownloadForPosPDF"); urlLi.add("/ecenter/policyDownload/Download/policyDownload"); urlLi.add("/ecenter/insuringAndClaims/PolicyClaimCheck/policyClaim"); urlLi.add("/sendPac"); urlLi.add("/ecenter/servicesModule/catchTBpack/getPack"); urlLi.add("/ecenter/servicesModule/catchTBpack/sendPack"); urlLi.add("/ecenter/servicesModule/activityPageConfig/tuangou"); urlLi.add("/ecenter/servicesModule/activityPageConfig/getCountyByCity"); urlLi.add("/ecenter/servicesModule/activityPageConfig/getActivityDetails"); urlLi.add("/ecenter/servicesModule/freesave/validateCardId"); urlLi.add("/ecenter/servicesModule/freesave/validateName"); urlLi.add("/ecenter/servicesModule/freesave/validateEmail"); urlLi.add("/ecenter/servicesModule/freesave/activateFreeSave"); urlLi.add("/ecenter/servicesModule/freesave/getPageUserCardInfoMsg"); urlLi.add("/ecenter/views/servicesModule/creditCardBlindQuery.jsp"); urlLi.add("/ecenter/views/servicesModule/activateFreeSave.jsp"); urlLi.add("/ecenter/views/servicesModule/unRegisterActivate.jsp"); urlLi.add("/ecenter/views/servicesModule/registeredActivate.jsp"); urlLi.add("/ecenter/servicesModule/checkStore/CheckStoreCode"); urlLi.add("/ecenter/sendpac"); urlLi.add("/ecenter/policyModule/Policy/checkReleStatus"); //add 20140825 start**改版流程 添加 urlLi.add("/ecenter/proposalModule/proposal/carJQProposalInfo"); urlLi.add("/ecenter/proposalModule/proposal/EADproposalInfo"); urlLi.add("/ecenter/orderModule/order/DATGroupOrderDetail"); //add 20140825 end urlLi.add("/ecenter/shortUrl/jpage"); urlLi.add("/ecenter/shortUrl/validRand"); urlLi.add("/ecenter/policyModule/Policy/queryClaimInfo"); urlLi.add("/ecenter/servicesModule/gift/queryGift"); //ebs-4349 两个网络整合 urlLi.add("/ecenter/ecenterClub"); urlLi.add("/ecenter/views/ecenterClub/loginRegisterNew/login.jsp"); //EBS-4828 **首页页面查询 urlLi.add("/ecenter/servicesModule/panicbuy/queryPanicBuyInfo"); urlLi.add("/ecenter/views/servicesModule/panicBuySrc.jsp"); //add 20141107 end urlLi.add("/ecenter/servicesModule/memberNew/getQxInfo"); urlLi.add("/ecenter/servicesModule/suggestion"); urlLi.add("/ecenter/servicesModule/memberNewCon"); urlLi.add("/ecenter/servicesModule/netorg"); urlLi.add("/ecenter/servicesModule/website"); urlLi.add("/ecenter/ecenterClub/loginRegisterNew/newLogin/isBeforeEntry"); urlLi.add("getEntry"); urlLi.add("/ecar/payment/entryDefray"); urlLi.add("/eproperty/pay"); for(int i=0; i<urlLi.size(); i++){ if(url.indexOf(urlLi.get(i)) >= 0){ urlValue = true; break; } } if("/ecenter/insuringAndClaims/PolicyClaimCheck/policyClaimNewIndex/getPolicyPage".equals(url)){ urlValue=false; } return urlValue; } }
<!-- begin session过期验证 --> <filter> <filter-name>SessionFilter</filter-name> <filter-class>cn.com.**.**.personalCenter.filter.SessionFilter</filter-class> </filter> <filter-mapping> <filter-name>SessionFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- end --> <!-- 过滤器 登陆状态 --> <filter> <filter-name>SecurityFilter</filter-name> <filter-class>cn.com.**.**.utils.SecurityFilter</filter-class> </filter> <!-- 安全登陆过滤 --> <filter-mapping> <filter-name>SecurityFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>