layui富文本域使用案例——增删改查及访问(基于layui数据表格)

时间:2024-04-04 17:50:16

先来看一下效果图:

layui富文本域使用案例——增删改查及访问(基于layui数据表格)

新增:

layui富文本域使用案例——增删改查及访问(基于layui数据表格)

访问:

layui富文本域使用案例——增删改查及访问(基于layui数据表格)

首先需要引入layui插件

页面显示部分代码,这里因为页面是load过去的,所以这里代码没有引入样式文件:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<body>
	<table class="layui-hide" id = "layUITextarea" lay-filter="layUITextarea"></table>
	<script type="text/html" id="toolbarDemo">
  		<div class="layui-btn-group">
    		<button class="layui-btn layui-btn-sm" lay-event="add"><i class="layui-icon">&#xe654;</i>新增</button>
    		<button class="layui-btn layui-btn-sm" lay-event="updata"><i class="layui-icon">&#xe642;</i>修改</button>
    		<button class="layui-btn layui-btn-sm" lay-event="delete"><i class="layui-icon">&#xe640;</i>删除</button>
    		<button class="layui-btn layui-btn-sm" lay-event="find"><i class="layui-icon">&#xe615;</i>查询</button>
			<button class="layui-btn layui-btn-sm" lay-event="refresh"><i class="layui-icon">&#xe666;</i>刷新</button>
  		</div>
	</script>
	<script type="text/html" id="barDemo">
  		<a class="layui-btn layui-btn-xs" lay-event="visit"><i class="layui-icon">&#xe609;</i>访问</a>
	</script>
	
	<script type="text/javascript">
		layui.use("table", function(){
			var search = {};
			var that = this;
			var table = layui.table;
			table.render({
				elem: '#layUITextarea',
				url: 'layUITextarea/page',
				toolbar: '#toolbarDemo',
				title: '文章管理',
				height: 'full-160',
				page: true,
				cols: [ [
					{type:'radio', fixed: 'left'},
					{field: 'id', title: 'ID', sort: true},
					{field: 'createName', title: '发布人'},
					{field: 'createDate', title: '发布时间'},
					{field: 'title', title: '标题'},
					{field: 'type', title: '类型'},
					{fixed: 'right', title:'操作', toolbar: '#barDemo'}
				] ]
			});
			table.on('toolbar(layUITextarea)', function(obj){
				var checkStatus = table.checkStatus('layUITextarea');
				var data = checkStatus.data;
				if(obj.event === "add"){
					$.post("layUITextarea/edit", function(data){
						layui.use('layer', function(){
							layer.open({
								title: '文章管理',
								type: 1,
	    	      				shade: 0.3,
	    	      				maxmin: true,
	    	      				content: data,
	    	      				area: ['80%', '80%'],
	    	      				btn: ['确定', '取消'],
	    	      				yes:function(){
	    	      				},
	    	      				//弹出层打开回调
	    	      				success: function(layero, index){
	    	      					layui.use('form', function(){
	    	      						var form=layui.form;
						    			layero.addClass('layui-form');
							    		var submitBtn=layero.find('.layui-layer-btn0');
							    		submitBtn.attr('lay-filter','formVerify').attr('lay-submit','');
							    		layero.keydown(function(e){
								    		if(e.keyCode==13){
								    			submitBtn.click();
								    		}
								    	});
							    		form.on('submit(formVerify)',function(data){
							    			$.post("layUITextarea/save", data.field, function(result){
							    				if(result.success){
						    						layer.close(index);
						    						table.reload('layUITextarea',{
						    							url:'layUITextarea/page'
						    						});
						    					}
						    					layer.msg(result.msg,{offset:'rb'});
			    	      					});
							    		});
	    	      					})
	    	      				}
							})
						});
					});
				}else if(obj.event === "updata"){
					if(data.length != 1){
						layer.msg('请选择一行进行编辑',{offset:'rb'});
					}else{
						var id = data[0].id;
						$.post("layUITextarea/edit", {id: id}, function(data){
							layui.use('layer', function(){
								layer.open({
									title: '文章管理',
									type: 1,
		    	      				shade: 0.3,
		    	      				maxmin: true,
		    	      				content: data,
		    	      				area: ['80%', '80%'],
		    	      				btn: ['确定', '取消'],
		    	      				yes:function(){
		    	      				},
		    	      				//弹出层打开回调
		    	      				success: function(layero, index){
		    	      					layui.use('form', function(){
		    	      						var form=layui.form;
							    			layero.addClass('layui-form');
								    		var submitBtn=layero.find('.layui-layer-btn0');
								    		submitBtn.attr('lay-filter','formVerify').attr('lay-submit','');
								    		layero.keydown(function(e){
									    		if(e.keyCode==13){
									    			submitBtn.click();
									    		}
									    	});
								    		form.on('submit(formVerify)',function(data){
								    			$.post("layUITextarea/save", data.field, function(result){
								    				if(result.success){
							    						layer.close(index);
							    						table.reload('layUITextarea',{
							    							url:'layUITextarea/page'
							    						});
							    					}
							    					layer.msg(result.msg,{offset:'rb'});
				    	      					});
								    		});
		    	      					})
		    	      				}
								})
							});
						});						
					}
				}else if(obj.event === "delete"){
					if(data.length != 1){
						layer.msg('请选择一行进行删除',{offset:'rb'});
					}else{
						layer.confirm('确定要删除吗?', function(index) {
				        	var id = data[0].id;
				        	$.post("layUITextarea/delete", {id: id}, function(result){
				        		table.reload('layUITextarea',{
	    							url:'layUITextarea/page'
	    						});
				        	});
				        	layer.close(index);
			        	});
					}
				}else if(obj.event === "find"){
					$.post("layUITextarea/search", that.search, function(data){
						layui.use('layer', function(){
							layer.open({
								title: '查询',
								type: 1,
	    	      				shade: 0.3,
	    	      				maxmin: true,
	    	      				content: data,
	    	      				area: ['480px', '240px'],
	    	      				btn: ['确定', '清除查询', '取消'],
	    	      				yes:function(){
	    	      				},
	    	      				btn2:function(index,layero){
	    	      					that.search={};
	    	      					table.reload('layUITextarea',{
		    							url:'layUITextarea/page',
		    							where: ''
		    						});
					    			layer.close(index);
	    	      				},
	    	      				//弹出层打开回调
	    	      				success: function(layero, index){
	    	      					layui.use('form', function(){
	    	      						var form=layui.form;
						    			layero.addClass('layui-form');
							    		var submitBtn=layero.find('.layui-layer-btn0');
							    		submitBtn.attr('lay-filter','formVerify').attr('lay-submit','');
							    		layero.keydown(function(e){
								    		if(e.keyCode==13){
								    			submitBtn.click();
								    		}
								    	});
							    		form.on('submit(formVerify)',function(data){
			    	      					that.search = data.field;
							    			table.reload('layUITextarea',{
				    							url:'layUITextarea/page',
				    							where: data.field
				    						});
							    			layer.close(index);
							    		});
	    	      					})
	    	      				}
							})
						});
					});
				}else if(obj.event === 'refresh'){
					table.reload('layUITextarea',{
						url:'layUITextarea/page',
						where: that.search
					});
				}
			});
			table.on('tool(layUITextarea)', function(obj){
				var id = obj.data.id;
				if(obj.event === 'visit'){
					window.open("layUITextarea/visit?id="+id);
				}
			});
		});
	</script>
