我们知道Ajax不能做页面redirect
和forward
跳转,所以Ajax请求假如没登录,那么这个请求给用户的感觉就是没有任何反应,而用户又不知道用户已经退出或是 Session 超时了。这个时候如何解决?
Shiro 教程,Ajax请求拦截跳转页面方案
在登录拦截器中,如我们自己定义的LoginFilter
中,先行判断下,是否为 Ajax 请求,如果是 Ajax 请求并且没有相关权限,采用Response
输出一段 JSON 数据返回即可。
判断请求是否为Ajax请求
Response 输出JSON数据
/**
* 使用 response 输出JSON
* @param hresponse
* @param resultMap
* @throws IOException
*/
public static void out(ServletResponse response, Map<String, String> resultMap){
PrintWriter out = null;
try {
response.setCharacterEncoding("UTF-8");//设置编码
response.setContentType("application/json");//设置返回类型
out = response.getWriter();
out.println(JSONObject.fromObject(resultMap).toString());//输出
} catch (Exception e) {
LoggerUtils.fmtError(CLAZZ, e, "输出JSON报错。");
}finally{
if(null != out){
out.flush();
out.close();
}
}
}
Shiro Filter 判断Ajax 请求并且处理
前端Javascript处理Ajax请求返回值
首先提供一个判断方法:
然后来一个栗子: