如何修改第三方jar包里的类的方法,使得jar包里的方法都调用自己重写的方法

作者使用的框架为ureport2(基于java的spring引擎的报表框架)


image.png
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    ">
    <import resource="classpath:ureport-core-context.xml"/>
    <import resource="classpath:ureport-font-context.xml"/>
    
    <bean id="ureport.datasourceServletAction" class="com.bstek.ureport.console.designer.DatasourceServletAction"></bean>
    <bean id="ureport.resourceLoaderServletAction" class="com.bstek.ureport.console.res.ResourceLoaderServletAction"></bean>
    <bean id="ureport.designerServletAction" class="com.bstek.ureport.console.designer.DesignerServletAction">
        <property name="reportRender" ref="ureport.reportRender"></property>
        <property name="reportParser" ref="ureport.reportParser"></property>
    </bean>
    
    <bean id="ureport.searchFormDesignerAction" class="com.bstek.ureport.console.designer.SearchFormDesignerAction"></bean>
    
    <bean id="ureport.htmlPreviewServletAction" class="com.bstek.ureport.console.html.HtmlPreviewServletAction">
        <property name="exportManager" ref="ureport.exportManager"></property>
        <property name="reportBuilder" ref="ureport.reportBuilder"></property>
        <property name="reportRender" ref="ureport.reportRender"></property>
    </bean>
    <bean id="ureport.exportWordServletAction" class="com.bstek.ureport.console.word.ExportWordServletAction">
        <property name="exportManager" ref="ureport.exportManager"></property>
        <property name="reportBuilder" ref="ureport.reportBuilder"></property>
    </bean>
    
    <bean id="ureport.exportPdfServletAction" class="com.bstek.ureport.console.pdf.ExportPdfServletAction">
        <property name="exportManager" ref="ureport.exportManager"></property>
        <property name="reportBuilder" ref="ureport.reportBuilder"></property>
        <property name="reportRender" ref="ureport.reportRender"></property>
    </bean>
    
    <bean id="ureport.exportExcelServletAction" class="com.bstek.ureport.console.excel.ExportExcelServletAction">
        <property name="exportManager" ref="ureport.exportManager"></property>
        <property name="reportBuilder" ref="ureport.reportBuilder"></property>
    </bean>
    
    <bean id="ureport.exportExcel97ServletAction" class="com.bstek.ureport.console.excel.ExportExcel97ServletAction">
        <property name="exportManager" ref="ureport.exportManager"></property>
        <property name="reportBuilder" ref="ureport.reportBuilder"></property>
    </bean>
    
    <bean id="ureport.imageServletAction" class="com.bstek.ureport.console.image.ImageServletAction"></bean>
    <bean id="ureport.importExcelServletAction" class="com.bstek.ureport.console.importexcel.ImportExcelServletAction"></bean>
    
    <bean id="ureport.chartServletAction" class="com.bstek.ureport.console.chart.ChartServletAction"></bean>
    
    <bean id="ureport.httpSessionReportCache" class="com.bstek.ureport.console.cache.HttpSessionReportCache">
        <property name="disabled" value="${ureport.disableHttpSessionReportCache}"></property>
    </bean>
</beans>

可以看到我想修改的类被加入到了spring中管理
我们先来看看这个类的方法:

/*******************************************************************************
 * Copyright 2017 Bstek
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.  You may obtain a copy
 * of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations under
 * the License.
 ******************************************************************************/
package com.bstek.ureport.console.designer;

import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

import com.bstek.ureport.cache.CacheUtils;
import com.bstek.ureport.console.RenderPageServletAction;
import com.bstek.ureport.console.cache.TempObjectCache;
import com.bstek.ureport.console.exception.ReportDesignException;
import com.bstek.ureport.definition.ReportDefinition;
import com.bstek.ureport.dsl.ReportParserLexer;
import com.bstek.ureport.dsl.ReportParserParser;
import com.bstek.ureport.dsl.ReportParserParser.DatasetContext;
import com.bstek.ureport.export.ReportRender;
import com.bstek.ureport.expression.ErrorInfo;
import com.bstek.ureport.expression.ScriptErrorListener;
import com.bstek.ureport.parser.ReportParser;
import com.bstek.ureport.provider.report.ReportProvider;

