• Java过滤器应用-对Ajax请求做Session失效判断


     过滤器常用来对Session过期做判断

     Layout.js  

    1.为ajax请求添加标识   

    2.无论ajax请求成功与否,complete函数终会执行

     1 // 全局Ajax设置, 用于session过期后的跳转
     2 function ajaxSetup() {
     3     $.ajaxSetup({
     4         timeout : 10000,
     5         beforeSend : function(xhr) {
     6             //添加ajax请求标识
     7             xhr.setRequestHeader("ajaxReq", "ajax");
     8         },
     9         complete : function(xhr, ts) {
    10             if (xhr.statusText == 'sessiontimeout' && xhr.status == 403) {
    11                 // 跳转
    12                 window.location.href = "login.jsp";
    13             }
    14         }
    15     });
    16 }

    请求过滤器,Session过期则修改请求状态为403(或其他),设置过期标识sessionState为timeout,便于ajax回调函数判断。

     1 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
     2 
     3         HttpServletRequest req = (HttpServletRequest) request;
     4         HttpServletResponse res = (HttpServletResponse) response;
     5         String servletPath = req.getServletPath();
     6         
     7         if(except.contains(req.getRequestURI())){
     8             chain.doFilter(request, response);
     9         }
    11         
    13         Object sessionObj = req.getSession().getAttribute(key);
    14         if(sessionObj==null){
    15             //如果是ajax请求
    16             if(req.getHeader("ajaxReq")!=null && req.getHeader("ajaxReq").equals("ajax")){
    17                 res.setHeader("sessionState", "timeout");
    18                 res.setStatus(403);
    19                 return;
    20             }else{
    21                 chain.doFilter(request, response);
    22                 String contextPath = req.getContextPath();
    23                 String redirect = servletPath + "?" + StringUtils.defaultString(req.getQueryString());
    24                 res.sendRedirect(contextPath + forward + "?redirect=" + URLEncoder.encode(redirect, "UTF-8"));
    25             }
    26             
    27         }else{
    28             // pass the request along the filter chain
    29             chain.doFilter(request, response);
    30             System.out.println("chain.do after");
    31         }
    32         
    33     }

     目前发现ajax全局设置对load函数无效。

    觉得不错,点个赞吧
  • 相关阅读:
    成功并不是要得到什么,而是要放弃什么
    Qt一步一步实现插件通信(附源码)
    Qt一步一步实现插件调用(附源码)
    推荐大家阅读——《你的知识需要管理》
    移动商机十人谈__移动红利
    如果再不要求进步,那么你就是下一个陨落的巨头
    贫穷的本质__如何改变穷人的现状?
    贫穷的本质__缺乏对未来的信心和长远规划
    痛苦并愉快的被洗着_品牌洗脑
    Qt_Pro详解
  • 原文地址:https://www.cnblogs.com/luangeng/p/5625011.html
Copyright © 2020-2023  润新知