struts2-权限拦截器日志拦截器execAndWait(进度条)拦截器配置

Posted 爆烈鼓手

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了struts2-权限拦截器日志拦截器execAndWait(进度条)拦截器配置相关的知识,希望对你有一定的参考价值。

1.权限拦截器

package login;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;

public class LoginInterceptor extends AbstractInterceptor {
    private static final long serialVersionUID = 1L;
    @Override
    public String intercept(ActionInvocation ai) throws Exception {
        //取得请求的URL  
        String url = ServletActionContext.getRequest().getRequestURL().toString();  
        HttpServletResponse response=ServletActionContext.getResponse();  
        response.setHeader("Pragma","No-cache");            
        response.setHeader("Cache-Control","no-cache");     
        response.setHeader("Cache-Control", "no-store");     
        response.setDateHeader("Expires",0);  
        System.out.println("execute LoginInterceptor");
        //对登录与注销请求直接放行,不予拦截  
        if (url.indexOf("login.action")!=-1 || url.indexOf("logout.action")!=-1)
            {  
                return ai.invoke();  
            }  
        else
        {  
            //验证Session是否过期  
            if(!ServletActionContext.getRequest().isRequestedSessionIdValid())
                {  
                    //session过期,转向session过期提示页,最终跳转至登录页面  
                    return "tologin";  
                }  
            else
                {  
                    String systemUser =(String) ServletActionContext.getRequest().getSession().getAttribute("user");  
                    //验证是否已经登录  
                    if (systemUser==null)
                        {  
                            //尚未登录,跳转至登录页面  
                            return "tologin";  
                        }
                    else
                        {                      
                            return ai.invoke();                   
                        }                  
                }              
        }  
        
    }

}
LoginInterceptor

2.日志拦截器

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;
import com.opensymphony.xwork2.interceptor.PreResultListener;
public class DologInterceptor implements Interceptor {
    private static final long serialVersionUID = 1L;
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    @Override
    public void init() {
        // TODO Auto-generated method stub
    }
     LogDao ld=new LogDao();
    @Override
    public String intercept(ActionInvocation ai) throws Exception {
        ai.addPreResultListener(new PreResultListener() {
                          public void beforeResult(ActionInvocation ai, String arg1) {
                              try {
                                      boolean param=true;
                                      System.out.println("execute DologIntercepter");
                                      OperateLog log=new OperateLog();
                                      long time=System.currentTimeMillis();
                                      log.setId(time);
                                      SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd H:m:s");
                                        String operatetime=format.format(new Date()).toString();
                                        log.setOperatetime(operatetime);
                                      Map<String, Object> session = ai.getInvocationContext().getSession();
                                      String user = (String) session.get("user");
                                      if (user != null) 
                                          {
                                              log.setOperator(user);
                                          } 
                                      else 
                                          {
                                              log.setOperator("operator:can\'t get form system");
                                          }
                                      String operation="className:" + ai.getAction() + " ";
                                      operation=operation+"methodName:" + ai.getInvocationContext().getName()+ " ";
                                      
                                      Map<String, Object> map = ai.getInvocationContext().getParameters();
                                      Set<String> keys = map.keySet();
                                      if (keys==null||keys.size()==0) 
                                          {
                                            param=false;
                                            System.out.println("parameters null");
                                          }
                                      else
                                          {
                                              operation=operation+"Parameters:";
                                              for (String key : keys) 
                                                  {
                                                      operation=operation+key + "=" + ((Object[]) map.get(key))[0]+ "#";
                                                  }
                                          }
                                      operation=operation+" executeResult:" + ai.getResultCode() + " ";
                                      log.setOperation(operation);
                                      if (param) 
                                          {
                                              ld.save(log);
                                              System.out.println("print the log object:"+log);
                                          }
                              } 
                              
                              catch (Exception e) {
                                  e.printStackTrace();
                              }
              
                          }
                      });
                      return ai.invoke();
                  }
    }
DologInterceptor

3.execAndWait为struts2自带拦截器,这里不附源代码

前台与execAndWait配合的页面代码:

重点是: <meta http-equiv="refresh" content="3;url=generatePath.action">

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

    <title>My JSP \'indicate_waiting.jsp\' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">   
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!-- 下面的meta元素才是重点,其他的没什么影响,是IDE自带的  -->
    <meta http-equiv="refresh" content="3;url=generatePath.action">
  <title> 正在查询,请稍等...</title>
<style type="text/css">
.query_hint{
    border:5px solid #939393;
    width:400px;
    height:50px;
    line-height:55px;
    padding:0 20px;
    position:absolute;
    left:40%;
    margin-left:-140px;
    top:30%;
    margin-top:-40px;
    font-size:15px;
    color:#333;
    font-weight:bold;
    text-align:center;
    background-color:#f9f9f9;
}
.query_hint img{position:relative;top:10px;left:-8px;}
</style>
 </head>

 <body>
  <div id="query_hint" class="query_hint">
       <img src="images/waiting.gif" />正在执行查询,请稍等...<%-- <s:property value="complete"/> --%>
  </div>

</html>
indicate_waiting.jsp

4.在struts.xml中对拦截器的配置

<package name="generatepath" namespace="/" extends="struts-default">
        <interceptors>
        <!-- 定义权限控制拦截器 -->
        <interceptor name="loginVerify" class="login.LoginInterceptor"></interceptor>
        <!-- 定义日志拦截器 -->
        <interceptor name="dolog" class="dolog.DologInterceptor"></interceptor>
        <!-- 定义一个包含登陆控制和日志管理的拦截器栈 -->   
         <interceptor-stack name="mydefaultStack">
               <interceptor-ref name="loginVerify"></interceptor-ref>
               <interceptor-ref name="dolog"></interceptor-ref>
               <interceptor-ref name="defaultStack"></interceptor-ref>
              <interceptor-ref name="execAndWait">
                <param name="delay">1000</param>
                <param name="delaySleepInterval">1000</param> 
              </interceptor-ref>
           </interceptor-stack>
        </interceptors>
        <!-- 定义默认拦截器 -->
        <default-interceptor-ref name="mydefaultStack"></default-interceptor-ref>
        <!-- 定义全局处理结果 -->
        <global-results>   
            <result name="tologin" type="redirect">/session.jsp</result>  
        </global-results> 
        <action name="generatePath" class="neo4j.PathIndicationAction" method="doIndicatePath">
            <result name="wait">/work/search/indicate_waiting.jsp</result>
            <result name="indicateResult">/work/search/pathIndication.jsp</result>
        </action>
</package>
View Code

5.后台实现代码略。

以上是关于struts2-权限拦截器日志拦截器execAndWait(进度条)拦截器配置的主要内容,如果未能解决你的问题,请参考以下文章

6Struts2拦截器实现权限控制

struts2拦截器加自定义注解实现权限控制

struts2的拦截器和spring的AOP哪个实现权限管理更好

Struts2学习—拦截器之登录权限

struts2的拦截器跟spring2 AOP有啥区别?哪个好?

一个网站的权限管理,用过滤器还是拦截器更好