/**
 * @author Jacky.gao
 * @since 2017年1月25日
 */
public class DesignerServletAction extends RenderPageServletAction {
    private ReportRender reportRender;
    private ReportParser reportParser;
    private List<ReportProvider> reportProviders=new ArrayList<ReportProvider>();
    @Override
    public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method=retriveMethod(req);
        if(method!=null){
            invokeMethod(method, req, resp);
        }else{
            VelocityContext context = new VelocityContext();
            context.put("contextPath", req.getContextPath());
            resp.setContentType("text/html");
            resp.setCharacterEncoding("utf-8");
            Template template=ve.getTemplate("ureport-html/designer.html","utf-8");
            PrintWriter writer=resp.getWriter();
            template.merge(context, writer);
            writer.close();
        }
    }
    public void scriptValidation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String content=req.getParameter("content");
        ANTLRInputStream antlrInputStream=new ANTLRInputStream(content);
        ReportParserLexer lexer=new ReportParserLexer(antlrInputStream);
        CommonTokenStream tokenStream=new CommonTokenStream(lexer);
        ReportParserParser parser=new ReportParserParser(tokenStream);
        ScriptErrorListener errorListener=new ScriptErrorListener();
        parser.removeErrorListeners();
        parser.addErrorListener(errorListener);
        parser.expression();
        List<ErrorInfo> infos=errorListener.getInfos();
        writeObjectToJson(resp, infos);
    }
    
    public void conditionScriptValidation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String content=req.getParameter("content");
        ANTLRInputStream antlrInputStream=new ANTLRInputStream(content);
        ReportParserLexer lexer=new ReportParserLexer(antlrInputStream);
        CommonTokenStream tokenStream=new CommonTokenStream(lexer);
        ReportParserParser parser=new ReportParserParser(tokenStream);
        ScriptErrorListener errorListener=new ScriptErrorListener();
        parser.removeErrorListeners();
        parser.addErrorListener(errorListener);
        parser.expr();
        List<ErrorInfo> infos=errorListener.getInfos();
        writeObjectToJson(resp, infos);
    }
    
    
    public void parseDatasetName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String expr=req.getParameter("expr");
        ANTLRInputStream antlrInputStream=new ANTLRInputStream(expr);
        ReportParserLexer lexer=new ReportParserLexer(antlrInputStream);
        CommonTokenStream tokenStream=new CommonTokenStream(lexer);
        ReportParserParser parser=new ReportParserParser(tokenStream);
        parser.removeErrorListeners();
        DatasetContext ctx=parser.dataset();
        String datasetName=ctx.Identifier().getText();
        Map<String,String> result=new HashMap<String,String>();
        result.put("datasetName", datasetName);
        writeObjectToJson(resp, result);
    }
    public void savePreviewData(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String content=req.getParameter("content");
        content=decodeContent(content);
        InputStream inputStream=IOUtils.toInputStream(content,"utf-8");
        ReportDefinition reportDef=reportParser.parse(inputStream,"p");
        reportRender.rebuildReportDefinition(reportDef);
        IOUtils.closeQuietly(inputStream);
        TempObjectCache.putObject(PREVIEW_KEY, reportDef);
    }
    
    public void loadReport(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String file=req.getParameter("file");
        if(file==null){
            throw new ReportDesignException("Report file can not be null.");
        }
        file=ReportUtils.decodeFileName(file);
        Object obj=TempObjectCache.getObject(file);
        if(obj!=null && obj instanceof ReportDefinition){
            ReportDefinition reportDef=(ReportDefinition)obj;
            TempObjectCache.removeObject(file);
            writeObjectToJson(resp, new ReportDefinitionWrapper(reportDef));
        }else{
            ReportDefinition reportDef=reportRender.parseReport(file);
            writeObjectToJson(resp, new ReportDefinitionWrapper(reportDef));            
        }
    }
    
    public void deleteReportFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String file=req.getParameter("file");
        if(file==null){
            throw new ReportDesignException("Report file can not be null.");
        }
        ReportProvider targetReportProvider=null;
        for(ReportProvider provider:reportProviders){
            if(file.startsWith(provider.getPrefix())){
                targetReportProvider=provider;
                break;
            }
        }
        if(targetReportProvider==null){
            throw new ReportDesignException("File ["+file+"] not found available report provider.");
        }
        targetReportProvider.deleteReport(file);
    }
    
    
    public void saveReportFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String file=req.getParameter("file");
        file=ReportUtils.decodeFileName(file);
        String content=req.getParameter("content");
        content=decodeContent(content);
        ReportProvider targetReportProvider=null;
        for(ReportProvider provider:reportProviders){
            if(file.startsWith(provider.getPrefix())){
                targetReportProvider=provider;
                break;
            }
        }
        if(targetReportProvider==null){
            throw new ReportDesignException("File ["+file+"] not found available report provider.");
        }
        targetReportProvider.saveReport(file, content);
        InputStream inputStream=IOUtils.toInputStream(content,"utf-8");
        ReportDefinition reportDef=reportParser.parse(inputStream, file);
        reportRender.rebuildReportDefinition(reportDef);
        CacheUtils.cacheReportDefinition(file, reportDef);
        IOUtils.closeQuietly(inputStream);
    }
    
    public void loadReportProviders(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        writeObjectToJson(resp, reportProviders);
    }
    
    public void setReportRender(ReportRender reportRender) {
        this.reportRender = reportRender;
    }
    
    public void setReportParser(ReportParser reportParser) {
        this.reportParser = reportParser;
    }
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
        super.setApplicationContext(applicationContext);
        Collection<ReportProvider> providers=applicationContext.getBeansOfType(ReportProvider.class).values();
        for(ReportProvider provider:providers){
            if(provider.disabled() || provider.getName()==null){
                continue;
            }
            reportProviders.add(provider);
        }
    }

    @Override
    public String url() {
        return "/designer";
    }
}

没错,作者我本人想修改ureport2的loadReport方法,因为框架中的下载文件名一直是ureport-p.xlsx,所以我想修改。
作者在这里提供2种方法,有一种方法是我工作的老大给的建议

1:我的思路

image.png

新建一个类和jar包类的方法一模一样,因为自己的代码的优先级高于maven依赖的版本
参考网址:https://blog.csdn.net/yw_1207/article/details/80828236
代码如下:

package com.sf.energy.nplatform.report.adapter;

import com.bstek.ureport.cache.CacheUtils;
import com.bstek.ureport.console.RenderPageServletAction;
import com.bstek.ureport.console.cache.TempObjectCache;
import com.bstek.ureport.console.designer.ReportDefinitionWrapper;
import com.bstek.ureport.console.designer.ReportUtils;
import com.bstek.ureport.console.exception.ReportDesignException;
import com.bstek.ureport.definition.ReportDefinition;
import com.bstek.ureport.dsl.ReportParserLexer;
import com.bstek.ureport.dsl.ReportParserParser;
import com.bstek.ureport.export.ReportRender;
import com.bstek.ureport.expression.ErrorInfo;
import com.bstek.ureport.expression.ScriptErrorListener;
import com.bstek.ureport.parser.ReportParser;
import com.bstek.ureport.provider.report.ReportProvider;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;

/**
 * @Author bi xuan
 * @Date 1/27/2021 2:52 PM
 * @Version 1.0
 */
public class DesignerServletAction  extends RenderPageServletAction {
    private ReportRender reportRender;
    private ReportParser reportParser;
    private List<ReportProvider> reportProviders=new ArrayList<ReportProvider>();
    private String fileName;
    public String getFileName() {
        return fileName;
    }

