代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
| package com.sunsheen.filter;
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;
import com.sunsheen.jfids.system.config.Configs; import com.sunsheen.jfids.system.security.login.Session;
public class LoginFilter implements Filter {
public LoginFilter() { }
public void destroy() { }
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)throws IOException, ServletException { HttpServletRequest req = (HttpServletRequest) request; String reqUrl = req.getRequestURI();
if(reqUrl.contains("/hkcloud/login.w.xhtml") || reqUrl.contains("/hkcloud/getUser") || reqUrl.contains("/hkcloud/login") || reqUrl.contains("/static/") || reqUrl.endsWith(".css") || reqUrl.endsWith(".js")){ chain.doFilter(request, response); return; } HttpSession session = Session.getHttpSession(); String apiKey = (String) session.getAttribute("ApiKey"); HttpServletResponse res = (HttpServletResponse) response; if (apiKey == null || apiKey.equals("")) { String loginUrl = Configs.get("AllConfig.loginUrl"); if("XMLHttpRequest".equals(req.getHeader("X-Requested-With"))){ res.setHeader("redirect", "redirect"); res.setHeader("url", req.getContextPath() + loginUrl); res.setStatus(HttpServletResponse.SC_FORBIDDEN); return; }else{ res.sendRedirect(req.getContextPath() + loginUrl); } } else { chain.doFilter(request, response); return; } }
public void init(FilterConfig fConfig) throws ServletException { } }
|
注:
ajax请求返回重定向信息
在项目中,考虑到web前台ajax请求未登录资源时,后台返回的重定向信息,ajax不能自动判断是否是重定向,以下是一种折中方法:
前端jquery.ajax默认设置,ajax设置要放在程序ajax调用前
,我一般放在公共js中统一引用到文件头里的
,这样调用ajax的时候就无需操心其他设置了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
|
$.ajaxSetup({ complete : function(XMLHttpRequest, textStatus) { var redirect = XMLHttpRequest.getResponseHeader("redirect"); if (redirect == "redirect") { var win = window; while (win != win.top) { win = win.top; } win.location.href = XMLHttpRequest.getResponseHeader("url"); } }, type : 'POST' });
|