Struts 2拦截器重定向不适用于Ajax

时间:2014-04-19 17:24:20

标签: java ajax jsp struts2

我已经配置了Struts 2 Interceptor来验证用户会话。在无效会话中,我将重定向到错误页面。

Interceptor对正常调用动作类工作正常,但是当我通过ajax调用调用动作类时,错误页重定向不起作用。

我目前正在为此做的是在拦截器和JSP上根据从JSP重定向的属性值来设置请求属性。

但是我没有采用任何方式在JSP中编写任何东西,以便在以正常方式和Ajax形式调用动作类时,以类似的方式在错误页面重定向中编写任何内容

谢谢, 维奈

1 个答案:

答案 0 :(得分:2)

  1. 在拦截器中,在我们返回错误之前将响应状态设置为UnAuthorized。

           httpResponse.setStatus(HttpStatus.SC_UNAUTHORIZED);
           return "errorPage";
    
  2. 在ajax调用中,我们发出的请求最终会话超时并重定向,请将错误处理块直接重定向到此处的页面。

      $.ajax({
        url : "some.action",
            data : {
                "query" : inputText
        },
        type : 'GET',
        dataType : 'json',
    success : function(data) {
        //code
    },
    error : function(data) {
        if (data.status == 401 ){
            console.log("UnAuthorized. Redirecting to Error");
            window.location.replace(contextPath +"/error.jsp");
        }
    }
    
  3. 为errorpage设置struts条目以避免任何配置问题。

        <result name="errorPage">errorPage.jsp</result>