    @Override
    public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method=retriveMethod(req);
        if(method!=null){
            invokeMethod(method, req, resp);
        }else{
            VelocityContext context = new VelocityContext();
            context.put("contextPath", req.getContextPath());
            resp.setContentType("text/html");
            resp.setCharacterEncoding("utf-8");
            Template template=ve.getTemplate("ureport-html/designer.html","utf-8");
            PrintWriter writer=resp.getWriter();
            template.merge(context, writer);
            writer.close();
        }
    }
    public void scriptValidation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String content=req.getParameter("content");
        ANTLRInputStream antlrInputStream=new ANTLRInputStream(content);
        ReportParserLexer lexer=new ReportParserLexer(antlrInputStream);
        CommonTokenStream tokenStream=new CommonTokenStream(lexer);
        ReportParserParser parser=new ReportParserParser(tokenStream);
        ScriptErrorListener errorListener=new ScriptErrorListener();
        parser.removeErrorListeners();
        parser.addErrorListener(errorListener);
        parser.expression();
        List<ErrorInfo> infos=errorListener.getInfos();
        writeObjectToJson(resp, infos);
    }

    public void conditionScriptValidation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String content=req.getParameter("content");
        ANTLRInputStream antlrInputStream=new ANTLRInputStream(content);
        ReportParserLexer lexer=new ReportParserLexer(antlrInputStream);
        CommonTokenStream tokenStream=new CommonTokenStream(lexer);
        ReportParserParser parser=new ReportParserParser(tokenStream);
        ScriptErrorListener errorListener=new ScriptErrorListener();
        parser.removeErrorListeners();
        parser.addErrorListener(errorListener);
        parser.expr();
        List<ErrorInfo> infos=errorListener.getInfos();
        writeObjectToJson(resp, infos);
    }


    public void parseDatasetName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String expr=req.getParameter("expr");
        ANTLRInputStream antlrInputStream=new ANTLRInputStream(expr);
        ReportParserLexer lexer=new ReportParserLexer(antlrInputStream);
        CommonTokenStream tokenStream=new CommonTokenStream(lexer);
        ReportParserParser parser=new ReportParserParser(tokenStream);
        parser.removeErrorListeners();
        ReportParserParser.DatasetContext ctx=parser.dataset();
        String datasetName=ctx.Identifier().getText();
        Map<String,String> result=new HashMap<String,String>();
        result.put("datasetName", datasetName);
        writeObjectToJson(resp, result);
    }
    public void savePreviewData(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String content=req.getParameter("content");
        content=decodeContent(content);
        InputStream inputStream= IOUtils.toInputStream(content,"utf-8");
        ReportDefinition reportDef=reportParser.parse(inputStream,"p");
        reportRender.rebuildReportDefinition(reportDef);
        IOUtils.closeQuietly(inputStream);
        TempObjectCache.putObject(PREVIEW_KEY, reportDef);
    }

    public void loadReport(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String file=req.getParameter("file");
        if(file==null){
            throw new ReportDesignException("Report file can not be null.");
        }
        //备注file不能修改,调试源码时发现这个loadReport被调用了两次,第一次是加载整个报表界面使用,第二次是加载报表列表使用,改了就会报错
        file= ReportUtils.decodeFileName(file);
        this.fileName = file;
//        this.fileName = this.fileName.replace("file:","").split(".")[0];
        this.fileName = this.fileName.replace("file:","").split("\\.")[0];
        Object obj=TempObjectCache.getObject(file);
        if(obj!=null && obj instanceof ReportDefinition){
            ReportDefinition reportDef=(ReportDefinition)obj;
            TempObjectCache.removeObject(file);
            writeObjectToJson(resp, new ReportDefinitionWrapper(reportDef));
        }else{
            ReportDefinition reportDef=reportRender.parseReport(file);
            writeObjectToJson(resp, new ReportDefinitionWrapper(reportDef));
        }
    }

    public void deleteReportFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String file=req.getParameter("file");
        if(file==null){
            throw new ReportDesignException("Report file can not be null.");
        }
        ReportProvider targetReportProvider=null;
        for(ReportProvider provider:reportProviders){
            if(file.startsWith(provider.getPrefix())){
                targetReportProvider=provider;
                break;
            }
        }
        if(targetReportProvider==null){
            throw new ReportDesignException("File ["+file+"] not found available report provider.");
        }
        targetReportProvider.deleteReport(file);
    }


    public void saveReportFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String file=req.getParameter("file");
        file=ReportUtils.decodeFileName(file);
        String content=req.getParameter("content");
        content=decodeContent(content);
        ReportProvider targetReportProvider=null;
        for(ReportProvider provider:reportProviders){
            if(file.startsWith(provider.getPrefix())){
                targetReportProvider=provider;
                break;
            }
        }
        if(targetReportProvider==null){
            throw new ReportDesignException("File ["+file+"] not found available report provider.");
        }
        targetReportProvider.saveReport(file, content);
        InputStream inputStream=IOUtils.toInputStream(content,"utf-8");
        ReportDefinition reportDef=reportParser.parse(inputStream, file);
        reportRender.rebuildReportDefinition(reportDef);
        CacheUtils.cacheReportDefinition(file, reportDef);
        IOUtils.closeQuietly(inputStream);
    }

    public void loadReportProviders(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        writeObjectToJson(resp, reportProviders);
    }

    public void setReportRender(ReportRender reportRender) {
        this.reportRender = reportRender;
    }

    public void setReportParser(ReportParser reportParser) {
        this.reportParser = reportParser;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
        super.setApplicationContext(applicationContext);
        Collection<ReportProvider> providers=applicationContext.getBeansOfType(ReportProvider.class).values();
        for(ReportProvider provider:providers){
            if(provider.disabled() || provider.getName()==null){
                continue;
            }
            reportProviders.add(provider);
        }
    }

    @Override
    public String url() {
        return "/designer";
    }
}