</body>

新增页面(新增和修改共用的一个页面)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<body>
<style type = "text/css">
	#layUITextareaHome{
		padding: 0 20px;
	}
	.layui-inline{
		width:45%;
		margin-top: 20px;
	}
</style>
	<div id="layUITextareaHome">
		<form id="myForm" action="layUITextarea/save" method="post" class="layui-form white-bg radius">
			<input type="hidden" name="id" id = "id" value="${model.id}">
			<div class="layui-form-item">
				<div class="layui-inline">
					<label class="layui-form-label">标题</label>
					<div class="layui-input-block">
						<input type="text" class="layui-input" name="title" value="${model.title}">
					</div>
				</div>
				<div class="layui-inline"> 
					<label class="layui-form-label">类型</label>
					<div class="layui-input-block">
						<input type="text" class="layui-input" name="type" value="${model.type}">
					</div>
				</div>
			</div>
			<textarea id="lay_edit" lay-verify="content" name = "text">${model.text}</textarea>
			
		</form>
	</div>
	<script>
		layui.use(['layedit', 'form'], function(){
			var form = layui.form;
		  	var layedit = layui.layedit;
		  	layedit.set({	//设置图片接口
		  	  	uploadImage: {
			  	    url: 'layUITextarea/upload', //接口url
			  	    type: 'post'
		  	  	}
		  	});
		  	//创建一个编辑器
		  	var index = layedit.build('lay_edit',{
		  		height: 350
		  	});
		  	//提交时把值同步到文本域中
		  	form.verify({
		  		//content富文本域中的lay-verify值
		           content: function(value) {
		               return layedit.sync(index);
		           }
		       });
		});
	</script>
