参考引用方法
在新项目写了一个filter,能拦截jsp,.action的请求,但是ajax的请求可以拦截不能实现重写向登录页面。这是一个bug呀!
参考以上引用的方法,解决了。
ajax重定向的问题。
默认ajax是不支持重定向的,因为ajax本身就是局部刷新,不重新加载页面的。如果需要用到重定向可以通过以下方法:
第一步:filter
- public class AgentLoginFilter extends HttpServlet implements Filter{
- private static final Log log = LogFactory.getLog(AgentLoginFilter.class);
- @Override
- public void init(FilterConfig filterConfig) throws ServletException {
-
- }
- @Override
- public void doFilter(ServletRequest sRequest, ServletResponse sResponse, FilterChain filterChain)
- throws IOException, ServletException {
- HttpServletRequest request = (HttpServletRequest) sRequest;
- HttpServletResponse response = (HttpServletResponse) sResponse;
- HttpSession session = request.getSession();
- String url=request.getServletPath();
- String contextPath=request.getContextPath();
- String type = request.getHeader("X-Requested-With")==null?"":request.getHeader("X-Requested-With");
- String basePath = request.getScheme() + "://"+ request.getServerName() + ":" + request.getServerPort()+ contextPath + "/";
- if(url.equals("")){
- url+="/agent";
- }
- boolean isHasLogin = AgentSessionHelper.getHasLogined(request.getSession());
- if(!isHasLogin){
- if((url.startsWith("/agent") && !url.startsWith("/agent/login/YSAgentLoginAction/login.action"))
- && !url.startsWith("/agent/agentLogin.jsp")){
-
- if (StringUtils.equals("XMLHttpRequest", type)) {
-
- response.setHeader("SESSIONSTATUS", "TIMEOUT");
- response.setHeader("CONTEXTPATH", basePath+"agent/agentLogin.jsp");
- response.setStatus(HttpServletResponse.SC_FORBIDDEN);
- return;
- }else{
- response.sendRedirect(contextPath+"/agent/agentLogin.jsp");
- return;
- }
- }
- }else{
- if(url.startsWith("/agent/agentLogin.jsp")){
- response.sendRedirect(contextPath+"/agent/agentIndex.jsp");
- return;
- }
- }
- filterChain.doFilter(sRequest, sResponse);
- }
- }
第二步:在公共js 中写入
通过$.ajaxSetup()方法给ajax方法统一添加请求执行结束后,执行的操作。
- $.ajaxSetup( {
-
- complete :
- function(XMLHttpRequest, textStatus) {
-
- var sessionstatus = XMLHttpRequest.getResponseHeader("sessionstatus");
- if (sessionstatus == "TIMEOUT") {
- var win = window;
- while (win != win.top){
- win = win.top;
- }
- win.location.href= XMLHttpRequest.getResponseHeader("CONTEXTPATH");
- }
- }
- });