然后将其加入到spring管理中,我这里使用的和框架一样的方式,使用xml的bean标签加入到xml中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd
    ">
    <import resource="classpath:ureport-core-context.xml"/>
    <import resource="classpath:ureport-font-context.xml"/>
    
    <bean id="ureport.datasourceServletAction" class="com.bstek.ureport.console.designer.DatasourceServletAction"></bean>
    <bean id="ureport.resourceLoaderServletAction" class="com.bstek.ureport.console.res.ResourceLoaderServletAction"></bean>
    <bean id="ureport.DesignerServletAction" class="com.sf.energy.nplatform.report.adapter.DesignerServletAction">
        <property name="reportRender" ref="ureport.reportRender"></property>
        <property name="reportParser" ref="ureport.reportParser"></property>
    </bean>
    
    <bean id="ureport.searchFormDesignerAction" class="com.bstek.ureport.console.designer.SearchFormDesignerAction"></bean>
    
    <bean id="ureport.htmlPreviewServletAction" class="com.bstek.ureport.console.html.HtmlPreviewServletAction">
        <property name="exportManager" ref="ureport.exportManager"></property>
        <property name="reportBuilder" ref="ureport.reportBuilder"></property>
        <property name="reportRender" ref="ureport.reportRender"></property>
    </bean>
    <bean id="ureport.exportWordServletAction" class="com.bstek.ureport.console.word.ExportWordServletAction">
        <property name="exportManager" ref="ureport.exportManager"></property>
        <property name="reportBuilder" ref="ureport.reportBuilder"></property>
    </bean>
    
    <bean id="ureport.exportPdfServletAction" class="com.bstek.ureport.console.pdf.ExportPdfServletAction">
        <property name="exportManager" ref="ureport.exportManager"></property>
        <property name="reportBuilder" ref="ureport.reportBuilder"></property>
        <property name="reportRender" ref="ureport.reportRender"></property>
    </bean>

    <bean id="ureport.exportExcelServletAction" class="com.sf.energy.nplatform.report.adapter.ExportExcelServletActionAdapter">
        <property name="exportManager" ref="ureport.exportManager"></property>
        <property name="reportBuilder" ref="ureport.reportBuilder"></property>
    </bean>
    
    <bean id="ureport.exportExcel97ServletAction" class="com.bstek.ureport.console.excel.ExportExcel97ServletAction">
        <property name="exportManager" ref="ureport.exportManager"></property>
        <property name="reportBuilder" ref="ureport.reportBuilder"></property>
    </bean>
    
    <bean id="ureport.imageServletAction" class="com.bstek.ureport.console.image.ImageServletAction"></bean>
    <bean id="ureport.importExcelServletAction" class="com.bstek.ureport.console.importexcel.ImportExcelServletAction"></bean>
    
    <bean id="ureport.chartServletAction" class="com.bstek.ureport.console.chart.ChartServletAction"></bean>
    
    <bean id="ureport.httpSessionReportCache" class="com.bstek.ureport.console.cache.HttpSessionReportCache">
        <property name="disabled" value="${ureport.disableHttpSessionReportCache}"></property>
    </bean>
</beans>

