本篇博客目的有两个:
1、layui内置模块的开发
2、layui第三方组件的平台的使用
这个案例主要用到了三个内置模块,分别是表单、表格、弹出层。用到的第三方组件是layui的富文本编辑器。
参考地址
layui官网:https://www.layui.com/
layui拓展后的富文本编辑器:https://fly.layui.com/extend/layedit/
整个项目的配置及目录结构与上篇博客完全一致,这里只贴开发相关代码。
DateUtil.java
package com.javaxl.springboot06.utils;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* 日期处理工具包
* @author Administrator
*
*/
public class DateUtil {
/**
* 日期转字符串
* @param date
* @param format
* @return
*/
public static String formatDate(Date date,String format){
String result="";
SimpleDateFormat sdf=new SimpleDateFormat(format);
if(date!=null){
result=sdf.format(date);
}
return result;
}
/**
* 字符串转日期
* @param str
* @param format
* @return
* @throws Exception
*/
public static Date formatString(String str,String format) throws Exception{
SimpleDateFormat sdf=new SimpleDateFormat(format);
return sdf.parse(str);
}
/**
* 获取当前时间的字符串
* @return
* @throws Exception
*/
public static String getCurrentDateStr()throws Exception{
Date date=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMddhhmmss");
return sdf.format(date);
}
}
StringUtils.java
package com.javaxl.springboot06.utils;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Set;
public class StringUtils {
// 私有的构造方法,保护此类不能在外部实例化
private StringUtils() {
}
/**
* 如果字符串等于null或去空格后等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isBlank(String s) {
boolean b = false;
if (null == s || s.trim().equals("")) {
b = true;
}
return b;
}
/**
* 如果字符串不等于null或去空格后不等于"",则返回true,否则返回false
*
* @param s
* @return
*/
public static boolean isNotBlank(String s) {
return !isBlank(s);
}
/**
* set集合转string
* @param hasPerms
* @return
*/
public static String SetToString(Set hasPerms){
return Arrays.toString(hasPerms.toArray()).replaceAll(" ", "").replace("[", "").replace("]", "");
}
/**
* 转换成模糊查询所需参数
* @param before
* @return
*/
public static String toLikeStr(String before){
return isBlank(before) ? null : "%"+before+"%";
}
/**
* 将图片的服务器访问地址转换为真实存放地址
* @param imgpath 图片访问地址(http://localhost:8080/uploadImage/2019/01/26/20190126000000.jpg)
* @param serverDir uploadImage
* @param realDir E:/temp/
* @return
*/
public static String serverPath2realPath(String imgpath, String serverDir, String realDir) {
imgpath = imgpath.substring(imgpath.indexOf(serverDir));
return imgpath.replace(serverDir,realDir);
}
/**
* 过滤掉集合里的空格
* @param list
* @return
*/
public static List<String> filterWhite(List<String> list){
List<String> resultList=new ArrayList<String>();
for(String l:list){
if(isNotBlank(l)){
resultList.add(l);
}
}
return resultList;
}
/**
* 从html中提取纯文本
* @param strHtml
* @return
*/
public static String html2Text(String strHtml) {
String txtcontent = strHtml.replaceAll("</?[^>]+>", ""); //剔出<html>的标签
txtcontent = txtcontent.replaceAll("<a>\\s*|\t|\r|\n</a>", "");//去除字符串中的空格,回车,换行符,制表符
return txtcontent;
}
}PageBean.java
package com.javaxl.springboot06.utils;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;
/**
* 分页工具类
*/
public class PageBean {
private int page = 1;// 页码
private int rows = 10;// 页大小
private int total = 0;// 总记录数
private boolean pagination = true;// 是否分页
// 保存上次查询的参数
private Map<String, String[]> paramMap;
// 保存上次查询的url
private String url;
public void setRequest(HttpServletRequest request) {
String page = request.getParameter("page");
String rows = request.getParameter("limit");
String pagination = request.getParameter("pagination");
this.setPage(page);
this.setRows(rows);
this.setPagination(pagination);
this.setUrl(request.getRequestURL().toString());
this.setParamMap(request.getParameterMap());
}
public PageBean() {
super();
}
public Map<String, String[]> getParamMap() {
return paramMap;
}
public void setParamMap(Map<String, String[]> paramMap) {
this.paramMap = paramMap;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public int getPage() {
return page;
}
public void setPage(int page) {
this.page = page;
}
public void setPage(String page) {
if(StringUtils.isNotBlank(page)) {
this.page = Integer.parseInt(page);
}
}
public int getRows() {
return rows;
}
public void setRows(String rows) {
if(StringUtils.isNotBlank(rows)) {
this.rows = Integer.parseInt(rows);
}
}
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public void setTotal(String total) {
if(StringUtils.isNotBlank(total)) {
this.total = Integer.parseInt(total);
}
}
public boolean isPagination() {
return pagination;
}
public void setPagination(boolean pagination) {
this.pagination = pagination;
}
public void setPagination(String pagination) {
if(StringUtils.isNotBlank(pagination) && "false".equals(pagination)) {
this.pagination = Boolean.parseBoolean(pagination);
}
}
/**
* 最大页
* @return
*/
public int getMaxPage() {
int max = this.total/this.rows;
if(this.total % this.rows !=0) {
max ++ ;
}
return max;
}
/**
* 下一页
* @return
*/
public int getNextPage() {
int nextPage = this.page + 1;
if(nextPage > this.getMaxPage()) {
nextPage = this.getMaxPage();
}
return nextPage;
}
/**
* 上一页
* @return
*/
public int getPreviousPage() {
int previousPage = this.page -1;
if(previousPage < 1) {
previousPage = 1;
}
return previousPage;
}
/**
* 获得起始记录的下标
*
* @return
*/
public int getStartIndex() {
return (this.page - 1) * this.rows;
}
@Override
public String toString() {
return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", pagination=" + pagination + "]";
}
}
entity层
package com.javaxl.springboot06.entity;
import com.fasterxml.jackson.annotation.JsonFormat;
import javax.persistence.*;
import java.util.Date;
/**
* @author 小李飞刀
* @site www.javaxl.com
* @company
* @create 2019-02-22 11:23
*/
@Entity
@Table(name = "t_springboot_blog")
public class Blog {
@Id
@GeneratedValue
private Integer bid;
@Column(length = 256)
private String title;
@Column(length = 512)
private String summary;
@Column(columnDefinition="TEXT")
private String content;
@Column(length = 256)
private String keyWord;
@Column(columnDefinition = "DATE")
private Date releaseDate;
public Integer getBid() {
return bid;
}
public void setBid(Integer bid) {
this.bid = bid;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getSummary() {
return summary;
}
public void setSummary(String summary) {
this.summary = summary;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getKeyWord() {
return keyWord;
}
public void setKeyWord(String keyWord) {
this.keyWord = keyWord;
}
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
public Date getReleaseDate() {
return releaseDate;
}
public void setReleaseDate(Date releaseDate) {
this.releaseDate = releaseDate;
}
}
dao层、service层略过
controler层
package com.javaxl.springboot06.controller;
import com.javaxl.springboot06.entity.Blog;
import com.javaxl.springboot06.service.BlogService;
import com.javaxl.springboot06.utils.DateUtil;
import com.javaxl.springboot06.utils.PageBean;
import com.javaxl.springboot06.utils.StringUtils;
import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author 小李飞刀
* @site www.javaxl.com
* @company
* @create 2019-02-22 11:40
*/
@Controller
public class BlogController {
@Autowired
private BlogService blogService;
@RequestMapping("/blog/toList")
public String toList(){
return "list";
}
@ResponseBody
@RequestMapping("/blog/list")
public Map list(Blog blog, HttpServletRequest request){
Map result = new HashMap();
PageBean pageBean = new PageBean();
pageBean.setRequest(request);
blog.setTitle(StringUtils.toLikeStr(blog.getTitle()));
Page<Blog> blogs = blogService.listPager(blog, pageBean);
pageBean.setTotal(blogs.getTotalElements()+"");
result.put("data",blogs.getContent());
result.put("code","0");
result.put("count",pageBean.getTotal());
return result;
}
@RequestMapping("/blog/toAdd")
public String toAdd(){
return "add";
}
@RequestMapping("/blog/toEdit")
public String toEdit(){
return "edit";
}
@ResponseBody
@RequestMapping("/blog/save")
public Map save(Blog blog){
Map map = new HashMap();
blog.setReleaseDate(new Date());
this.blogService.save(blog);
map.put("success",true);
return map;
}
@ResponseBody
@RequestMapping("/blog/del")
public Map del(Blog blog){
Map map = new HashMap();
this.blogService.deleteById(blog.getBid());
map.put("success",true);
return map;
}
@ResponseBody
@RequestMapping("/blog/load")
public Blog load(Integer bid){
return blogService.findById(bid);
}
@ResponseBody
@RequestMapping("/blog/uploadImage")
public Map uploadImage(HttpServletRequest request, MultipartFile image){
Map map = new HashMap();
String realDir = "E:/temp/";
String timeDir = DateUtil.formatDate(new Date(),"yyyy/MM/dd");
// 实际博客附带的图片上传地址(E:/temp/2019/01/26/20190126000000.jpg)
String realPath = null;
try {
//原始图片名称
String imageName = image.getOriginalFilename();
//存入数据库的图片名称
String imageSaveName = DateUtil.getCurrentDateStr()+imageName.substring(imageName.lastIndexOf("."));
realPath = realDir+timeDir+"/"+ imageSaveName;
// 通过浏览器访问服务器的映射地址,并且存入数据库(http://localhost:8080/uploadImage/2019/01/26/20190126000000.jpg)
String sererPath = "/uploadImages/"+timeDir+"/"+ imageSaveName;
FileUtils.copyInputStreamToFile(image.getInputStream(),new File(realPath));
// 正常上传返回码为 {code:0,msg:”上传成功”,data:{src:”服务器文件地址”}};
map.put("code",0);
map.put("msg","上传成功");
Map src = new HashMap();
src.put("src",request.getContextPath()+sererPath);
map.put("data",src);
} catch (Exception e) {
e.printStackTrace();
}
return map;
}
/**
* 删除掉不需要的博客图片
* @param request
* @param imgpath
* @return
*/
@ResponseBody
@RequestMapping("/blog/delUploadImage")
public Map delUploadImage(HttpServletRequest request, String imgpath){
Map map = new HashMap();
String realPath = StringUtils.serverPath2realPath(imgpath
, "/uploadImages/"
,"E:/temp/");
try {
FileUtils.forceDelete(new File(realPath));
map.put("success",true);
} catch (IOException e) {
e.printStackTrace();
}
return map;
}
}
页面层
list.html
<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">
<title>博客列表</title>
<link rel="stylesheet" th:href="@{/static/js/layui/css/layui.css}">
<script th:src="@{/static/js/layui/layui.js}" type="text/javascript"></script>
<input id="ctx" th:value="@{/}" type="hidden">
</head>
<body style="padding: 0px;">
<!--搜索框-->
<div class="searchTable layui-form">
博客主题:
<div class="layui-inline">
<input class="layui-input" name="s_title" id="s_title" autocomplete="off">
</div>
<button class="layui-btn" lay-submit="" lay-filter="reload">搜索</button>
<button class="layui-btn" lay-event="add" id="addBtn">新增</button>
</div>
<!--数据表格-->
<table class="layui-hide" id="data_table" lay-filter="data_table"></table>
<!--顶部按钮-->
<script type="text/html" id="topBtns">
<!--搜索维度下的按钮-->
<div class="layui-btn-container">
</div>
</script>
<!--行内数据按钮-->
<script type="text/html" id="lineBtns">
<a class="layui-btn layui-btn-xs" lay-event="edit">编辑</a>
<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
</script>
<script type="text/javascript" th:inline="none">
layui.use(['element', 'table', 'form'], function () {
var $ = layui.jquery;
var element = layui.element; //Tab的切换功能,切换事件监听等,需要依赖element模块
var table = layui.table;
var ctx = document.getElementById("ctx").value;
var form = layui.form;
var data_table = "data_table";
table.render({
elem: '#'+data_table
, url: ctx+'blog/list'
, toolbar: '#topBtns'
// ,defaultToolbar:[] 设置这个还是会留空白
,id:data_table
, title: '博客类别数据表'
, page: true
,cols: [[ //表头
{type: 'checkbox', fixed: 'left'}
,{field: 'bid', title: 'ID', sort: true, fixed: 'left'}
,{field: 'title', title: '标题'}
,{field: 'summary', title: '摘要', event: 'summarySign'}
,{field: 'keyWord', title: '关键字'}
,{field: 'releaseDate', title: '发布时间'}
, {fixed: 'right', title: '操作', toolbar: '#lineBtns'}
]]
,done: function (res, curr, count) {
//layui-table-tool
// $('tr').css({'background-color': '#009688', 'color': '#fff'});
$('.layui-table-tool').removeClass('layui-table-tool');
$('.layui-table-tool-self').html("");
}
});
//模糊查询(查询框一定要放到工具栏中,不能表格重载)
//不妨在工具栏中的话,添加lay-form属性也是可以的
form.on('submit(reload)', function (data) {
table.reload(data_table, {
url: ctx + 'blog/list',
where: {"title": data.field.s_title}
});
return false;
});
//新增
$("#addBtn").click(function () {
layer.open({
type: 2 //此处以iframe举例
, title: '新增博客'
, area: ['100%', '100%']
, shade: 0.6
, content: ctx + 'blog/toAdd'
});
});
//监听行工具事件
table.on('tool('+data_table+')', function (obj) {
var data = obj.data;
if (obj.event === 'del') {
console.log(obj)
layer.confirm('真的删除行么', function (index) {
$.ajax({
url: ctx + "blog/del"
, data: {'bid': data.bid}
, success: function (result) {
if (result.success) {
layer.msg("删除成功!!!")
table.reload(data_table, {
page: {
curr: 1 //重新从第 1 页开始
}
});
}
}
})
});
} else if (obj.event === 'edit') {
layer.open({
type: 2 //此处以iframe举例
, title: '修改博客'
, area: ['100%', '100%']
, shade: 0
, maxmin: true
, offset: 'auto'
, content: ctx + 'blog/toEdit?bid='+obj.data.bid
// , btn: ['继续弹出', '全部关闭'] //只是为了演示
});
} else if (obj.event === 'summarySign') {
layer.prompt({
formType: 2
, area: ['100%', '100%']
,title: '展示 ID 为 ['+ data.bid +'] 的博客HTML'
,value: data.content
}, function(value, index){
layer.close(index);
});
}
});
});
</script>
</body>
</html>add.html
<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">
<title>博客新增</title>
<link rel="stylesheet" th:href="@{/static/js/layui/css/layui.css}">
<script th:src="@{/static/js/layui/layui.js}" type="text/javascript"></script>
<script th:src="@{/static/js/layui/extends/Kz.layedit/Content/ace/ace.js}" type="text/javascript"></script>
<input id="ctx" th:value="@{/}" type="hidden">
</head>
<body style="margin: 0px;padding: 0px;">
<form class="layui-form" action="" lay-filter="form_filter">
<input type="hidden" id="s_bid" name="bid" value="${param.p_bid}">
<div class="layui-form-item">
<label class="layui-form-label">博客标题</label>
<div class="layui-input-block">
<input type="text" name="title" lay-verify="" autocomplete="off" placeholder="请输入博客标题" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">博客内容</label>
<div class="layui-input-block" id="content" name="content">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">关键字</label>
<div class="layui-input-block">
<input type="text" name="keyWord" placeholder="请输入关键字" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit="" lay-filter="pageSubmit">立即提交</button>
</div>
</div>
</form>
<script>
layui.use(['layedit','element','table','form'], function(){
var $ = layui.jquery;
var element = layui.element; //Tab的切换功能,切换事件监听等,需要依赖element模块
var table = layui.table;
var form = layui.form;
var layedit = layui.layedit;
var ctx = $("#ctx").val();
layedit.set({
//暴露layupload参数设置接口 --详细查看layupload参数说明
uploadImage: {
url: ctx+'blog/uploadImage',
accept: 'image',
field:'image',
acceptMime: 'image/*',
exts: 'jpg|png|gif|bmp|jpeg',
size: 1024 * 10,
data: {
name: "测试参数",
age:99
}
,done: function (data) {
console.log(data);
}
}
, uploadFiles: {
url: 'your url',
accept: 'file',
acceptMime: 'file/*',
size: '20480',
autoInsert: true , //自动插入编辑器设置
done: function (data) {
console.log(data);
}
}
//右键删除图片/视频时的回调参数,post到后台删除服务器文件等操作,
//传递参数:
//图片: imgpath --图片路径
//视频: filepath --视频路径 imgpath --封面路径
//附件: filepath --附件路径
, calldel: {
url: ctx+'/admin/blog/delUploadImage',
done: function (data) {
console.log(data);
}
}
, rightBtn: {
type: "layBtn",//default|layBtn|custom 浏览器默认/layedit右键面板/自定义菜单 default和layBtn无需配置customEvent
customEvent: function (targetName, event) {
//根据tagName分类型设置
switch (targetName) {
case "img":
alert("this is img");
break;
default:
alert("hello world");
break;
};
//或者直接统一设定
//alert("all in one");
}
}
//开发者模式 --默认为false
, devmode: true
//是否自动同步到textarea
, autoSync: true
//内容改变监听事件
, onchange: function (content) {
console.log(content);
}
//插入代码设置 --hide:false 等同于不配置codeConfig
, codeConfig: {
hide: true, //是否隐藏编码语言选择框
default: 'javascript', //hide为true时的默认语言格式
encode: true //是否转义
}
//新增iframe外置样式和js
, quote:{
style: ['/p1/static/layui/extends/Kz.layedit/Content/css.css'],
//js: ['/Content/Layui-KnifeZ/lay/modules/jquery.js']
}
, facePath: 'http://knifez.gitee.io/kz.layedit/Content/Layui-KnifeZ/'
, devmode: true
, videoAttr: ' preload="none" '
, tool: [
'html'
, 'code', 'strong', 'italic', 'underline', 'del'//代码块、加粗、斜体、下划线、删除线
, 'addhr'//添加水平线
, '|','removeformat', 'fontFomatt', 'fontfamily','fontSize'//段落格式,字体样式,字体颜色
, 'fontBackColor', 'colorpicker'//字体颜色,字体背景色
, 'face' , '|', 'left', 'center', 'right', '|', 'link', 'unlink'//表情、左对齐、右对齐、居中、插入链接、清除链接
, 'images'//多图上传
, 'image_alt'//图片上传
, 'video'//视频上传
,'attachment'//插入附件
, 'anchors'//添加锚点
, '|' , 'table','customlink'//插入表格、自定义链接
, 'fullScreen','preview'//全屏、预览
]
, height: '500px'
});
var ieditor = layedit.build('content');
//设置编辑器内容
// layedit.setContent(ieditor, "<h1>hello layedit</h1><p>对layui.layedit的拓展,基于layui v2.4.3.增加了HTML源码模式、插入table、批量上传图片、图片插入、超链接插入功能优化、视频插入功能、全屏功能、段落、字体颜色、背景色设置、锚点设置等功能。</p><br><br><div>by KnifeZ </div>", false);
// alert(layedit.getContent(ieditor));
// alert(layedit.getText(ieditor));
//监听提交
form.on('submit(pageSubmit)', function(data){
console.log(data);
$.ajax({
url:ctx + "blog/save"
,method:'post'
// ,data:$(data.form).serialize()//没有单选复选框的时候用,layui不会携带这些参数
,data:{
'title':data.field.title,
'summary':layedit.getText(ieditor).substr(0,155),
'content':layedit.getContent(ieditor),
'keyWord':data.field.keyWord
}
,success:function (result) {
if(result.success){
var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
parent.layer.close(index); //再执行关闭
//tableId表格id
parent.layui.table.reload('data_table',{
page: {
curr: 1 //重新从第 1 页开始
}
});
}
}
});
return false;
});
});
</script>
</body>
</html>edit.html
<!DOCTYPE html>
<html lang="en">
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">
<title>博客新增</title>
<link rel="stylesheet" th:href="@{/static/js/layui/css/layui.css}">
<script th:src="@{/static/js/layui/layui.js}" type="text/javascript"></script>
<script th:src="@{/static/js/layui/extends/Kz.layedit/Content/ace/ace.js}" type="text/javascript"></script>
<script th:src="@{/static/js/xxx.js}" type="text/javascript"></script>
<input id="ctx" th:value="@{/}" type="hidden">
</head>
<body style="margin: 0px;padding: 0px;">
<form class="layui-form" action="" lay-filter="form_filter">
<div class="layui-form-item">
<label class="layui-form-label">博客标题</label>
<div class="layui-input-block">
<input type="text" name="title" lay-verify="" autocomplete="off" placeholder="请输入博客标题" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">博客内容</label>
<div class="layui-input-block" id="content" name="content">
</div>
</div>
<div class="layui-form-item">
<label class="layui-form-label">关键字</label>
<div class="layui-input-block">
<input type="text" name="keyWord" placeholder="请输入关键字" autocomplete="off" class="layui-input">
</div>
</div>
<div class="layui-form-item">
<div class="layui-input-block">
<button class="layui-btn" lay-submit="" lay-filter="pageSubmit">立即提交</button>
</div>
</div>
</form>
<script>
layui.use(['layedit','element','table','form'], function(){
var $ = layui.jquery;
var element = layui.element; //Tab的切换功能,切换事件监听等,需要依赖element模块
var table = layui.table;
var layedit = layui.layedit;
var form = layui.form;
var ctx = document.getElementById("ctx").value;
var s_bid = UrlParam.paramValues("bid");
$.ajax({
url:ctx+"blog/load?bid="+s_bid
,async:false
,success:function (result) {
// console.log(result);
form.val('form_filter',{
'title':result.title,
'summary':result.summary,
'content':result.content,
'releaseDate':result.releaseDate,
'keyWord':result.keyWord
});
}
});
layedit.set({
//暴露layupload参数设置接口 --详细查看layupload参数说明
uploadImage: {
url: ctx+'blog/uploadImage',
accept: 'image',
field:'image',
acceptMime: 'image/*',
exts: 'jpg|png|gif|bmp|jpeg',
size: 1024 * 10,
data: {
name: "测试参数",
age:99
}
,done: function (data) {
console.log(data);
}
}
//右键删除图片/视频时的回调参数,post到后台删除服务器文件等操作,
//传递参数:
//图片: imgpath --图片路径
//视频: filepath --视频路径 imgpath --封面路径
//附件: filepath --附件路径
, calldel: {
url: ctx+'blog/delUploadImage',
done: function (data) {
console.log(data);
}
}
//开发者模式 --默认为false
, devmode: true
//是否自动同步到textarea
, autoSync: true
//插入代码设置 --hide:false 等同于不配置codeConfig
, codeConfig: {
hide: true, //是否隐藏编码语言选择框
default: 'javascript', //hide为true时的默认语言格式
encode: true //是否转义
}
//新增iframe外置样式和js
, quote:{
style: ['/p1/static/layui/extends/Kz.layedit/Content/css.css'],
//js: ['/Content/Layui-KnifeZ/lay/modules/jquery.js']
}
, facePath: 'http://knifez.gitee.io/kz.layedit/Content/Layui-KnifeZ/'
, devmode: true
, videoAttr: ' preload="none" '
, tool: [
'html'
, 'code', 'strong', 'italic', 'underline', 'del'//代码块、加粗、斜体、下划线、删除线
, 'addhr'//添加水平线
, '|','removeformat', 'fontFomatt', 'fontfamily','fontSize'//段落格式,字体样式,字体颜色
, 'fontBackColor', 'colorpicker'//字体颜色,字体背景色
, 'face' , '|', 'left', 'center', 'right', '|', 'link', 'unlink'//表情、左对齐、右对齐、居中、插入链接、清除链接
, 'images'//多图上传
, 'image_alt'//图片上传
, 'video'//视频上传
,'attachment'//插入附件
, 'anchors'//添加锚点
, '|' , 'table','customlink'//插入表格、自定义链接
, 'fullScreen','preview'//全屏、预览
]
, height: '500px'
});
var ieditor = layedit.build('content');
//设置编辑器内容
// layedit.setContent(ieditor, $("#s_content").val(), false);
// alert(layedit.getContent(ieditor));
// alert(layedit.getText(ieditor));
//监听提交
form.on('submit(pageSubmit)', function(data){
// console.log(data);
$.ajax({
url:ctx + "blog/save"
,method:'post'
,data:{
'bid':data.field.bid,
'title':data.field.title,
'summary':layedit.getText(ieditor).substr(0,155),
'content':layedit.getContent(ieditor),
'keyWord':data.field.keyWord
}
,success:function (result) {
if(result.success){
var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
parent.layer.close(index); //再执行关闭
//tableId表格id
parent.layui.table.reload('data_table',{
page: {
curr: 1 //重新从第 1 页开始
}
});
}
}
});
return false;
});
});
</script>
</body>
</html>xxx.js
var UrlParam = function() { // url参数
var data, index;
(function init() {
data = []; //值,如[["1","2"],["zhangsan"],["lisi"]]
index = {}; //键:索引,如{a:0,b:1,c:2}
var u = window.location.search.substr(1);
if (u != '') {
var params = decodeURIComponent(u).split('&');
for (var i = 0, len = params.length; i < len; i++) {
if (params[i] != '') {
var p = params[i].split("=");
if (p.length == 1 || (p.length == 2 && p[1] == '')) {// p | p= | =
data.push(['']);
index[p[0]] = data.length - 1;
} else if (typeof(p[0]) == 'undefined' || p[0] == '') { // =c 舍弃
continue;
} else if (typeof(index[p[0]]) == 'undefined') { // c=aaa
data.push([p[1]]);
index[p[0]] = data.length - 1;
} else {// c=aaa
data[index[p[0]]].push(p[1]);
}
}
}
}
})();
return {
// 获得参数,类似request.getParameter()
param : function(o) { // o: 参数名或者参数次序
try {
return (typeof(o) == 'number' ? data[o][0] : data[index[o]][0]);
} catch (e) {
}
},
//获得参数组, 类似request.getParameterValues()
paramValues : function(o) { // o: 参数名或者参数次序
try {
return (typeof(o) == 'number' ? data[o] : data[index[o]]);
} catch (e) {}
},
//是否含有paramName参数
hasParam : function(paramName) {
return typeof(paramName) == 'string' ? typeof(index[paramName]) != 'undefined' : false;
},
// 获得参数Map ,类似request.getParameterMap()
paramMap : function() {
var map = {};
try {
for (var p in index) { map[p] = data[index[p]]; }
} catch (e) {}
return map;
}
}
}();最终项目运行结果如下



小结:
这个案例有两个需要注意的点:
1、js代码得有th:inline="none"设置 <script type="text/javascript" th:inline="none"></script>
2、jsp中的${param.name}在html中获取
备案号:湘ICP备19000029号
Copyright © 2018-2019 javaxl晓码阁 版权所有