EasyUI+Struts2整合KindEditor

EasyUI整合KindEditor:

<%@ page language="java"  pageEncoding="UTF-8"%>
<script>
var editor;
$(function(){
   var options = {
	   themeType : 'default',   //指定主题风格,可设置”default”、”simple”,指定simple时需要引入simple.css; 默认值: “default”
	   resizeType: 0,           //2或1或0,2时可以拖动改变宽度和高度,1时只能改变高度,0时不能拖动;默认值: 2
	   allowFileManager:true,   //true时显示浏览远程服务器按钮 ;默认值: false
	   allowMediaUpload:false, //true时显示视音频上传按钮。默认值: true
	   allowFlashUpload:false, //true时显示Flash上传按钮;默认值: true
	   uploadJson:'${pageContext.request.contextPath}/uploadAction!kindEditorUpload.action',          //指定上传文件的服务器端程序
	   fileManagerJson:'${pageContext.request.contextPath}/uploadAction!kindEditorView.action',     //指定浏览远程图片的服务器端程序
	   afterCreate:function(){ //加载完成后改变皮肤
		   var color = $('.panel-header').css('background-color');
		   $('.ke-toolbar').css('background-color',color);
	   }
	   
   };
   editor = KindEditor.create('#editor_id',options);
   /**
   *提交表单
   */
   $('#kindEditor').click(function(){
		var f = $('#kindEditor_From');
		
		f.form({
			url : '${pageContext.request.contextPath}/uploadAction!saveData.action',
			onSubmit : function() {
				editor.sync();
				var isValid = $(this).form('validate');
				return isValid;
			},
			success : function(d) {
				var json = $.parseJSON(d);
				if (json.success) {
					$('#editor_name').val("");
					editor.html("");
				}
				$.messager.show({
					title : '提示',
					msg : json.msg,
				});
			}
		});
		f.submit();
		
	});
});
/**
 * 浏览服务器文件
 */
  function fileManage() {
	editor.loadPlugin('filemanager', function() {
		editor.plugin.filemanagerDialog({
			viewType : 'VIEW',
			dirName : 'image',
			clickFn : function(url, title) {
				editor.insertHtml('<img src="'+url+'" alt="" />');
				editor.hideDialog();
			}
		});
	});
}
</script>

<div style="padding:5px;">

<form id="kindEditor_From" method="post">  
文章标题:<input name="cname" id=editor_name class="easyui-validatebox" data-options="required:true,missingMessage:'请填写文章标题称'" style="width: 80%;" />
<a  class="easyui-linkbutton" οnclick="fileManage();" data-options="iconCls:'icon-search',plain:true" >浏览服务器</a>  
<textarea id="editor_id" name="cdesc" style="width:100%;height:400px;">
   <strong>HTML内容</strong>
</textarea>
<a id="kindEditor" class="easyui-linkbutton" data-options="iconCls:'icon-ok'" style="position:relative;float:right;margin-top:5px;margin-right:5px">提交</a>  
</form>
</div>