</body>

查询页面:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<body>
<style type="text/css">
	.layui-form-item{
		margin: 20px 100px 0px 45px;
	}
</style>
	<form class="layui-form" action="save" method="post" lay-filter="stuform">
		<div class="layui-form-item" >
			<label class="layui-form-label">标题:</label>
			<div class="layui-input-block">
				<input type="text" name="title" value="${model.title}" class="layui-input" />
			</div>
		</div>
		<div class="layui-form-item" >
			<label class="layui-form-label">类型:</label>
			<div class="layui-input-block">
				<input type="text" name="type" value="${model.type}" class="layui-input" />
			</div>
		</div>
	</form>
</body>

java实体类:继承的BaseEntity类

package tgc.edu.exam.custom;

import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.MappedSuperclass;

/**
 * 公共实体类
 * @author asus
 *
 * @param <ID>
 */
@MappedSuperclass
public class BaseEntity<ID> {
	private ID id;
	private String createName; // 更新人
	private String createDate; // 更新时间

	@Id
	@GeneratedValue
	public ID getId() {
		return id;
	}

	public void setId(ID id) {
		this.id = id;
	}

	public String getCreateName() {
		return createName;
	}

	public void setCreateName(String createName) {
		this.createName = createName;
	}

	public String getCreateDate() {
		return createDate;
	}

	public void setCreateDate(String createDate) {
		this.createDate = createDate;
	}

	public BaseEntity(ID id, String createName, String createDate) {
		super();
		this.id = id;
		this.createName = createName;
		this.createDate = createDate;
	}
	public BaseEntity(ID id) {
		super();
		this.id = id;
	}
	public BaseEntity() {
		super();
		// TODO Auto-generated constructor stub
	}
	

}

文本域实体类:

package tgc.edu.exam.entity;

import javax.persistence.Column;
import javax.persistence.Entity;

import tgc.edu.exam.custom.BaseEntity;

/**
 * 文本域案例
 * @author asus
 *
 */
@Entity
public class LayUITextarea extends BaseEntity<Integer> {
	private String title;	//标题
	private String text;	//文本内容
	private String type;	//类型
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}
	@Column(columnDefinition="LONGTEXT")
	public String getText() {
		return text;
	}
	public void setText(String text) {
		this.text = text;
	}
	public String getType() {
		return type;
	}
	public void setType(String type) {
		this.type = type;
	}
	public LayUITextarea(Integer id, String createName, String createDate, String title, String text, String type) {
		super(id, createName, createDate);
		this.title = title;
		this.text = text;
		this.type = type;
	}
	public LayUITextarea() {
		super();
		// TODO Auto-generated constructor stub
	}
	public LayUITextarea(Integer id, String createName, String createDate) {
		super(id, createName, createDate);
		// TODO Auto-generated constructor stub
	}
	
}

控制器controller,后台核心代码

package tgc.edu.exam.web.controller;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.UUID;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import tgc.edu.exam.custom.AjaxResult;
import tgc.edu.exam.custom.DataGridParam;
import tgc.edu.exam.custom.DataGridUtils;
import tgc.edu.exam.entity.LayUITextarea;
import tgc.edu.exam.security.UserUtils;
import tgc.edu.exam.service.LayUITextareaService;
import tgc.edu.exam.service.PictureService;
import tgc.edu.exam.web.form.LayUITextareaForm;

@Controller
@RequestMapping(value="/layUITextarea")
public class LayUITextareaContreoller {
	@Autowired
	private LayUITextareaService layuiService;
	@Autowired
	private UserUtils userUtils;
	@Autowired
	private PictureService pService;
	
	//静态路径
	@Value("${web.upload-path}")
    private String path;
	
	@RequestMapping(value="/manage")
	public void manage() {
		
	}
	
