欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java集成Onlyoffice的示例代碼及場景分析

 更新時間:2025年05月27日 11:30:34   作者:想要變瘦的小碼頭  
這篇文章主要介紹了Java集成Onlyoffice的示例代碼及場景分析,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友參考下吧

需求場景:實現(xiàn)文檔的在線編輯,團隊協(xié)作

總結(jié):兩個接口 + 前端頁面 + 配置項

接口1:一個接口,將onlyoffice前端需要的配置項返回給前端(文檔地址、是否編輯模式...)

前端:接受配置項,集成onlyoffice的js文件,展示文檔 

接口2:一個回調(diào)接口,用于onlyoffice前端的文件保存后的調(diào)用方法

一些配置項:application 里面配置 服務(wù)器的地址,token 等 ,maven 引入依賴。

文章結(jié)尾提供官方示例代碼:

注意:

1、docs-integration-sdk 2024年12月,國內(nèi)騰訊的中央倉庫下不了,我不想換鏡像,就注釋掉,用的離線包。

2、加了一個pom 的依賴,不加啟動報錯

<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.5.13</version>
</dependency>

接口1:文檔地址必須可以讓onlyofficeu所在的服務(wù)器可以訪問到,可以是本地磁盤的映射,可以是 MINIO。文檔應(yīng)當(dāng)還有一個唯一的Key;

public String index(@RequestParam("fileName") final String fileName,
                        @RequestParam(value = "action", required = false) final String actionParam,
                        @RequestParam(value = "type", required = false) final String typeParam,
                        @RequestParam(value = "actionLink", required = false) final String actionLink,
                        @CookieValue(value = "uid") final String uid,
                        @CookieValue(value = "ulang") final String lang,
                        final Model model) throws JsonProcessingException {
        Action action = null;
        Type type = Type.DESKTOP;
        Locale locale = new Locale("en");
        if (actionParam != null) {
            action = Action.valueOf(actionParam);
        }
        if (typeParam != null) {
            type = Type.valueOf(typeParam.toUpperCase());
        }
        List<String> langsAndKeys = Arrays.asList(langs.split("\\|"));
        for (String langAndKey : langsAndKeys) {
            String[] couple = langAndKey.split(":");
            if (couple[0].equals(lang)) {
                String[] langAndCountry = couple[0].split("-");
                locale = new Locale(langAndCountry[0], langAndCountry.length > 1 ? langAndCountry[1] : "");
            }
        }
        Optional<User> optionalUser = userService.findUserById(Integer.parseInt(uid));
        // if the user is not present, return the ONLYOFFICE start page
        if (!optionalUser.isPresent()) {
            return "index.html";
        }
        Config config = configService.createConfig(
                fileName,
                action,
                type
        );
        JSONObject actionData = null;
        if (actionLink != null && !actionLink.isEmpty()) {
            actionData = new JSONObject(actionLink);
        }
        config.getEditorConfig().setActionLink(actionData);
        config.getEditorConfig().setLang(locale.toLanguageTag());
        model.addAttribute("model", config);
        // create the document service api URL and add it to the model
        model.addAttribute("docserviceApiUrl", urlManager.getDocumentServerApiUrl());
        // get an image and add it to the model
        model.addAttribute("dataInsertImage",  getInsertImage());
        // get a document for comparison and add it to the model
        model.addAttribute("dataDocument",  getCompareFile());
        // get recipients data for mail merging and add it to the model
        model.addAttribute("dataSpreadsheet", getSpreadsheet());
        // get user data for mentions and add it to the model
        model.addAttribute("usersForMentions", getUserMentions(uid));
        model.addAttribute("usersInfo", getUsersInfo(uid));
        // get user data for protect and add it to the model
        model.addAttribute("usersForProtect", getUserProtect(uid));
        return "editor.html";
    }