后台JAVA上传程序片:

	/**
	 * KindEditor上传文件
	 */
   public void kindEditorUpload(){
	   Map<String, Object> m = new HashMap<String, Object>();
		m.put("error", 1);
		m.put("message", "上传失败!");
		String savePath = ServletActionContext.getServletContext().getRealPath("/") + ResourceUtil.getUploadDirectory() + "/";// 文件保存目录路径
		String saveUrl = "/" + ResourceUtil.getUploadDirectory() + "/";// 文件保存目录URL

		// 定义允许上传的文件扩展名
		HashMap<String, String> extMap = new HashMap<String, String>();
		extMap.put("image", ResourceUtil.get("image"));
		extMap.put("flash", ResourceUtil.get("flash"));
		extMap.put("media", ResourceUtil.get("media"));
		extMap.put("file", ResourceUtil.get("file"));


		// 检查目录
		File uploadDir = new File(savePath);
		if (!uploadDir.isDirectory()) {
			uploadDir.mkdirs();
		}

		// 检查目录写权限
		if (!uploadDir.canWrite()) {
			m.put("error", 1);
			m.put("message", "上传目录没有写权限!");
			super.writeJson(m);
			return ;
		}

		String dirName = ServletActionContext.getRequest().getParameter("dir");
		logger.info(dirName);
		if (dirName == null) {
			dirName = "image";
		}
		if (!extMap.containsKey(dirName)) {
			m.put("error", 1);
			m.put("message", "目录名不正确!");
			super.writeJson(m);
			return ;
		}

		// 创建文件夹
		savePath += dirName + "/";
		saveUrl += dirName + "/";
		File saveDirFile = new File(savePath);
		if (!saveDirFile.exists()) {
			saveDirFile.mkdirs();
		}
		SimpleDateFormat yearDf = new SimpleDateFormat("yyyy");
		SimpleDateFormat monthDf = new SimpleDateFormat("MM");
		SimpleDateFormat dateDf = new SimpleDateFormat("dd");
		Date date = new Date();
		String ymd = yearDf.format(date) + "/" + monthDf.format(date) + "/" + dateDf.format(date) + "/";
		savePath += ymd;
		saveUrl += ymd;
		File dirFile = new File(savePath);
		if (!dirFile.exists()) {
			dirFile.mkdirs();
		}
		
		MultiPartRequestWrapper multiPartRequest = (MultiPartRequestWrapper) ServletActionContext.getRequest();// 由于struts2上传文件时自动使用了request封装
		File[] files = multiPartRequest.getFiles("imgFile");// 上传的文件集合
		String[] fileNames = multiPartRequest.getFileNames("imgFile");// 上传文件名称集合
        logger.info(files.length);
		if (files == null || files.length < 1) {
			m.put("error", 1);
			m.put("message", "请选择文件!");
			super.writeJson(m);
			return ;
		}

		for (int i = 0; i < files.length; i++) {// 循环所有文件
			File file = files[i];// 上传的文件(临时文件)
			String fileName = fileNames[i];// 上传文件名

			if (file.length() > ResourceUtil.getUploadFileMaxSize()) {
				m.put("error", 1);
				m.put("message", "上传文件超出限制大小!");
				super.writeJson(m);
				return ;
			}
			
			// 检查扩展名
			String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
			if (!Arrays.<String> asList(extMap.get(dirName).split(",")).contains(fileExt)) {
				m.put("error", 1);
				m.put("message", "上传文件扩展名是不允许的扩展名。\n只允许" + extMap.get(dirName) + "格式!");
				super.writeJson(m);
				return ;
			}

			String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + fileExt;// 新的文件名称
			File uploadedFile = new File(savePath, newFileName);

			try {
				FileCopyUtils.copy(file, uploadedFile);// 利用spring的文件工具上传
				m.put("error", 0);
				m.put("url", ServletActionContext.getRequest().getContextPath() +saveUrl + newFileName);
				super.writeJson(m);
				return ;
			} catch (Exception e) {
				m.put("error", 1);
				m.put("message", "上传文件失败");
				super.writeJson(m);
			}

		}

		super.writeJson(m);
   }


浏览服务器文件程序片:

   /**
    * 浏览服务器文件
    */
   public void kindEditorView(){
	   HttpServletRequest request = ServletActionContext.getRequest();
	   HttpServletResponse response = ServletActionContext.getResponse();
	   PrintWriter out =null;
		try {
			out = response.getWriter();
		} catch (IOException e) {
			e.printStackTrace();
		}
	   
	   //根目录路径,可以指定绝对路径,比如 /var/www/attached/
		String rootPath = ServletActionContext.getServletContext().getRealPath("/") + ResourceUtil.getUploadDirectory() + "/";// 文件保存目录路径
	   //根目录URL,可以指定绝对路径,比如 http://www.yoursite.com/attached/
		String rootUrl =request.getContextPath()+ "/" + ResourceUtil.getUploadDirectory() + "/";// 文件保存目录URL
	   //图片扩展名
	   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("无效的目录名称!");
	   		return;
	   	}
	   	rootPath += dirName + "/";
	   	rootUrl += dirName + "/";
	   	File saveDirFile = new File(rootPath);
	   	if (!saveDirFile.exists()) {
	   		saveDirFile.mkdirs();
	   	}
	   }
	   //根据path参数,设置各路径和URL
	   String 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 type
	   String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";

	   //不允许使用..移动到上一级目录
	   if (path.indexOf("..") >= 0) {
	   	out.println("不允许访问!");
	   	return;
	   }
	   //最后一个字符不是/
	   if (!"".equals(path) && !path.endsWith("/")) {
	   	out.println("参数无效!");
	   	return;
	   }
	   //目录不存在或不是目录
	   File currentPathFile = new File(currentPath);
	   if(!currentPathFile.isDirectory()){
	   	out.println("目录不存在!");
	   	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());
	   }
	   Map<String, Object> result = new HashMap<String, Object>();
	   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);
       super.writeJson(result);
   }