	/**
	 * 查询页面
	 * @param map
	 * @param form
	 */
	@RequestMapping(value="/search")
	public void search(ModelMap map, LayUITextareaForm form) {
		map.put("model", form);
	}
	
	/**
	 * 新增修改页面
	 * @param map
	 * @param id
	 */
	@RequestMapping(value="/edit")
	public void edit(ModelMap map, Integer id) {
		LayUITextarea lay = new LayUITextarea();
		if(id != null) {
			lay = layuiService.findById(id);
		}
		map.put("model", lay);
	}
	
	/**
	 * 删除
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/delete")
	@ResponseBody
	public Object delete(Integer id) {
		layuiService.deleteById(id);
		return new AjaxResult("ok");
	}
	
	/**
	 * 图片上传
	 * @param file
	 * @return
	 */
	@RequestMapping(value="/upload")
	@ResponseBody
	public Object upload(MultipartFile file) {
		String filename = file.getOriginalFilename();
		String uuid = UUID.randomUUID().toString();
		boolean boole = pService.savefile(file, uuid);
		if (boole) {
			Map<String,Object> map = new HashMap<String,Object>();
			Map<String,Object> map2 = new HashMap<String,Object>();
			map.put("code", 0);	//0表示上传成功
			map.put("msg","上传成功"); //提示消息
			map2.put("src", path+"layUITextarea/download?uuid="+uuid);
			map2.put("title", filename);
			map.put("data", map2);
			return map;
		} else {
			return new AjaxResult(true, file.getOriginalFilename());
		}
	}
	
	/**
	 * 下载
	 * @param uuid
	 * @param request
	 * @param response
	 */
	@RequestMapping(value = "/download")
	@ResponseBody
	private void download(String uuid, HttpServletRequest request, HttpServletResponse response) {
		pService.download(uuid, request, response);
	}
	
	/**
	 * 保存
	 * @param form
	 * @return
	 */
	@RequestMapping(value="/save")
	@ResponseBody
	public Object save(LayUITextareaForm form) {
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		try {
			LayUITextarea model = new LayUITextarea();
			String name = userUtils.getName();
			Integer id = form.getId();
			if(id != null) {
				model = layuiService.findById(id);
			}
			model.setCreateDate(sdf.format(new Date()));
			model.setCreateName(name);
			BeanUtils.copyProperties(form, model,"id");
			layuiService.save(model);
			return new AjaxResult("数据保存成功");
		} catch (Exception e) {
			return new AjaxResult(false,"数据保存失败");
		}
	}
	
	/**
	 * 访问
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/visit")
	@ResponseBody
	public Object visit(Integer id) {
		return layuiService.findById(id).getText();
	}
	
	/**
	 * 数据加载
	 * @param map
	 * @param param
	 * @param form
	 * @return
	 */
	@RequestMapping(value="/page")
	@ResponseBody
	public HashMap<String, Object> data(ModelMap map, DataGridParam param, LayUITextareaForm form) {
		Sort sort=Sort.by("id");
		Pageable pabeable = param.getPageable(sort);
		Specification<LayUITextarea> spec = buildSpec(form);
		Page<LayUITextarea> page = layuiService.findAll(spec, pabeable);
		return DataGridUtils.buildResult(page);
	}

	/**
	 * 安全查询
	 * @param form
	 * @return
	 */
	private Specification<LayUITextarea> buildSpec(LayUITextareaForm form) {
		Specification<LayUITextarea> specification = new Specification<LayUITextarea>() {

			private static final long serialVersionUID = 1L;
			
			@Override
			public Predicate toPredicate(Root<LayUITextarea> root, CriteriaQuery<?> query, CriteriaBuilder cb) {
				HashSet<Predicate> rules=new HashSet<>();
				if(StringUtils.hasText(form.getTitle())) {
					Predicate name = cb.like(root.get("title"), "%"+form.getTitle()+"%");
					rules.add(name);
				}
				if(StringUtils.hasText(form.getType())) {
					Predicate difficultylevel = cb.like(root.get("type"), "%"+form.getType()+"%");
					rules.add(difficultylevel);
				}
				return cb.and(rules.toArray(new Predicate[rules.size()]));
			}

		};
		return specification;
	}
}

form表单提交获取编辑器值问题:https://blog.csdn.net/qq_40205116/article/details/89433623

图片上传回显为题:https://blog.csdn.net/qq_40205116/article/details/89433791