日期:2014-05-19  浏览次数:20626 次

struts2拦截器登录校验无法正确处理json请求
本帖最后由 zhangchu_63 于 2012-01-04 17:18:36 编辑
最近做个项目用到了Flexigrid,部分操作使用AJAX提交。
系统配置了一个登录和session失效验证的struts2全局拦截器,当ajax请求发送到后台时,拦截器可以拦截,但是判断出没有登录或者session超时的时候却不能跳转到指定页面。
这样的话权限什么的根本没法做。
不知道我表述的有没有问题。

<package name="strutsCheckLogin" extends="json-default">
<interceptors>
<interceptor name="noLogin"
class="com.zc.zcproject.commonInterceptor.AuthorityInterceptor" />
<interceptor-stack name="appStack">
<interceptor-ref name="defaultStack" />
</interceptor-stack>
<interceptor-stack
name="defaultPaginationInterceptorStack">
<interceptor-ref name="noLogin" />
<interceptor-ref name="appStack" />
</interceptor-stack>
</interceptors>
<default-interceptor-ref
name="defaultPaginationInterceptorStack" />
<global-results>
<result name="json" >
${pageContext.request.contextPath}/page/main_login.jsp
</result>
<result name="login" >
${pageContext.request.contextPath}/page/main_login.jsp
</result>
<result name="noframe">
${pageContext.request.contextPath}/page/error/error.jsp
</result>
</global-results>
<global-exception-mappings>
<exception-mapping result="noframe"
exception="com.zc.zcproject.exception.AppException">
</exception-mapping>
</global-exception-mappings>
</package>





public String intercept(ActionInvocation ai) throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
HttpServletResponse response = ServletActionContext.getResponse();
ActionContext ctx = ai.getInvocationContext();
Map session = ctx.getSession();
Object ACCOUNT = (Object) session.get(Constants.USER);
if (ACCOUNT != null) {
return ai.invoke();
}

_logger.info("intercept user is not login");
if(isAjaxRequest(request)){
return "json";
}else{
System.out.println("login");
return "login";
}
}

private boolean isAjaxRequest(HttpServletRequest request) {
String header = request.getHeader("X-Requested-With");
if (header != null && "XMLHttpRequest".equals(header))
return true;
else
return false;
}



各位帮帮忙吧。

------解决方案--------------------
我之前也遇到过这样的问题。但是LZ要明白,提交AJAX是无法通过后台的ACTION直接跳转的。2种情况,1:JS提交AJAX请求,如果ACTION返回1个页面,那JS则不能正确解析返回的数据;2:直接访问一个后台URL地址(如直接在浏览器地址栏输入或点1个超连接等等),如果后台返回JSON或XML格式的字符串,浏览器会提示你下载保存。这两种情况都是不希望看到的。
解决办法是 情况1:ACTION返回JSON或XML格式字符串,JS接收到返回数据后弹出提示信息 或者由JS控制跳转到1个页面。 情况2:ACTION直接返回到1个无权限页面或者登陆页面。

------解决方案--------------------
修改代码:
public String intercept(ActionInvocation ai) throws Exception {
        HttpServletRequest request = ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
  &nbs