kkFileView(二)关键代码分析(1)

2021SC@SDUSC

此项目是由Springboot框架搭建,前端使用了freemaker生成页面。

(一)

首先我们分析了项目的目录结构

可以得到项目的前端代码在resources包中,static中存放着css,js,bootstrap等静态文件,web中存放ftl类型的freemaker文件。

java包中存放着项目的核心后端代码,其中FilePreviewApplication为启动项目的主程序。

@SpringBootApplication
@EnableScheduling
@ComponentScan(value = "cn.keking.*")
public class FilePreviewApplication {
	public static void main(String[] args) {
        SpringApplication.run(FilePreviewApplication.class, args);
	}
}

其中@SpringBootApplication 注解为Springboot项目的入口。

@EnableScheduling注解 在项目启动类上加上该注解,可以实现定时器任务(与@Component和@Scheduled搭配使用)在这里我们先不分析这个作用。

@ComponentScan注解中指定要扫描的包文件。

(二)确定Controller

在Springboot结构中,控制层controller的作用为接收客户端的请求,再调用Service层业务逻辑,获取数据,传递给视图层客户端并呈现。

在controller中,实现文件转换和预览的类为OnlinePreviewController。

在方法上使用@RequestMapping注解 使该方法负责处理该url并且是post方法传递过来的请求。文件预览的主要方法如下:

/**
     * 文件预览
     * @param url
     * @param model
     * @param req
     * @return
     */
    @RequestMapping(value = "/onlinePreview")
    public String onlinePreview(String url, Model model, HttpServletRequest req) {
        // 解析文件属性
        FileAttribute fileAttribute = fileUtils.getFileAttribute(url);
        req.setAttribute("fileKey", req.getParameter("fileKey"));
        model.addAttribute("pdfDownloadDisable", ConfigConstants.getPdfDownloadDisable()); // true : 禁止下载转换生成的pdf文件
        model.addAttribute("officePreviewType", req.getParameter("officePreviewType")); // 转换后的文件展示的类型  默认为图片(image),可配置为pdf
        // 获取文件格式转换Service
        FilePreview filePreview = previewFactory.get(fileAttribute);
        logger.info("预览文件url:{},previewType:{}", url, fileAttribute.getType());
        // 核心方法: 文件类型转换,预览
        return filePreview.filePreviewHandle(url, model, fileAttribute);
    }

其中FileAttribute类为文件的属性,通过传来的url,用工具类fileUtils中getFileAttribute(url)方法解析文件的属性。

setAttribute()和getAttribute()方法:设置、获取域对象的共享数据。

接着获取service层,这里调用了工厂类FilePreview的方法进行类型确定,调用何种类型的方法。

@Service
public class FilePreviewFactory {

    private final ApplicationContext context;

    public FilePreviewFactory(ApplicationContext context) {
        this.context = context;
    }

    /**
     * 根据 fileAttribute 获取对应文件转换的FilePreviewImpl
     * @param fileAttribute
     * @return
     */
    public FilePreview get(FileAttribute fileAttribute) {
        Map<String, FilePreview> filePreviewMap = context.getBeansOfType(FilePreview.class);
        return filePreviewMap.get(fileAttribute.getType().getInstanceName());
    }
}

get方法通过文件类型返回的FilePreview接口类。impl包中所有的接口类都继承于该接口,继承了接口的方法filePreviewHandle(),根据调用的不同类中的不同方法返回一个字符串。字符串自动匹配对应的ftl文件。

经验分享 程序员 微信小程序 职场和发展