修改的代码:

 <bean id="ureport.DesignerServletAction" class="com.sf.energy.nplatform.report.adapter.DesignerServletAction">
        <property name="reportRender" ref="ureport.reportRender"></property>
        <property name="reportParser" ref="ureport.reportParser"></property>
    </bean>

之前的calss为jar包里类的reference。
由于jvm的加载优先级问题,就会找bean的id找到我们的类进行实例化加到bean,替代了框架里的类。
到此我们思路结束了。

2:我工作老大的思路

image.png

新建一个adapter类
代码如下:

package com.sf.energy.nplatform.report.adapter;
import com.bstek.ureport.cache.CacheUtils;
import com.bstek.ureport.console.RenderPageServletAction;
import com.bstek.ureport.console.cache.TempObjectCache;
import com.bstek.ureport.console.designer.DesignerServletAction;
import com.bstek.ureport.console.designer.ReportDefinitionWrapper;
import com.bstek.ureport.console.designer.ReportUtils;
import com.bstek.ureport.console.exception.ReportDesignException;
import com.bstek.ureport.definition.ReportDefinition;
import com.bstek.ureport.dsl.ReportParserLexer;
import com.bstek.ureport.dsl.ReportParserParser;
import com.bstek.ureport.export.ReportRender;
import com.bstek.ureport.expression.ErrorInfo;
import com.bstek.ureport.expression.ScriptErrorListener;
import com.bstek.ureport.parser.ReportParser;
import com.bstek.ureport.provider.report.ReportProvider;
import org.antlr.v4.runtime.ANTLRInputStream;
import org.antlr.v4.runtime.CommonTokenStream;
import org.apache.commons.io.IOUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.*;

/**
 * @Author bi xuan
 * @Date 2021/1/13 18:19
 * @Version 1.0
 */
//@Component
public class DesignerServletActionAdapter extends RenderPageServletAction {
//    @Autowired
    private ReportRender reportRender;
//    @Autowired
    private ReportParser reportParser;
    private List<ReportProvider> reportProviders=new ArrayList<ReportProvider>();
    private String fileName;
    public String getFileName() {
        return fileName;
    }

