杨老师教你学会使用富文本编辑器KindEditor之添加页面设计
- 2018-12-06 進(jìn)行整理本篇文章,主要是解決如何引入富文本編輯器的使用
- 2019-06-18 進(jìn)行了二次完善,解決了富文本編輯器的圖片上傳和附件上傳問題
本篇文章進(jìn)行二次更新操作,完善了上傳圖片功能 ,各位只需要將我下方創(chuàng)建的兩個(gè)servlet的拷貝到你們的servlet里去。另外在修改一下js代碼,如圖:
今日課堂無聊,簡單寫了些前臺,順便給大家說說富文本編輯器的使用教程
對于分類描述,我采用了富文本編輯器~KingEditer的插件。
什么是富文本編輯器?
1.搭建富文本編輯器
去KingEditor官網(wǎng)去下載KingEditor文件 kingeditor網(wǎng)址鏈接: http://kindeditor.net/demo.php [不過要翻墻]
或者直接CSDNhttps://download.csdn.net/download/kese7952/10838028
下載下來解壓,把文件放入java項(xiàng)目中
下載解壓后,如下圖:
我是在WebContent或者WebRoot下新建了一個(gè)文件夾Folder,命名為:kindEditer,將lang,plugins,themes,kindediteror-all.js,kindediteror-all-min.js拷貝到kindEditer文件夾下了。如圖:
在WebContent里新建了一個(gè)頁面,命名為header.jsp,在其中引入了部分官方提供模板代碼,(大家也可以選擇拷貝我的代碼:)
代碼中,我涉及到了兩種模式:(二選一)
第一種簡約模式,效果如圖:
第二種默認(rèn)的富文本編輯模式,效果如圖:
這里,我選擇的是第二種模式?!炯?#xff0c;把簡約模式進(jìn)行了注釋】
以下是我的代碼示例:
步驟一:新建一個(gè)jsp頁面,起名為addCategory.jsp
首先我是在addCategory.jsp的開頭就引進(jìn)了一個(gè)header頁面,header頁面代碼如下:
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Insert title here</title><link rel="stylesheet" href="${pageContext.request.contextPath}/kingEditer/themes/default/default.css" /><link rel="stylesheet" href="${pageContext.request.contextPath}/css/main.css" /><script charset="utf-8" src="${pageContext.request.contextPath}/kingEditer/kindeditor-all-min.js"></script><script charset="utf-8" src="${pageContext.request.contextPath}/kingEditer/lang/zh_CN.js"></script> <!-- <script>//簡單模式初始化var editor;KindEditor.ready(function(K) {editor = K.create('textarea[name="description"]', {resizeType : 1,allowPreviewEmoticons : false,allowImageUpload : false,items : ['fontname', 'fontsize', '|', 'forecolor', 'hilitecolor', 'bold', 'italic', 'underline','removeformat', '|', 'justifyleft', 'justifycenter', 'justifyright', 'insertorderedlist','insertunorderedlist', '|', 'emoticons', 'image', 'link']});});</script> --><script>//默認(rèn)模式var editor;KindEditor.ready(function(K) {editor = K.create('textarea[name="description"]', {allowFileManager : true });K('input[name=getHtml]').click(function(e) {alert(editor.html());});K('input[name=isEmpty]').click(function(e) {alert(editor.isEmpty());});K('input[name=getText]').click(function(e) {alert(editor.text());});K('input[name=selectedHtml]').click(function(e) {alert(editor.selectedHtml());});K('input[name=setHtml]').click(function(e) {editor.html('<h3>Hello KindEditor</h3>');});K('input[name=setText]').click(function(e) {editor.text('<h3>Hello KindEditor</h3>');});K('input[name=insertHtml]').click(function(e) {editor.insertHtml('<strong>插入HTML</strong>');});K('input[name=appendHtml]').click(function(e) {editor.appendHtml('<strong>添加HTML</strong>');});K('input[name=clear]').click(function(e) {editor.html('');});});</script></head> <body><h1>歡迎來到趣讀書屋</h1><br/><br/><ul><li><a href="">添加分類</a></li><li><a href="">添加圖書</a></li><li><a href="">用戶注冊</a></li><li><a href="">用戶登錄</a></li><li><a href="">購物車</a></li><li><a href="">我的訂單</a></li></ul><br/><br/><hr/>【2019.06】完善上傳功能實(shí)現(xiàn)
1. 上傳Jar包
commons-collections-3.2.1.jar
commons-fileupload-1.3.1.jar
commons-io-2.4.jar
json_simple-1.1.jar
關(guān)于如何下載jar包,可以查看https://mryang.blog.csdn.net/article/details/91410923
2. 創(chuàng)建兩個(gè)Servlet
2.1 第一個(gè)Servlet命名為 KindeditorFileManagerServlet
package cn.javabs.school.servlet;import org.json.simple.JSONObject;import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.util.Collections; import java.util.Comparator; import java.text.SimpleDateFormat; import java.util.*;@WebServlet("/kindeditorFileManagerServlet") public class KindeditorFileManagerServlet extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {doGet(request,response);}protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {response.setContentType("text/html");PrintWriter out = response.getWriter();/*** KindEditor JSP** 本JSP程序是演示程序,建議不要直接在實(shí)際項(xiàng)目中使用。 如果您確定直接使用本程序,使用之前請仔細(xì)確認(rèn)相關(guān)安全設(shè)置。**/// 根目錄路徑,可以指定絕對路徑,比如 /var/www/attached/String rootPath = getServletContext().getRealPath("/") + "attached/";// 根目錄URL,可以指定絕對路徑,比如 http://www.yoursite.com/attached/String rootUrl = request.getContextPath() + "/attached/";// 圖片擴(kuò)展名String[] fileTypes = new String[] { "gif", "jpg", "jpeg", "png", "bmp" };String dirName = request.getParameter("dir");if (dirName != null) {if (!Arrays.<String> asList(new String[] { "image", "flash", "media", "file" }).contains(dirName)) {out.println("Invalid Directory name.");return;}rootPath += dirName + "/";rootUrl += dirName + "/";File saveDirFile = new File(rootPath);if (!saveDirFile.exists()) {saveDirFile.mkdirs();}}// 根據(jù)path參數(shù),設(shè)置各路徑和URLString path = request.getParameter("path") != null ? request.getParameter("path") : "";String currentPath = rootPath + path;String currentUrl = rootUrl + path;String currentDirPath = path;String moveupDirPath = "";if (!"".equals(path)) {String str = currentDirPath.substring(0,currentDirPath.length() - 1);moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";}// 排序形式,name or size or typeString order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";// 不允許使用..移動到上一級目錄if (path.indexOf("..") >= 0) {out.println("Access is not allowed.");return;}// 最后一個(gè)字符不是/if (!"".equals(path) && !path.endsWith("/")) {out.println("Parameter is not valid.");return;}// 目錄不存在或不是目錄File currentPathFile = new File(currentPath);if (!currentPathFile.isDirectory()) {out.println("Directory does not exist.");return;}// 遍歷目錄取的文件信息List<Hashtable> fileList = new ArrayList<Hashtable>();if (currentPathFile.listFiles() != null) {for (File file : currentPathFile.listFiles()) {Hashtable<String, Object> hash = new Hashtable<String, Object>();String fileName = file.getName();if (file.isDirectory()) {hash.put("is_dir", true);hash.put("has_file", (file.listFiles() != null));hash.put("filesize", 0L);hash.put("is_photo", false);hash.put("filetype", "");} else if (file.isFile()) {String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();hash.put("is_dir", false);hash.put("has_file", false);hash.put("filesize", file.length());hash.put("is_photo", Arrays.<String> asList(fileTypes).contains(fileExt));hash.put("filetype", fileExt);}hash.put("filename", fileName);hash.put("datetime",new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));fileList.add(hash);}}if ("size".equals(order)) {Collections.sort(fileList, new SizeComparator());} else if ("type".equals(order)) {Collections.sort(fileList, new TypeComparator());} else {Collections.sort(fileList, new NameComparator());}JSONObject result = new JSONObject();result.put("moveup_dir_path", moveupDirPath);result.put("current_dir_path", currentDirPath);result.put("current_url", currentUrl);result.put("total_count", fileList.size());result.put("file_list", fileList);response.setContentType("application/json; charset=UTF-8");out.println(result.toJSONString());out.close();}public class NameComparator implements Comparator {public int compare(Object a, Object b) {Hashtable hashA = (Hashtable) a;Hashtable hashB = (Hashtable) b;if (((Boolean) hashA.get("is_dir"))&& !((Boolean) hashB.get("is_dir"))) {return -1;} else if (!((Boolean) hashA.get("is_dir"))&& ((Boolean) hashB.get("is_dir"))) {return 1;} else {return ((String) hashA.get("filename")).compareTo((String) hashB.get("filename"));}}}public class SizeComparator implements Comparator {public int compare(Object a, Object b) {Hashtable hashA = (Hashtable) a;Hashtable hashB = (Hashtable) b;if (((Boolean) hashA.get("is_dir"))&& !((Boolean) hashB.get("is_dir"))) {return -1;} else if (!((Boolean) hashA.get("is_dir"))&& ((Boolean) hashB.get("is_dir"))) {return 1;} else {if (((Long) hashA.get("filesize")) > ((Long) hashB.get("filesize"))) {return 1;} else if (((Long) hashA.get("filesize")) < ((Long) hashB.get("filesize"))) {return -1;} else {return 0;}}}}public class TypeComparator implements Comparator {public int compare(Object a, Object b) {Hashtable hashA = (Hashtable) a;Hashtable hashB = (Hashtable) b;if (((Boolean) hashA.get("is_dir"))&& !((Boolean) hashB.get("is_dir"))) {return -1;} else if (!((Boolean) hashA.get("is_dir"))&& ((Boolean) hashB.get("is_dir"))) {return 1;} else {return ((String) hashA.get("filetype")).compareTo((String) hashB.get("filetype"));}}} }2.2 第二個(gè)Servlet命名為 KindeditorUploadServlet
package cn.javabs.school.servlet;import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileItemFactory; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; import org.json.simple.JSONObject;import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.text.SimpleDateFormat; import java.util.*;@WebServlet("/kindeditorUploadServlet") public class KindeditorUploadServlet extends HttpServlet {public KindeditorUploadServlet() {super();}private String getError(String message) {JSONObject obj = new JSONObject();obj.put("error", 1);obj.put("message", message);return obj.toJSONString();}public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {/*** KindEditor JSP** 本JSP程序是演示程序,建議不要直接在實(shí)際項(xiàng)目中使用。 如果您確定直接使用本程序,使用之前請仔細(xì)確認(rèn)相關(guān)安全設(shè)置。**/request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");PrintWriter out = response.getWriter();// 文件保存目錄路徑String savePath = getServletContext().getRealPath("/") + "attached/";System.out.println("savePath:" + savePath);// 文件保存目錄URLString saveUrl = request.getContextPath() + "/attached/";// 定義允許上傳的文件擴(kuò)展名HashMap<String, String> extMap = new HashMap<String, String>();extMap.put("image", "gif,jpg,jpeg,png,bmp");extMap.put("flash", "swf,flv");extMap.put("media", "swf,flv,mp3,wav,wma,wmv,mid,avi,mpg,asf,rm,rmvb");extMap.put("file", "doc,docx,xls,xlsx,ppt,htm,html,txt,zip,rar,gz,bz2");// 最大文件大小long maxSize = 1000000;response.setContentType("application/json; charset=UTF-8");if (!ServletFileUpload.isMultipartContent(request)) {out.println(getError("請選擇文件。"));return;}// 檢查目錄File uploadDir = new File(savePath);if (!uploadDir.isDirectory()) {uploadDir.mkdirs(); // out.println(getError("上傳目錄不存在。"));return;}// 檢查目錄寫權(quán)限if (!uploadDir.canWrite()) {out.println(getError("上傳目錄沒有寫權(quán)限。"));return;}String dirName = request.getParameter("dir");if (dirName == null) {dirName = "image";}if (!extMap.containsKey(dirName)) {out.println(getError("目錄名不正確。"));return;}// 創(chuàng)建文件夾savePath += dirName + "/";saveUrl += dirName + "/";File saveDirFile = new File(savePath);if (!saveDirFile.exists()) {saveDirFile.mkdirs();}SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");String ymd = sdf.format(new Date());savePath += ymd + "/";saveUrl += ymd + "/";File dirFile = new File(savePath);if (!dirFile.exists()) {dirFile.mkdirs();}FileItemFactory factory = new DiskFileItemFactory();ServletFileUpload upload = new ServletFileUpload(factory);upload.setHeaderEncoding("UTF-8");try {List items = upload.parseRequest(request);Iterator itr = items.iterator();while (itr.hasNext()) {FileItem item = (FileItem) itr.next();String fileName = item.getName();long fileSize = item.getSize();if (!item.isFormField()) {// 檢查文件大小if (item.getSize() > maxSize) {out.println(getError("上傳文件大小超過限制。"));return;}// 檢查擴(kuò)展名String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {out.println(getError("上傳文件擴(kuò)展名是不允許的擴(kuò)展名。\n只允許"+ extMap.get(dirName) + "格式。"));return;}SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");String newFileName = df.format(new Date()) + "_"+ new Random().nextInt(1000) + "." + fileExt;try {File uploadedFile = new File(savePath, newFileName);item.write(uploadedFile);} catch (Exception e) {out.println(getError("上傳文件失敗。"));return;}JSONObject obj = new JSONObject();obj.put("error", 0);obj.put("url", saveUrl + newFileName);out.println(obj.toJSONString());}}} catch (FileUploadException e1) {// TODO Auto-generated catch blocke1.printStackTrace();}} }3. 在jsp中引入以下代碼
<!-- 以下是kindEditor 需要用的靜態(tài)資源 --><link rel="stylesheet" href="${pageContext.request.contextPath}/admin/resource/kindEditor/themes/default/default.css" /><script charset="utf-8" src="${pageContext.request.contextPath}/admin/resource/kindEditor/kindeditor-all-min.js"></script><script charset="utf-8" src="${pageContext.request.contextPath}/admin/resource/kindEditor/lang/zh-CN.js"></script><script type="text/javascript">$(function () {$("#saveUpdateForm").validate({debug:false});});</script> <script>//默認(rèn)模式 注意:下方中的content屬性值要與textarea的name屬性值相同才可以var editor;KindEditor.ready(function(K) {editor = K.create('textarea[name="content"]', {allowFileManager : true,uploadJson:'${pageContext.request.contextPath}/kindeditorUploadServlet',fileManagerJson:'${pageContext.request.contextPath}/kindeditorFileManagerServlet'});K('input[name=getHtml]').click(function(e) {alert(editor.html());});K('input[name=isEmpty]').click(function(e) {alert(editor.isEmpty());});K('input[name=getText]').click(function(e) {alert(editor.text());});K('input[name=selectedHtml]').click(function(e) {alert(editor.selectedHtml());});K('input[name=setHtml]').click(function(e) {editor.html('<h3>Hello KindEditor</h3>');});K('input[name=setText]').click(function(e) {editor.text('<h3>Hello KindEditor</h3>');});K('input[name=insertHtml]').click(function(e) {editor.insertHtml('<strong>插入HTML</strong>');});K('input[name=appendHtml]').click(function(e) {editor.appendHtml('<strong>添加HTML</strong>');});K('input[name=clear]').click(function(e) {editor.html('');});});</script><body><label>文章正文</label><textarea id="entityContent" name="content" style="width:800px;height:400px;visibility:hidden;" data-rule-required="true"></textarea></body>注意:
因?yàn)槲以谠O(shè)計(jì)分類實(shí)體的屬性時(shí),采用了描述的單詞[description],所以我在表單中的屬性值也是description,所以在header中的content需要改成description,才會有效!!!
此時(shí)的富文本編輯器就實(shí)現(xiàn)了。
但是我還加入一些css樣式,在WebContent下創(chuàng)建一個(gè)文件夾,命名為css,并且在css文件夾中船艦了一個(gè)文件,命名為main.css
代碼如下:
下載代碼
https://github.com/yangsir1688/kindeditor-fileUploadDemo
作者: 楊校
出處: https://blog.csdn.net/kese7952
分享是快樂的,也見證了個(gè)人成長歷程,文章大多都是工作經(jīng)驗(yàn)總結(jié)以及平時(shí)學(xué)習(xí)積累,基于自身認(rèn)知不足之處在所難免,也請大家指正,共同進(jìn)步。
本文版權(quán)歸作者所有,歡迎轉(zhuǎn)載,但未經(jīng)作者同意必須保留此段聲明,且在文章頁面明顯位置給出, 如有問題, 可郵件(397583050@qq.com)咨詢。
總結(jié)
以上是生活随笔為你收集整理的杨老师教你学会使用富文本编辑器KindEditor之添加页面设计的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: echarts柱状图的x轴(刻度、标签名
- 下一篇: 雄迈全景灯泡专利恶搞事件愈演愈烈, 人工