接口2:回調(diào)保存,其中的  {\"error\":\"0\"} 是告訴onlyOffice回調(diào)接口是沒問題的,這樣就可以在線編輯文檔了,否則的話會彈出窗口說明。

public String track(final HttpServletRequest request,  // track file changes
                        @RequestParam("fileName") final String fileName,
                        @RequestParam("userAddress") final String userAddress,
                        @RequestBody final Callback body) {
        Callback callback;
        try {
            String bodyString = objectMapper
                    .writeValueAsString(body);  // write the request body to the object mapper as a string
            if (bodyString.isEmpty()) {  // if the request body is empty, an error occurs
                throw new RuntimeException("{\"error\":1,\"message\":\"Request payload is empty\"}");
            }
            String authorizationHeader = request.getHeader(settingsManager.getSecurityHeader());
            callback = callbackService.verifyCallback(body, authorizationHeader);
            callbackService.processCallback(callback, fileName);
        } catch (Exception e) {
            String message = e.getMessage();
            if (!message.contains("\"error\":1")) {
                e.printStackTrace();
            }
            return message;
        }
        return "{\"error\":\"0\"}";
    }

前端展示

<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no, minimal-ui" />
        <meta name="apple-mobile-web-app-capable" content="yes" />
        <meta name="mobile-web-app-capable" content="yes" />
        <!--
        *
        * (c) Copyright Ascensio System SIA 2024
        *
        * 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.
        *
        -->
        <title>ONLYOFFICE</title>
        <link rel="icon" th:href="@{/css/img/{icon}.ico(icon=${model.getDocumentType()})}" rel="external nofollow"  type="image/x-icon"/>
        <link rel="stylesheet" type="text/css" href="css/editor.css" rel="external nofollow"  />
        <script type="text/javascript" th:src="@{${docserviceApiUrl}}"></script>
        <script th:inline="javascript">
                var docEditor;
                var config;
                var innerAlert = function (message, inEditor) {
                    if (console && console.log)
                        console.log(message);
                    if (inEditor && docEditor)
                        docEditor.showMessage(message);
                };
                // the application is loaded into the browser
                var onAppReady = function () {
                    innerAlert("Document editor ready");
                };
                // the document is modified
                var onDocumentStateChange = function (event) {
                    var title = document.title.replace(/\*$/g, "");
                    document.title = title + (event.data ? "*" : "");
                };
                // the user is trying to switch the document from the viewing into the editing mode
                var onRequestEditRights = function () {
                    location.href = location.href.replace(RegExp("\&?action=\\w+", "i"), "") + "&action=edit";
                };
                // an error or some other specific event occurs
                var onError = function (event) {
                    if (event) innerAlert(event.data);
                };
                // the document is opened for editing with the old document.key value
                var onOutdatedVersion = function (event) {
                    location.reload(true);
                };
                // replace the link to the document which contains a bookmark
                var replaceActionLink = function(href, linkParam) {
                    var link;
                    var actionIndex = href.indexOf("&actionLink=");
                    if (actionIndex != -1) {
                        var endIndex = href.indexOf("&", actionIndex + "&actionLink=".length);
                        if (endIndex != -1) {
                            link = href.substring(0, actionIndex) + href.substring(endIndex) + "&actionLink=" + encodeURIComponent(linkParam);
                        } else {
                            link = href.substring(0, actionIndex) + "&actionLink=" + encodeURIComponent(linkParam);
                        }
                    } else {
                        link = href + "&actionLink=" + encodeURIComponent(linkParam);
                    }
                    return link;
                }
                // the user is trying to get link for opening the document which contains a bookmark, scrolling to the bookmark position
                var onMakeActionLink = function (event) {
                    var actionData = event.data;
                    var linkParam = JSON.stringify(actionData);
                    docEditor.setActionLink(replaceActionLink(location.href, linkParam));
                };
                // the meta information of the document is changed via the meta command
                var onMetaChange = function (event) {
                    if (event.data.favorite !== undefined) {
                        var favorite = !!event.data.favorite;
                        var title = document.title.replace(/^\☆/g, "");
                        document.title = (favorite ? "☆" : "") + title;
                        docEditor.setFavorite(favorite);
                    }
                    innerAlert("onMetaChange: " + JSON.stringify(event.data));
                };
                var dataInsertImage = [[${dataInsertImage}]];
                // the user is trying to insert an image by clicking the Image from Storage button
                var onRequestInsertImage = function(event) {
                    const temp = Object.assign({}, {"c": event.data.c}, dataInsertImage);
                    docEditor.insertImage(temp);
                };
                var dataDocument = [[${dataDocument}]];
                // the user is trying to select document for comparing by clicking the Document from Storage button
                var onRequestSelectDocument = function(event) {
                    const temp = Object.assign({"c": event.data.c}, JSON.parse(dataDocument));
                    docEditor.setRequestedDocument(temp);
                };
                var dataSpreadsheet = [[${dataSpreadsheet}]];
                // the user is trying to select recipients data by clicking the Mail merge button
                var onRequestSelectSpreadsheet = function (event) {
                    const temp = Object.assign({"c": event.data.c}, JSON.parse(dataSpreadsheet));
                    docEditor.setRequestedSpreadsheet(temp);
                };
                config = [[${model}]];
                if (config.editorConfig.user.name == "Anonymous") {
                    config.editorConfig.user.name = "";
                }
                var onRequestSaveAs = function (event) {  //  the user is trying to save file by clicking Save Copy as... button
                    var title = event.data.title;
                    var url = event.data.url;
                    var data = {
                        title: title,
                        url: url
                    };
                    let xhr = new XMLHttpRequest();
                    xhr.open("POST", "saveas");
                    xhr.setRequestHeader('Content-Type', 'application/json');
                    xhr.send(JSON.stringify(data));
                    xhr.onload = function () {
                        innerAlert(xhr.responseText);
                        innerAlert(JSON.parse(xhr.responseText).file, true);
                    }
                };
                var onRequestRename = function(event) { //  the user is trying to rename file by clicking Rename... button
                    innerAlert("onRequestRename: " + JSON.stringify(event.data));
                    var newfilename = event.data;
                    var data = {
                        fileName: newfilename,
                        fileKey: config.document.key,
                        fileType: config.document.fileType
                    };
                    let xhr = new XMLHttpRequest();
                    xhr.open("POST", "rename");
                    xhr.setRequestHeader('Content-Type', 'application/json');
                    xhr.send(JSON.stringify(data));
                    xhr.onload = function () {
                        innerAlert(xhr.responseText);
                    }
                };
                var onRequestOpen = function(event) {  // user open external data source
                    innerAlert("onRequestOpen");
                    var windowName = event.data.windowName;
                    requestReference(event.data, function (data) {
                        if (data.error) {
                            var winEditor = window.open("", windowName);
                            winEditor.close();
                            innerAlert(data.error, true);
                            return;
                        }
                        var link = data.link;
                        window.open(link, windowName);
                    });
                };
                var onRequestReferenceData = function(event) {  // user refresh external data source
                    innerAlert("onRequestReferenceData");
                    requestReference(event.data, function (data) {
                        docEditor.setReferenceData(data);
                    });
                };
                var requestReference = function(data, callback) {
                    innerAlert(data);
                    let xhr = new XMLHttpRequest();
                    xhr.open("POST", "reference");
                    xhr.setRequestHeader("Content-Type", "application/json");
                    xhr.send(JSON.stringify(data));
                    xhr.onload = function () {
                        innerAlert(xhr.responseText);
                        callback(JSON.parse(xhr.responseText));
                    }
                };
                var onRequestHistory = function () {
                    var xhr = new XMLHttpRequest();
                    xhr.open("GET", "history?fileName=" + config.document.title, false);
                    xhr.send();
                    if (xhr.status == 200) {
                        var historyInfo = JSON.parse(xhr.responseText);
                        docEditor.refreshHistory(historyInfo);
                    }
                };
                var onRequestHistoryData = function (event) {
                    var version = event.data;
                    var historyDataUri = "historydata?fileName=" + config.document.title
                        + "&version=" + version;
                    var xhr = new XMLHttpRequest();
                    xhr.open("GET", historyDataUri, false);
                    xhr.send();
                    if (xhr.status == 200) {
                        var historyData = JSON.parse(xhr.responseText);
                        docEditor.setHistoryData(historyData);
                    }
                };
                var onRequestHistoryClose = function() {
                    document.location.reload();
                };
                function onRequestRestore(event) {
                  const query = new URLSearchParams(window.location.search)
                  const payload = {
                    fileName: query.get('fileName'),
                    version: event.data.version
                  }
                  const request = new XMLHttpRequest()
                  request.open('PUT', 'restore')
                  request.setRequestHeader('Content-Type', 'application/json')
                  request.send(JSON.stringify(payload))
                  request.onload = function () {
                    const response = JSON.parse(request.responseText);
                    if (response.success && !response.error) {
                      var historyInfoUri = "history?fileName=" + config.document.title;
                      var xhr = new XMLHttpRequest();
                      xhr.open("GET", historyInfoUri, false);
                      xhr.send();
                      if (xhr.status == 200) {
                          var historyInfo = JSON.parse(xhr.responseText);
                          docEditor.refreshHistory(historyInfo);
                      }
                    } else {
                      innerAlert(response.error);
                    }
                  }
                };
                var onRequestUsers = function (event) {
                    if (event && event.data) {
                         var c = event.data.c;
                        }
                    switch (c) {
                        case "info":
                            users = [];
                            var allUsers = [[${usersInfo}]];
                            for (var i = 0; i < event.data.id.length; i++) {
                                for (var j = 0; j < allUsers.length; j++) {
                                     if (allUsers[j].id == event.data.id[i]) {
                                        users.push(allUsers[j]);
                                        break;
                                    }
                                }
                            }
                            break;
                        case "protect":
                            var users = [[${usersForProtect}]];
                            break;
                        default:
                            users = [[${usersForMentions}]];
                    }
                    docEditor.setUsers({
                        "c": c,
                        "users": users,
                    });
                };
                var onRequestSendNotify = function(event) {  // the user is mentioned in a comment
                    event.data.actionLink = replaceActionLink(location.href, JSON.stringify(event.data.actionLink));
                    var data = JSON.stringify(event.data);
                    innerAlert("onRequestSendNotify: " + data);
                };
                config.width = "100%";
                config.height = "100%";
                config.events = {
                    "onAppReady": onAppReady,
                    "onDocumentStateChange": onDocumentStateChange,
                    "onError": onError,
                    "onOutdatedVersion": onOutdatedVersion,
                    "onMakeActionLink": onMakeActionLink,
                    "onMetaChange": onMetaChange,
                    "onRequestInsertImage": onRequestInsertImage,
                    "onRequestSelectDocument": onRequestSelectDocument,
                    "onRequestSelectSpreadsheet": onRequestSelectSpreadsheet
                };
                if (config.editorConfig.user.id != 4) {
                    // add mentions for not anonymous users
                    config.events['onRequestUsers'] = onRequestUsers;
                    config.events['onRequestSaveAs'] = onRequestSaveAs;
                    // the user is mentioned in a comment
                    config.events['onRequestSendNotify'] = onRequestSendNotify;
                    // prevent file renaming for anonymous users
                    config.events['onRequestRename'] = onRequestRename;
                    config.events['onRequestReferenceData'] = onRequestReferenceData;
                    // prevent switch the document from the viewing into the editing mode for anonymous users
                    config.events['onRequestEditRights'] = onRequestEditRights;
                    config.events['onRequestOpen'] = onRequestOpen;
                    config.events['onRequestHistory'] = onRequestHistory;
                    config.events['onRequestHistoryData'] = onRequestHistoryData;
                    if (config.editorConfig.user.id != 3) {
                        config.events['onRequestHistoryClose'] = onRequestHistoryClose;
                        config.events['onRequestRestore'] = onRequestRestore;
                    }
                }
                var сonnectEditor = function () {
                    docEditor = new DocsAPI.DocEditor("iframeEditor", config);
                };
                if (window.addEventListener) {
                    window.addEventListener("load", сonnectEditor);
                } else if (window.attachEvent) {
                    window.attachEvent("load", сonnectEditor);
                }
        </script>
    </head>
    <body>
        <div class="form">
            <div id="iframeEditor"></div>
        </div>
    </body>
</html>

 完整代碼可以下載,不搞VIP、付費

到此這篇關(guān)于Java集成Onlyoffice的文章就介紹到這了,更多相關(guān)Java集成Onlyoffice內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

您可能感興趣的文章:

相關(guān)文章

  • Java?list移除元素相關(guān)操作指南

    Java?list移除元素相關(guān)操作指南

    這篇文章主要給大家介紹了關(guān)于Java?list移除元素相關(guān)操作的相關(guān)資料,文中介紹的方法包括增強for循環(huán)、迭代器、Stream流和removeIf()方法,同時還介紹了如何從一個列表中刪除包含另一個列表元素的方法,以及如何刪除指定下標位置的元素,需要的朋友可以參考下
    2024-12-12
  • 詳解SpringBoot中的統(tǒng)一功能處理的實現(xiàn)

    詳解SpringBoot中的統(tǒng)一功能處理的實現(xiàn)

    這篇文章主要為大家詳細介紹了SpringBoot如何實現(xiàn)統(tǒng)一功能處理,文中的示例代碼講解詳細,對我們學(xué)習(xí)或工作有一定借鑒價值,需要的可以參考一下
    2023-01-01
  • 如何避免Apache?Beanutils屬性copy

    如何避免Apache?Beanutils屬性copy

    這篇文章主要為大家介紹了如何避免Apache?Beanutils屬性copy的分析詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪
    2023-01-01
  • java——多線程基礎(chǔ)

    java——多線程基礎(chǔ)

    Java多線程實現(xiàn)方式有兩種,第一種是繼承Thread類,第二種是實現(xiàn)Runnable接口,兩種有很多差異,下面跟著本文一起學(xué)習(xí)吧,希望能給你帶來幫助
    2021-07-07
  • MyBatis配置文件的寫法和簡單使用

    MyBatis配置文件的寫法和簡單使用

    MyBatis 是支持定制化 SQL、存儲過程以及高級映射的優(yōu)秀的持久層框架。這篇文章主要介紹了MyBatis配置文件的寫法和簡單使用,需要的朋友參考下
    2017-01-01
  • maven的三種工程pom、jar、war的區(qū)別

    maven的三種工程pom、jar、war的區(qū)別

    這篇文章主要介紹了maven的三種工程pom、jar、war的區(qū)別,詳細的介紹pom、jar、war和區(qū)別,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2018-11-11
  • 微信游戲打飛機游戲制作(java模擬微信打飛機游戲)

    微信游戲打飛機游戲制作(java模擬微信打飛機游戲)

    java模擬微信打飛機游戲,大家參考使用吧
    2013-12-12
  • 解析spring boot與ireport 整合問題

    解析spring boot與ireport 整合問題

    本文通過實例代碼給大家介紹了spring boot 與 ireport 整合問題,關(guān)于pom文件依賴的問題通過實例代碼給大家介紹的非常詳細,需要的朋友參考下吧
    2021-10-10
  • java編程中拷貝數(shù)組的方式及相關(guān)問題分析

    java編程中拷貝數(shù)組的方式及相關(guān)問題分析

    這篇文章主要介紹了java編程中拷貝數(shù)組的方式及相關(guān)問題分析,分享了Java中數(shù)組復(fù)制的四種方式,其次對二維數(shù)組的簡單使用有一段代碼示例,具有一定參考價值,需要的朋友可以了解下。
    2017-11-11
  • 詳解Java中List的正確的刪除方法

    詳解Java中List的正確的刪除方法

    這篇文章主要為大家詳細介紹了Java中List的正確的刪除方法,文中的示例代碼講解詳細,對我們學(xué)習(xí)有一定幫助,需要的可以參考一下
    2022-05-05

最新評論