用Struts2拦截器实现文件下载前的验证

思想:用户登录后,将登录信息存储在session中,每次需要验证时,取出来验证

缺陷:没有实现多用户登录时的情况

实行步骤:

登录信息的存储:

ActionContext actionContext = ActionContext.getContext();
Map<String, Object> session = actionContext.getSession();
session.put("currentUser", user1);

拦截器的实现:

ActionContext actionContext = invocation.getInvocationContext();
Map<String, Object> session = actionContext.getSession();
Object currentUser = session.get("currentUser");
String result = null;
if (currentUser != null) {
    System.out.println(currentUser);
    result = invocation.invoke();
} else {
    HttpServletRequest request = (HttpServletRequest)invocation.getInvocationContext().get(ServletActionContext.HTTP_REQUEST);
    request.setAttribute("error", "请先登录");
    result = "error";
}
return result;

struts.xml 中插入拦截器,并在文件下载处写入声明拦截器

 

你可能感兴趣的:(用Struts2拦截器实现文件下载前的验证)