    @Override
    public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method=retriveMethod(req);
        if(method!=null){
            invokeMethod(method, req, resp);
        }else{
            VelocityContext context = new VelocityContext();
            context.put("contextPath", req.getContextPath());
            resp.setContentType("text/html");
            resp.setCharacterEncoding("utf-8");
            Template template=ve.getTemplate("ureport-html/designer.html","utf-8");
            PrintWriter writer=resp.getWriter();
            template.merge(context, writer);
            writer.close();
        }
    }
    public void scriptValidation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String content=req.getParameter("content");
        ANTLRInputStream antlrInputStream=new ANTLRInputStream(content);
        ReportParserLexer lexer=new ReportParserLexer(antlrInputStream);
        CommonTokenStream tokenStream=new CommonTokenStream(lexer);
        ReportParserParser parser=new ReportParserParser(tokenStream);
        ScriptErrorListener errorListener=new ScriptErrorListener();
        parser.removeErrorListeners();
        parser.addErrorListener(errorListener);
        parser.expression();
        List<ErrorInfo> infos=errorListener.getInfos();
        writeObjectToJson(resp, infos);
    }

    public void conditionScriptValidation(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String content=req.getParameter("content");
        ANTLRInputStream antlrInputStream=new ANTLRInputStream(content);
        ReportParserLexer lexer=new ReportParserLexer(antlrInputStream);
        CommonTokenStream tokenStream=new CommonTokenStream(lexer);
        ReportParserParser parser=new ReportParserParser(tokenStream);
        ScriptErrorListener errorListener=new ScriptErrorListener();
        parser.removeErrorListeners();
        parser.addErrorListener(errorListener);
        parser.expr();
        List<ErrorInfo> infos=errorListener.getInfos();
        writeObjectToJson(resp, infos);
    }


    public void parseDatasetName(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String expr=req.getParameter("expr");
        ANTLRInputStream antlrInputStream=new ANTLRInputStream(expr);
        ReportParserLexer lexer=new ReportParserLexer(antlrInputStream);
        CommonTokenStream tokenStream=new CommonTokenStream(lexer);
        ReportParserParser parser=new ReportParserParser(tokenStream);
        parser.removeErrorListeners();
        ReportParserParser.DatasetContext ctx=parser.dataset();
        String datasetName=ctx.Identifier().getText();
        Map<String,String> result=new HashMap<String,String>();
        result.put("datasetName", datasetName);
        writeObjectToJson(resp, result);
    }
    public void savePreviewData(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String content=req.getParameter("content");
        content=decodeContent(content);
        InputStream inputStream= IOUtils.toInputStream(content,"utf-8");
        ReportDefinition reportDef=reportParser.parse(inputStream,"p");
        reportRender.rebuildReportDefinition(reportDef);
        IOUtils.closeQuietly(inputStream);
        TempObjectCache.putObject(PREVIEW_KEY, reportDef);
    }

    public void loadReport(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String file=req.getParameter("file");
        if(file==null){
            throw new ReportDesignException("Report file can not be null.");
        }
        //备注file不能修改,调试源码时发现这个loadReport被调用了两次,第一次是加载整个报表界面使用,第二次是加载报表列表使用,改了就会报错
        file= ReportUtils.decodeFileName(file);
        this.fileName = file;
//        this.fileName = this.fileName.replace("file:","").split(".")[0];
        this.fileName = this.fileName.replace("file:","").split("\\.")[0];
        Object obj=TempObjectCache.getObject(file);
        if(obj!=null && obj instanceof ReportDefinition){
            ReportDefinition reportDef=(ReportDefinition)obj;
            TempObjectCache.removeObject(file);
            writeObjectToJson(resp, new ReportDefinitionWrapper(reportDef));
        }else{
            ReportDefinition reportDef=reportRender.parseReport(file);
            writeObjectToJson(resp, new ReportDefinitionWrapper(reportDef));
        }
    }

    public void deleteReportFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String file=req.getParameter("file");
        if(file==null){
            throw new ReportDesignException("Report file can not be null.");
        }
        ReportProvider targetReportProvider=null;
        for(ReportProvider provider:reportProviders){
            if(file.startsWith(provider.getPrefix())){
                targetReportProvider=provider;
                break;
            }
        }
        if(targetReportProvider==null){
            throw new ReportDesignException("File ["+file+"] not found available report provider.");
        }
        targetReportProvider.deleteReport(file);
    }


    public void saveReportFile(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String file=req.getParameter("file");
        file=ReportUtils.decodeFileName(file);
        String content=req.getParameter("content");
        content=decodeContent(content);
        ReportProvider targetReportProvider=null;
        for(ReportProvider provider:reportProviders){
            if(file.startsWith(provider.getPrefix())){
                targetReportProvider=provider;
                break;
            }
        }
        if(targetReportProvider==null){
            throw new ReportDesignException("File ["+file+"] not found available report provider.");
        }
        targetReportProvider.saveReport(file, content);
        InputStream inputStream=IOUtils.toInputStream(content,"utf-8");
        ReportDefinition reportDef=reportParser.parse(inputStream, file);
        reportRender.rebuildReportDefinition(reportDef);
        CacheUtils.cacheReportDefinition(file, reportDef);
        IOUtils.closeQuietly(inputStream);
    }

    public void loadReportProviders(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        writeObjectToJson(resp, reportProviders);
    }

    public void setReportRender(ReportRender reportRender) {
        this.reportRender = reportRender;
    }

    public void setReportParser(ReportParser reportParser) {
        this.reportParser = reportParser;
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext)throws BeansException {
        super.setApplicationContext(applicationContext);
        Collection<ReportProvider> providers=applicationContext.getBeansOfType(ReportProvider.class).values();
        for(ReportProvider provider:providers){
            if(provider.disabled() || provider.getName()==null){
                continue;
            }
            reportProviders.add(provider);
        }
    }

    @Override
    public String url() {
        return "/designer";
    }
}

然后修改自己的xml

    <bean id="ureport.DesignerServletAction" class="com.sf.energy.nplatform.report.adapter.DesignerServletActionAdapter">
        <property name="reportRender" ref="ureport.reportRender"></property>
        <property name="reportParser" ref="ureport.reportParser"></property>
    </bean>

