修改struts2自定义标签的源代码,在原有基础上增加功能(用于OA项目权限判断,是否显示某个权限)

OA项目在做权限判断时  原始方式:

现在完成的功能 :通过改变struts2自定标签源代码   在原有的基础上  增加判断权限的功能  而页面上使用标签的方式 还是下图

步骤:

 

打开文件

搜索<name>a</name>

找到该标签对应的类全路径  然后打开源码

首先明确的是:源码是不可以修改的   但是我们知道项目中类的加载顺序是  现在src下找  如果找不到  才会去jar文件中寻找类  

所以 采取的办法 :把源代码复制  然后在src下创建和源代码相同的包名以及类名 

在这里边添加相应的功能   最终实现增强struts2标签的功能  主要覆写父类中一下的两个方法   

doEndTag()的作用是 :标签执行完之后  将要进行的动作   doStartTag()的作用是:标签执行前你想做什么事

我们需要用到标签中的action属性中的内容  所以修改doEndTag()中的代码即可,一下是部分代码:

 private static final long serialVersionUID = -1034616578492431113L;

    protected String href;
    protected String includeParams;
    protected String scheme;
    protected String action;
    protected String namespace;
    protected String method;
    protected String encode;
    protected String includeContext;
    protected String escapeAmp;
    protected String portletMode;
    protected String windowState;
    protected String portletUrlType;
    protected String anchor;
    protected String forceAddSchemeHostAndPort;
    
    /*
     * 开始增加判断是否显示或者不显示代码 覆写父类中的方法
     * (non-Javadoc)  --付强修改
     * @see org.apache.struts2.views.jsp.ComponentTagSupport#getBean(com.opensymphony.xwork2.util.ValueStack, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
     */
    @Override
    public int doEndTag() throws JspException {
        //当前登录的用户
        User user=null;
        user=(User) pageContext.getSession().getAttribute("user");
        //当前准备显示的权限对应的url  数据库中存的url是带着'/'的   /xxx.action
        String privUrl="/"+action;
        
        //找到URL中?的位置  xxx.action?a=1&b=2;
        int pos=privUrl.indexOf("?");
        if(pos>-1){//找到?号的位置
            //截取到字符串 截取?前面的内容
            privUrl=privUrl.substring(0,pos);
        }
        //去掉uI后缀
        if(privUrl.endsWith("UI")){//表示该字符串以UI结尾
            privUrl=privUrl.substring(0,privUrl.length()-2);
        }
        
        // TODO Auto-generated method stub
        if(user.hasPrivilegeByName(privUrl)){//这里判断 有权限吗  如果有  还按照原来的流程走  执行父类的方法 显示超链接  
            return super.doEndTag();//正常的生成并显示超链接标签 并继续执行页面中后面的代码
        }else{//否则 没有权限
            return EVAL_PAGE;//不生成 与显示超链接标签 只是继续执行页面中后面的代码
        }
    }
原文地址:https://www.cnblogs.com/Joke-Jay/p/7404866.html