<kbd id="m0mea"><tt id="m0mea"></tt></kbd>
  • <s id="m0mea"><code id="m0mea"></code></s>
    <tbody id="m0mea"><u id="m0mea"></u></tbody><rt id="m0mea"><menu id="m0mea"></menu></rt>
  • <legend id="m0mea"><input id="m0mea"></input></legend>

    SpringBoot2.x 整合 Ueditor
    2022-09-06 22:57:07


    SpringBoot2.x 整合 Ueditor_加載


    SpringBoot2.x 整合 Ueditor_javascript_02

    文章目錄

    一、基礎準備
    1. 創建項目并引入依賴

    boot-ueditor

    <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.5.4</version>
    <relativePath/> <!-- lookup parent from repository -->
    </parent>

    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
    <groupId>org.json</groupId>
    <artifactId>json</artifactId>
    <version>20190722</version>
    </dependency>
    <dependency>
    <groupId>commons-fileupload</groupId>
    <artifactId>commons-fileupload</artifactId>
    <version>1.3.2</version>
    </dependency>
    <dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.9</version>
    </dependency>
    2. 下載Ueditor源碼

    下載地址:??https://github.com/fex-team/ueditor/tree/dev-2.0.0??

    3. Java代碼整合

    將??ueditor-dev-2.0.0版本ueditorjspsrc??下的com文件夾整體復制到項目Java目錄下面

    SpringBoot2.x 整合 Ueditor_spring boot_03

    SpringBoot2.x 整合 Ueditor_html_04


    SpringBoot2.x 整合 Ueditor_html_05

    4. 靜態文件整合
    • ①把??ueditor??整個文件夾復制到static目錄下面
    • ②把??ueditorjspconfig.json??復制到ueditor的根目錄下面
    • ③在resources目錄下面創建js文件夾存放??jquery2.1.3.min.js??

    SpringBoot2.x 整合 Ueditor_html_06

    二、靜態頁面+控制層

    在??resources???目錄下面創建??templates??

    2.1. index.html
    <!DOCTYPE>
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
    <title>完整demo</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.config.js}"></script>
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.all.js}"> </script>
    <!--建議手動加在語言,避免在ie下有時因為加載語言失敗導致編輯器加載失敗-->
    <!--這里加載的語言文件會覆蓋你在配置項目里添加的語言類型,比如你在配置項目里配置的是英文,這里加載的中文,那最后就是中文-->
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/lang/zh-cn/zh-cn.js}"></script>
    <style type="text/css">
    div{
    width:100%;
    }
    </style>
    </head>
    <body>
    <div>
    <h1>完整demo</h1>
    <script id="editor" type="text/plain" style="width:1024px;height:500px;"></script>
    </div>
    <div id="btns">
    <div>
    <button onclick="getAllHtml()">獲得整個html的內容</button>
    <button onclick="getContent()">獲得內容</button>
    <button onclick="setContent()">寫入內容</button>
    <button onclick="setContent(true)">追加內容</button>
    <button onclick="getContentTxt()">獲得純文本</button>
    <button onclick="getPlainTxt()">獲得帶格式的純文本</button>
    <button onclick="hasContent()">判斷是否有內容</button>
    <button onclick="setFocus()">使編輯器獲得焦點</button>
    <button onmousedown="isFocus(event)">編輯器是否獲得焦點</button>
    <button onmousedown="setblur(event)" >編輯器失去焦點</button>

    </div>
    <div>
    <button onclick="getText()">獲得當前選中的文本</button>
    <button onclick="insertHtml()">插入給定的內容</button>
    <button id="enable" onclick="setEnabled()">可以編輯</button>
    <button onclick="setDisabled()">不可編輯</button>
    <button onclick=" UE.getEditor('editor').setHide()">隱藏編輯器</button>
    <button onclick=" UE.getEditor('editor').setShow()">顯示編輯器</button>
    <button onclick=" UE.getEditor('editor').setHeight(300)">設置高度為300默認關閉了自動長高</button>
    </div>

    <div>
    <button onclick="getLocalData()" >獲取草稿箱內容</button>
    <button onclick="clearLocalData()" >清空草稿箱</button>
    </div>

    </div>
    <div>
    <button onclick="createEditor()">
    創建編輯器</button>
    <button onclick="deleteEditor()">
    刪除編輯器</button>
    </div>

    <script type="text/javascript">

    //實例化編輯器
    //建議使用工廠方法getEditor創建和引用編輯器實例,如果在某個閉包下引用該編輯器,直接調用UE.getEditor('editor')就能拿到相關的實例
    var ue = UE.getEditor('editor');


    function isFocus(e){
    alert(UE.getEditor('editor').isFocus());
    UE.dom.domUtils.preventDefault(e)
    }
    function setblur(e){
    UE.getEditor('editor').blur();
    UE.dom.domUtils.preventDefault(e)
    }
    function insertHtml() {
    var value = prompt('插入html代碼', '');
    UE.getEditor('editor').execCommand('insertHtml', value)
    }
    function createEditor() {
    enableBtn();
    UE.getEditor('editor');
    }
    function getAllHtml() {
    alert(UE.getEditor('editor').getAllHtml())
    }
    function getContent() {
    var arr = [];
    arr.push("使用editor.getContent()方法可以獲得編輯器的內容");
    arr.push("內容為:");
    arr.push(UE.getEditor('editor').getContent());
    alert(arr.join(" "));
    }
    function getPlainTxt() {
    var arr = [];
    arr.push("使用editor.getPlainTxt()方法可以獲得編輯器的帶格式的純文本內容");
    arr.push("內容為:");
    arr.push(UE.getEditor('editor').getPlainTxt());
    alert(arr.join(' '))
    }
    function setContent(isAppendTo) {
    var arr = [];
    arr.push("使用editor.setContent('歡迎使用ueditor')方法可以設置編輯器的內容");
    UE.getEditor('editor').setContent('歡迎使用ueditor', isAppendTo);
    alert(arr.join(" "));
    }
    function setDisabled() {
    UE.getEditor('editor').setDisabled('fullscreen');
    disableBtn("enable");
    }

    function setEnabled() {
    UE.getEditor('editor').setEnabled();
    enableBtn();
    }

    function getText() {
    //當你點擊按鈕時編輯區域已經失去了焦點,如果直接用getText將不會得到內容,所以要在選回來,然后取得內容
    var range = UE.getEditor('editor').selection.getRange();
    range.select();
    var txt = UE.getEditor('editor').selection.getText();
    alert(txt)
    }

    function getContentTxt() {
    var arr = [];
    arr.push("使用editor.getContentTxt()方法可以獲得編輯器的純文本內容");
    arr.push("編輯器的純文本內容為:");
    arr.push(UE.getEditor('editor').getContentTxt());
    alert(arr.join(" "));
    }
    function hasContent() {
    var arr = [];
    arr.push("使用editor.hasContents()方法判斷編輯器里是否有內容");
    arr.push("判斷結果為:");
    arr.push(UE.getEditor('editor').hasContents());
    alert(arr.join(" "));
    }
    function setFocus() {
    UE.getEditor('editor').focus();
    }
    function deleteEditor() {
    disableBtn();
    UE.getEditor('editor').destroy();
    }
    function disableBtn(str) {
    var div = document.getElementById('btns');
    var btns = UE.dom.domUtils.getElementsByTagName(div, "button");
    for (var i = 0, btn; btn = btns[i++];) {
    if (btn.id == str) {
    UE.dom.domUtils.removeAttributes(btn, ["disabled"]);
    } else {
    btn.setAttribute("disabled", "true");
    }
    }
    }
    function enableBtn() {
    var div = document.getElementById('btns');
    var btns = UE.dom.domUtils.getElementsByTagName(div, "button");
    for (var i = 0, btn; btn = btns[i++];) {
    UE.dom.domUtils.removeAttributes(btn, ["disabled"]);
    }
    }

    function getLocalData () {
    alert(UE.getEditor('editor').execCommand( "getlocaldata" ));
    }

    function clearLocalData () {
    UE.getEditor('editor').execCommand( "clearlocaldata" );
    alert("已清空草稿箱")
    }
    </script>
    </body>
    </html>
    2.2. demo1.html
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
    <title>UEditor Demo</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>

    <script type="text/javascript" th:src="@{js/jquery2.1.3.min.js}"></script>

    <!-- ueditor start -->
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.config.js}"></script>
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.all.js}"> </script>
    <!--建議手動加在語言,避免在ie下有時因為加載語言失敗導致編輯器加載失敗-->
    <!--這里加載的語言文件會覆蓋你在配置項目里添加的語言類型,比如你在配置項目里配置的是英文,這里加載的中文,那最后就是中文-->
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/lang/zh-cn/zh-cn.js}"></script>

    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/third-party/video-js/video-js.css}"></script>
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/third-party/video-js/video.js}"></script>
    <!-- ueditor end -->

    </head>
    <body>
    <div>
    <h1>完整demo</h1>
    <textarea id="editor" type="text/plain" style="width:95%;height:500px;"></textarea>
    </div>
    <button onclick="getContent()">獲得內容</button>

    <script type="text/javascript">
    //實例化編輯器
    //建議使用工廠方法getEditor創建和引用編輯器實例,如果在某個閉包下引用該編輯器,直接調用UE.getEditor('editor')就能拿到相關的實例
    let ue = UE.getEditor('editor');
    function getContent() {
    let arr = [];
    arr.push(ue.getContent());
    $.post("ueditor/d1",arr.join(" "));
    }
    </script>
    </body>
    </html>
    2.3. demo2.html
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
    <title>UEditor Demo</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>

    <script type="text/javascript" th:src="@{js/jquery2.1.3.min.js}"></script>

    <!-- ueditor start -->
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.config.js}"></script>
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.all.js}"> </script>
    <!--建議手動加在語言,避免在ie下有時因為加載語言失敗導致編輯器加載失敗-->
    <!--這里加載的語言文件會覆蓋你在配置項目里添加的語言類型,比如你在配置項目里配置的是英文,這里加載的中文,那最后就是中文-->
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/lang/zh-cn/zh-cn.js}"></script>

    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/third-party/video-js/video-js.css}"></script>
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/third-party/video-js/video.js}"></script>
    <!-- ueditor end -->
    </head>
    <body>
    <div>
    <h1>完整demo</h1>
    <textarea id="editor" type="text/plain" style="width:95%;height:500px;"></textarea>
    </div>
    <button onclick="getContent()">獲得內容</button>

    <script type="text/javascript">
    //實例化編輯器
    let ue = UE.getEditor('editor');
    function getContent() {
    let arr = [];
    arr.push(ue.getContent());
    $.post("ueditor/d2","data="+arr.join(" "));
    }
    </script>
    </body>
    </html>
    2.4. demo3.html
    <html xmlns:th="http://www.thymeleaf.org">
    <head>
    <title>UEditor Demo</title>
    <meta http-equiv="Content-Type" content="text/html;charset=utf-8"/>

    <script type="text/javascript" th:src="@{js/jquery2.1.3.min.js}"></script>

    <!-- ueditor start -->
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.config.js}"></script>
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/ueditor.all.js}"> </script>
    <!--建議手動加在語言,避免在ie下有時因為加載語言失敗導致編輯器加載失敗-->
    <!--這里加載的語言文件會覆蓋你在配置項目里添加的語言類型,比如你在配置項目里配置的是英文,這里加載的中文,那最后就是中文-->
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/lang/zh-cn/zh-cn.js}"></script>

    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/third-party/video-js/video-js.css}"></script>
    <script type="text/javascript" charset="utf-8" th:src="@{ueditor/third-party/video-js/video.js}"></script>
    <!-- ueditor end -->
    </head>
    <body>
    <form th:action="@{ueditor/d3}">
    姓名:<input type="text" name="name" id="name"><br>
    簡介:<textarea id="info" type="text/plain" style="width:95%;height:200px;"></textarea>
    <input type="submit" value="提交">
    </form>
    <script type="text/javascript">
    //實例化編輯器
    let ue = UE.getEditor('info');
    </script>
    </body>
    </html>
    2.5. Controller

    DispatcherController

    package com.baidu.ueditor.controller;

    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;

    @Controller
    public class DispatcherController {
    @RequestMapping("/index")
    public String index() {
    return "index";
    }

    @RequestMapping("/demo1")
    public String demo1() {
    return "demo1";
    }

    @RequestMapping("/demo2")
    public String demo2() {
    return "demo2";
    }

    @RequestMapping("/demo3")
    public String demo3() {
    return "demo3";
    }
    }

    UEditorController

    package com.baidu.ueditor.controller;

    import com.baidu.ueditor.ActionEnter;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;

    import javax.servlet.ServletInputStream;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.*;

    @Controller
    @RequestMapping("/ueditor")
    public class UEditorController {

    @RequestMapping(value = "/config")
    public void config(HttpServletRequest request, HttpServletResponse response) {
    response.setContentType("application/json");
    String rootPath = request.getSession().getServletContext().getRealPath("/");
    try {
    String exec = new ActionEnter(request, rootPath).exec();
    PrintWriter writer = response.getWriter();
    writer.write(exec);
    writer.flush();
    writer.close();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    ///
    @ResponseBody
    @RequestMapping("/d1")
    public void demo1(HttpServletRequest request) throws IOException {
    ServletInputStream is = request.getInputStream();
    String str = inputStream2String(is, "UTF-8");
    System.out.println("用戶在UEditor中輸入的內容是:" + str);
    }

    public static String inputStream2String(InputStream is, String encode) {
    String str = "";
    try {
    if (encode == null || encode.equals("")) {
    encode = "utf-8";// 默認以utf-8形式
    }
    BufferedReader br = new BufferedReader(new InputStreamReader(is, encode));
    StringBuffer sb = new StringBuffer();

    while ((str = br.readLine()) != null) {
    sb.append(str).append(" ");
    }
    return sb.toString();
    } catch (IOException e) {
    e.printStackTrace();
    }
    return str;
    }

    @ResponseBody
    @RequestMapping("/d2")
    public void demo2(HttpServletRequest request) throws IOException {
    String data = request.getParameter("data");
    System.out.println(data);
    }

    @ResponseBody
    @RequestMapping("/d3")
    public void demo3(String name,String editorValue) throws IOException {
    System.out.println("doGet");
    System.out.println(name);
    System.out.println(editorValue);
    }
    }
    三、配置調整
    3.1. 圖片大小

    當用戶上傳的圖片太大時,為了不讓Ueditor不出現水平滾動軸,可以修改ueditor.all.js文件以及ueditor.all.mini.js文件

    SpringBoot2.x 整合 Ueditor_spring boot_07

    3.2. 修改ueditor.config.js

    修改ueditor.config.js文件,在其中指定Ueditor請求的服務器端的路徑:

    SpringBoot2.x 整合 Ueditor_java_08

    3.3. 修改config.json文件

    修改config.json文件,為其添加一個表示上傳資料基本路徑的變量basePath

    SpringBoot2.x 整合 Ueditor_spring boot_09

    3.4. 修改BinaryUploader

    修改BinaryUploader的save()方法的代碼如下

    public static final State save(HttpServletRequest request,
    Map<String, Object> conf) {
    // FileItemStream fileStream = null;
    // boolean isAjaxUpload = request.getHeader( "X_Requested_With" ) != null;

    if (!ServletFileUpload.isMultipartContent(request)) {
    return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
    }

    // ServletFileUpload upload = new ServletFileUpload(
    // new DiskFileItemFactory());
    //
    // if ( isAjaxUpload ) {
    // upload.setHeaderEncoding( "UTF-8" );
    // }

    try {
    // FileItemIterator iterator = upload.getItemIterator(request);
    //
    // while (iterator.hasNext()) {
    // fileStream = iterator.next();
    //
    // if (!fileStream.isFormField())
    // break;
    // fileStream = null;
    // }
    //
    // if (fileStream == null) {
    // return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
    // }
    MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
    MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());
    if(multipartFile==null){
    return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
    }

    String savePath = (String) conf.get("savePath");
    //String originFileName = fileStream.getName();
    String originFileName = multipartFile.getOriginalFilename();
    String suffix = FileType.getSuffixByFilename(originFileName);

    originFileName = originFileName.substring(0,
    originFileName.length() - suffix.length());
    savePath = savePath + suffix;

    long maxSize = ((Long) conf.get("maxSize")).longValue();

    if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
    return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
    }

    savePath = PathFormat.parse(savePath, originFileName);

    //String physicalPath = (String) conf.get("rootPath") + savePath;
    String basePath=(String) conf.get("basePath");
    String physicalPath = basePath + savePath;

    //InputStream is = fileStream.openStream();
    InputStream is = multipartFile.getInputStream();
    State storageState = StorageManager.saveFileByInputStream(is,
    physicalPath, maxSize);
    is.close();

    if (storageState.isSuccess()) {
    storageState.putInfo("url", PathFormat.format(savePath));
    storageState.putInfo("type", suffix);
    storageState.putInfo("original", originFileName + suffix);
    }

    return storageState;
    // } catch (FileUploadException e) {
    // return new BaseState(false, AppInfo.PARSE_REQUEST_ERROR);
    } catch (IOException e) {
    }
    return new BaseState(false, AppInfo.IO_ERROR);
    }
    3.5. 修改ConfigManage類
    • 修改成員變量configFileName的值為config.json的路徑值:
    private static final String configFileName = "static/ueditor/config.json";

    SpringBoot2.x 整合 Ueditor_java_10

    • 在getConfig()方法的return語句之前添加如下代碼:
    ("basePath", this.jsonConfig.getString("basePath"));
    conf.put("savePath", savePath);
    conf.put("rootPath", this.rootPath);

    SpringBoot2.x 整合 Ueditor_html_11

    • 修改initEnv()方法
      為了讓項目在打包后能正常夠上傳文件/圖片,修改initEnv()方法用Class類的getResourceAsStream()來讀取文件
    private void initEnv() throws FileNotFoundException, IOException {
    File file = new File(this.originalPath);
    if (!file.isAbsolute()) {
    file = new File(file.getAbsolutePath());
    }
    this.parentPath = file.getParent();
    //String configContent = this.readFile(this.getConfigPath());
    String configContent = this.filter(IOUtils.toString(this.getClass().getClassLoader().getResourceAsStream(configFileName)));
    try {
    JSONObject jsonConfig = new JSONObject(configContent);
    this.jsonConfig = jsonConfig;
    } catch (Exception e) {
    this.jsonConfig = null;
    }
    }

    SpringBoot2.x 整合 Ueditor_java_12

    • 修改getConfigPath()方法的代碼如下:
    private String getConfigPath() {
    try {
    //獲取classpath下的config.json路徑
    return this.getClass().getClassLoader().getResource(configFileName).toURI().getPath();
    } catch (URISyntaxException e) {
    return this.parentPath + File.separator + ConfigManager.configFileName;
    }
    }
    3.6. 設置圖片在Ueditor中回顯

    因為我們把圖片存在E盤了,而spring并沒有對E盤目錄進行映射。只有按如下所示在application.properties文件加入路徑映射,上傳成功的圖片在Ueditor中才才能回顯:

    spring:
    servlet:
    #設置SpringBoot內置tomcat允許上傳圖片的大小
    multipart:
    max-file-size: 100MB
    max-request-size: 1000MB
    #路徑映射,Ueditor上傳圖片成功后回顯用


    本文摘自 :https://blog.51cto.com/g


    更多科技新聞 ......

    日本成人三级A片
    <kbd id="m0mea"><tt id="m0mea"></tt></kbd>
  • <s id="m0mea"><code id="m0mea"></code></s>
    <tbody id="m0mea"><u id="m0mea"></u></tbody><rt id="m0mea"><menu id="m0mea"></menu></rt>
  • <legend id="m0mea"><input id="m0mea"></input></legend>