哈哈,你可能发现这不是一模一样吗?
其实我厚着脸皮承认其实都是我工作老大给的思路,
接下来是前方高能:作者自己的思路
因为我才毕业半年,在我接触到Java时就是springboot了,我不喜欢xml文件,所以我要用注解


image.png

xml注释掉


image.png

抱着好奇的心态run了一下,可以,这时开始头脑一片问号
@Autowired注解是根据byType进行加载的
这明显我的type是DesignerServletActionAdapter,jar包的是DesignServletAction,这类型都不同,是怎么替换的啊!
我决定查看调用栈一探究竟
image.png

image.png

image.png

image.png

image.png

没错。他是根据url这个方法来获取类的!(其实这里还是有一个疑惑,因为我重写的类的方法返回的还是/desinger,难到是因为我写的优先级方法高吗?)


image.png

判断url的源码为:

/*******************************************************************************
 * Copyright 2017 Bstek
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License.  You may obtain a copy
 * of the License at
 * 
 *   http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
 * License for the specific language governing permissions and limitations under
 * the License.
 ******************************************************************************/
package com.bstek.ureport.console;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

/**
 * @author Jacky.gao
 * @since 2017年1月25日
 */
public class UReportServlet extends HttpServlet {
    private static final long serialVersionUID = 533049461276487971L;
    public static final String URL = "/ureport";
    private Map<String, ServletAction> actionMap = new HashMap<String, ServletAction>();

    @Override
    public void init(ServletConfig config) throws ServletException {
        super.init(config);
        WebApplicationContext applicationContext = getWebApplicationContext(config);
        Collection<ServletAction> handlers = applicationContext.getBeansOfType(ServletAction.class).values();
        for (ServletAction handler : handlers) {
            String url = handler.url();
            if (actionMap.containsKey(url)) {
                throw new RuntimeException("Handler [" + url + "] already exist.");
            }
            actionMap.put(url, handler);
        }
    }
    
    protected WebApplicationContext getWebApplicationContext(ServletConfig config){
        return WebApplicationContextUtils.getWebApplicationContext(config.getServletContext());
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String path = req.getContextPath() + URL;
        String uri = req.getRequestURI();
        String targetUrl = uri.substring(path.length());
        if (targetUrl.length() < 1) {
            outContent(resp, "Welcome to use ureport,please specify target url.");
            return;
        }
        int slashPos = targetUrl.indexOf("/", 1);
        if (slashPos > -1) {
            targetUrl = targetUrl.substring(0, slashPos);
        }
        ServletAction targetHandler = actionMap.get(targetUrl);
        if (targetHandler == null) {
            outContent(resp, "Handler [" + targetUrl + "] not exist.");
            return;
        }
        RequestHolder.setRequest(req);
        try{
            targetHandler.execute(req, resp);
        }catch(Exception ex){
            resp.setCharacterEncoding("UTF-8");
            PrintWriter pw=resp.getWriter();
            Throwable e=buildRootException(ex);
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            String errorMsg = e.getMessage();
            if(StringUtils.isBlank(errorMsg)){
                errorMsg=e.getClass().getName();
            }
            pw.write(errorMsg);
            pw.close();             
            throw new ServletException(ex); 
        }finally{
            RequestHolder.clean();
        }
    }
    private Throwable buildRootException(Throwable throwable){
        if(throwable.getCause()==null){
            return throwable;
        }
        return buildRootException(throwable.getCause());
    }

    private void outContent(HttpServletResponse resp, String msg) throws IOException {
        resp.setContentType("text/html");
        PrintWriter pw = resp.getWriter();
        pw.write("<html>");
        pw.write("<header><title>UReport Console</title></header>");
        pw.write("<body>");
        pw.write(msg);
        pw.write("</body>");
        pw.write("</html>");
        pw.flush();
        pw.close();
    }
}

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 211,376评论 6 491
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,126评论 2 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 156,966评论 0 347
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,432评论 1 283
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,519评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,792评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,933评论 3 406
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,701评论 0 266
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,143评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,488评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,626评论 1 340
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,292评论 4 329
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,896评论 3 313
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,742评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,977评论 1 265
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,324评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,494评论 2 348

推荐阅读更多精彩内容