本文为原创,只为互相学习!
主页:写程序的小王叔叔的博客欢迎来访👀
支持:点赞
收藏
关注
社区:JAVA全栈进阶学习社区欢迎加入
编辑器使用
1)官网:在线HTML编辑器
2)使用
如果在编辑器中,某个功能不想让他显示,则可在kindeditor-all.js中的K.options = { items (通常在263行处)} 删除相应的功能名称(在浏览器中,用F12找相应功能的data-name)即可
参考文档:https://blog.csdn.net/qq_30258957/article/details/78762464
官 网:http://kindeditor.net/doc.php
<!-- 添加文本编辑器插件 -->
<script charset="utf-8" type="text/javascript" src="/kindeditor/kindeditor-all.js"></script>
<script charset="utf-8" type="text/javascript" src="/kindeditor/lang/zh-CN.js"></script>
<textarea
id="editor_id"
name="content"
style="width:700px;height:200px;visibility:hidden;">
</textarea>
<script type="text/javascript">var editor1;/**页面初始化 创建文本编辑器工具**/KindEditor.ready(function(K) {editor1 = K.create('textarea[name="content"]', {//定义属性cssPath : '../plugins/code/prettify.css',uploadJson : '../jsp/upload_json.jsp',fileManagerJson : '../jsp/file_manager_json.jsp',allowFileManager : true});prettyPrint();});function submitProduct(){/**取出文本编辑器的内容**/editor1.sync();//同步编辑器文件var productName = $("#productName").val();var productPrice = $("#productPrice").val();var productReward = $("#productReward").val();var productStock = $("#productStock").val();var productImgUrl = $("#productImgUrl").val();var productImgList = $("#productImgList").val();var productIntroduce = document.getElementById('editor_id').value; //获取编辑器普通jquery取值即可$.ajax({ type: 'get', url: '/admin/saveProduct', dataType : 'json', data: {'productName':productName,'productPrice':productPrice,'productReward':productReward,'productStock':productStock,'productImgUrl':productImgUrl,'productImgList':productImgList,'productIntroduce':productIntroduce},success : function(data){ if(data.errorCode == "0"){ alert("添加成功"); location.href="/admin/loginProductList/list";return; } if(data.errorCode == "1"){ alert("添加失败"); return; } var productIntroduce = data.productIntroduce;KindEditor.html("#editor_id", productIntroduce);//给编辑器赋值}, error:function(){ alert("system error"); } }); } </script>
CREATE TABLE `drp_product` (`product_id` bigint(20) NOT NULL AUTO_INCREMENT,`product_name` varchar(255) DEFAULT NULL,`product_style` varchar(255) DEFAULT NULL,`product_address` varchar(255) DEFAULT NULL,`product_price` double DEFAULT NULL,`product_stock` int(11) DEFAULT NULL,`product_introduce` text,`create_date` datetime DEFAULT NULL,`product_img_url` varchar(255) DEFAULT NULL,`product_reward` decimal(19,2) DEFAULT NULL,`product_sales` int(11) NOT NULL,`product_type` int(11) NOT NULL,`favorable_price` decimal(19,2) DEFAULT NULL,`product_details` varchar(255) DEFAULT NULL,`product_keyword` varchar(255) DEFAULT NULL,`product_priority` varchar(255) DEFAULT NULL,`number_of_goods` int(11) NOT NULL,`shopping_car_id` bigint(20) DEFAULT NULL,`product_img_list` varchar(255) DEFAULT NULL,`product_style_detailed` varchar(255) DEFAULT NULL,PRIMARY KEY (`product_id`)) ENGINE=InnoDB AUTO_INCREMENT=75 DEFAULT CHARSET=utf8;
/**如果在编辑器中,某个功能不想让他显示,则可在kindeditor-all.js中的K.options = { items (通常在263行处)}删除相应的功能名称(在浏览器中,用F12找相应功能的data-name)即可参考文档:https://blog.csdn.net/qq_30258957/article/details/78762464http://kindeditor.net/doc.php 官网**/
html代码
<!-- 添加文本编辑器插件 --><script charset="utf-8" type="text/javascript" src="/kindeditor/kindeditor-all.js"></script><script charset="utf-8" type="text/javascript" src="/kindeditor/lang/zh-CN.js"></script><script src="/kindeditor/themes/default/default.css" type="text/css" rel="stylesheet"></script><!--编写文本区域--><textarea id="editor_id" name="content" style="width:700px;height:200px;visibility:hidden;"></textarea><script type="text/javascript">var editor1;/**页面初始化 创建文本编辑器工具**/KindEditor.ready(function(K) {//定义生成编辑器的文本类型editor1 = K.create('textarea[name="content"]', {cssPath : '../plugins/code/prettify.css',allowImageUpload: true, //上传图片框本地上传的功能,false为隐藏,默认为trueallowImageRemote : false, //上传图片框网络图片的功能,false为隐藏,默认为trueformatUploadUrl:false,uploadJson : '/kindEditor/upLoad',//文件上传请求后台路径allowFileManager : true,afterCreate : function() {var self = this;K.ctrl(document, 13, function() {self.sync();document.forms['example'].submit();});K.ctrl(self.edit.doc, 13, function() {self.sync();document.forms['example'].submit();});} });prettyPrint();});
</script>
上传图片的工具类:
@WebServlet("/kindEditor/upLoad")
public class KindEditorUpload extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doPost(req, resp);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//设置Response响应的编码resp.setContentType("text/html; charset=UTF-8");//获取一个Response的Write对象PrintWriter writer = resp.getWriter();//文件保存目录路径String savePath = "D:\\images/";String saveUrl = savePath;//定义允许上传的文件扩展名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;String dirName = req.getParameter("dir");if (dirName == null) {dirName = "image";}if (!extMap.containsKey(dirName)) {writer.println(getError("目录名不正确。"));return;}//创建文件夹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");List items = null;try {items = upload.parseRequest(req);} catch (FileUploadException e) {e.printStackTrace();}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) {writer.println(getError("上传文件大小超过限制。"));return;}//检查扩展名String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();if (!Arrays.<String>asList(extMap.get(dirName).split(",")).contains(fileExt)) {writer.println(getError("上传文件扩展名是不允许的扩展名。\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) {writer.println(getError("上传文件失败。"));return;}String url = "http://localhost:8080/images/image/"+ ymd + "/" + newFileName;//显示图片的主要路径JSONObject obj = new JSONObject();obj.put("error", 0);obj.put("url",url);writer.println(obj.toString());}}//将writer对象中的内容输出writer.flush();//关闭writer对象writer.close();}//一个私有的方法,用于响应错误信息private String getError(String message) {JSONObject obj = new JSONObject();obj.put("error", 1);obj.put("message", message);return obj.toString();}}
显示图片工具类:
@Configuration
public class WebAppConfig extends WebMvcConfigurerAdapter {@Value("${cbs.imagesPath}")private String mImagesPath;//访问图片方法@Overridepublic void addResourceHandlers(ResourceHandlerRegistry registry) {if(mImagesPath.equals("") || mImagesPath.equals("${cbs.imagesPath}")){String imagesPath = WebAppConfig.class.getClassLoader().getResource("").getPath();if(imagesPath.indexOf(".jar")>0){imagesPath = imagesPath.substring(0, imagesPath.indexOf(".jar"));}else if(imagesPath.indexOf("classes")>0){imagesPath = "file:"+imagesPath.substring(0, imagesPath.indexOf("classes"));}imagesPath = imagesPath.substring(0, imagesPath.lastIndexOf("/"))+"/images/";mImagesPath = imagesPath;}LoggerFactory.getLogger(WebAppConfig.class).info("imagesPath="+mImagesPath);registry.addResourceHandler("/images/**").addResourceLocations(mImagesPath);//访问图片的路径super.addResourceHandlers(registry);}}
页面显示文本编辑内容:
<span id="productIntroduceId"></span> <!--将要显示文本编辑器内容部分-->
<input id="productIntroduce" th:value="${product.productIntroduce}" hidden="hidden"><!--获取文本编辑器内容部分--><script type="text/javascript">window.onload=function () {//将文本编辑器内容 用js进行替换显示document.getElementById("productIntroduceId").innerHTML=$("#productIntroduce").val();}
</script>
效果图:
以上是自己整理的,并测试过,可以直接用
转载声明:本文为博主原创文章,未经博主允许不得转载
⚠️注意 ~
💯本期内容就结束了,如果内容有误,麻烦大家评论区指出!
如有疑问❓可以在评论区留言💬或私信留言💬,尽我最大能力🏃♀️帮大家解决👨🏫!
如果我的文章有帮助到您,欢迎打赏✔️鼓励博主🏃,您的鼓励是我分享的动力🏃🏃🏃~