浏览服务器文件 用到的三个类:

NameComparator

package zy.comparator;

import java.util.Comparator;
import java.util.Hashtable;

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"));
		}
	}
}


SizeComparator

package zy.comparator;

import java.util.Comparator;
import java.util.Hashtable;

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;
			}
		}
	}
}


TypeComparator

package zy.comparator;

import java.util.Comparator;
import java.util.Hashtable;

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"));
		}
	}
}<SPAN style="COLOR: #ff0000">
</SPAN>


 

说明;

super.writeJson(result);方法是返回JSON;我用的fastjson插件返回json数据

public void writeJson(Object obj){
  String json = JSON.toJSONStringWithDateFormat(obj, "yyyy-MM-dd HH:mm:ss");
  ServletActionContext.getResponse().setContentType("text/html;charset=utf-8");
  try {
   PrintWriter out = ServletActionContext.getResponse().getWriter();
   out.write(json);
   out.flush();
   out.close();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
项目:使用AngularJs编写的简单 益智游戏(附源代码)  这是一个简单的 javascript 项目。这是一个拼图游戏,也包含一个填字游戏。这个游戏玩起来很棒。有两个不同的版本可以玩这个游戏。你也可以玩填字游戏。 关于游戏 这款游戏的玩法很简单。如上所述,它包含拼图和填字游戏。您可以通过移动图像来玩滑动拼图。您还可以选择要在滑动面板中拥有的列数和网格数。 另一个是填字游戏。在这里你只需要找到浏览器左侧提到的那些单词。 要运行此游戏,您需要在系统上安装浏览器。下载并在代码编辑器中打开此项目。然后有一个 index.html 文件可供您修改。在命令提示符中运行该文件,或者您可以直接运行索引文件。使用 Google Chrome 或 FireFox 可获得更好的用户体验。此外,这是一款多人游戏,双方玩家都是人类。 这个游戏包含很多 JavaScript 验证。这个游戏很有趣,如果你能用一点 CSS 修改它,那就更好了。 总的来说,这个项目使用了很多 javascript 和 javascript 库。如果你可以添加一些具有不同颜色选项的级别,那么你一定可以利用其库来提高你的 javascript 技能。 演示: 该项目为国外大神项目,可以作为毕业设计的项目,也可以作为大作业项目,不用担心代码重复,设计重复等,如果需要对项目进行修改,需要具备一定基础知识。 注意:如果装有360等杀毒软件,可能会出现误报的情况,源码本身并无病毒,使用源码时可以关闭360,或者添加信任。
MVC(Model-View-Controller)是一种软件设计模式,用于将应用程序的不同组成部分分离开来,以实现更好的代码组织、可维护性和重用性。 而EasyUI是一种基于jQuery的用户界面插件库,提供了许多用户界面组件和交互功能,使开发人员能够快速搭建富客户端应用程序。 SQL Server 2005是一种关系型数据库管理系统,提供了强大的数据管理和查询功能,可以用于存储和操作应用程序的数据。 对于MVC+EasyUI+SQL Server 2005的源代码,它可能是一个基于MVC架构的Web应用程序,使用了EasyUI来实现用户界面,通过SQL Server 2005来存储和管理数据。 具体而言,这个源代码可能包括以下内容: 1. 模型(Model)部分:负责定义数据结构和业务逻辑,可能包括与数据库的交互、数据验证和访问控制等。 2. 视图(View)部分:负责展示用户界面,可能包括使用EasyUI组件来创建交互式的界面元素,如表格、表单、对话框等。 3. 控制器(Controller)部分:负责响应用户交互事件,处理用户的请求并调用模型来获取或修改数据,然后更新视图展示给用户。 此外,源代码还可能包括数据库的设计和初始化脚本,用于创建数据库表和设置索引、约束等。 总之,MVC+EasyUI+SQL Server 2005的源代码可能是一个结合了分层架构、可视化界面和数据库管理的应用程序,通过使用这些技术和工具可以实现更好的代码组织和开发效率,以及更好的用户体验和数据管理能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值