在jsp中使用xheditor
在web开发中,经常会使用到编辑器进行图文内容的编辑,个人推荐使用xheditor,如你所见,CSDN也正是使用的xheditor。
官方网站为:http://xheditor.com/
xheditor-1.1.7 编辑器插件下载地址
http://download.csdn.net/detail/huahuagongzi9999/7130273
一,首先创建一个web工程:test-xheditor;具体目录结构如下:
二,按上图,导入相应的xheditor文件、lib包【commons-fileupload-1.2.1.jar,commons-io-1.3.2.jar,
commons-lang-2.4.jar,servlet-api.jar】、index.jsp。
三,系统常量类:SystemConstants.class,
/** * */ package com.xheditor.contants; /** * @author hu.shiguo * @time 2014-3-19下午11:57:14 * @description 系统常量 * @version */ public class SystemConstants { public static String WEB_ROOT = null; }
四,初始化配置类:SystemListener.class,
/** * */ package com.xheditor.listener; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import com.xheditor.contants.SystemConstants; /** * @author hu.shiguo * @time 2014-3-19下午11:50:36 * @description 系统加载监听器,可以在web容器启动的时候加载一些配置到内存中 * @version */ public class SystemListener implements ServletContextListener { /* (non-Javadoc) * @see javax.servlet.ServletContextListener#contextDestroyed(javax.servlet.ServletContextEvent) */ @Override public void contextDestroyed(ServletContextEvent event) { } /* (non-Javadoc) * @see javax.servlet.ServletContextListener#contextInitialized(javax.servlet.ServletContextEvent) */ @Override public void contextInitialized(ServletContextEvent event) { String webRoot = event.getServletContext().getRealPath("/"); System.out.println(webRoot); SystemConstants.WEB_ROOT = webRoot; } }
五,上传文件类:UploadFileServlet.class,
package com.sportevents.servlet; import java.io.File; import java.io.IOException; import java.io.PrintWriter; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.UUID; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.DiskFileUpload; import org.apache.commons.fileupload.FileItem; import org.apache.commons.lang.StringUtils; import com.sportevents.contants.SystemConstants; @SuppressWarnings({ "serial", "deprecation" }) public class UploadFileServlet extends HttpServlet { private static String baseFileDir = File.separator + "uploadFile" + File.separator;//上传文件存储目录 private static String baseURLDir = "/uploadFile/";//上传文件目录URL private static String fileExt = "jpg,jpeg,bmp,gif,png"; private static Long maxSize = 0l; // 0:不建目录 1:按天存入目录 2:按月存入目录 3:按扩展名存目录 建议使用按天存 private static String dirType = "1"; /** * 文件上传初始化工作 */ public void init() throws ServletException { /*获取文件上传存储的相当路径*/ if (!StringUtils.isBlank(this.getInitParameter("baseDir"))){ baseFileDir = this.getInitParameter("baseDir"); } String realBaseDir = this.getServletConfig().getServletContext().getRealPath(baseFileDir); File baseFile = new File(realBaseDir); if (!baseFile.exists()) { baseFile.mkdir(); } /*获取文件类型参数*/ fileExt = this.getInitParameter("fileExt"); if (StringUtils.isBlank(fileExt)) fileExt = "jpg,jpeg,gif,bmp,png"; /*获取文件大小参数*/ String maxSize_str = this.getInitParameter("maxSize"); if (StringUtils.isNotBlank(maxSize_str)) maxSize = new Long(maxSize_str); /*获取文件目录类型参数*/ dirType = this.getInitParameter("dirType"); if (StringUtils.isBlank(dirType)) dirType = "1"; if (",0,1,2,3,".indexOf("," + dirType + ",") < 0) dirType = "1"; } /** * 上传文件数据处理过程 */ @SuppressWarnings({"unchecked" }) public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html; charset=UTF-8"); response.setHeader("Cache-Control", "no-cache"); String err = ""; String newFileName = ""; DiskFileUpload upload = new DiskFileUpload(); try { List<FileItem> items = upload.parseRequest(request); Map<String, Serializable> fields = new HashMap<String, Serializable>(); Iterator<FileItem> iter = items.iterator(); while (iter.hasNext()) { FileItem item = (FileItem) iter.next(); if (item.isFormField()) fields.put(item.getFieldName(), item.getString()); else fields.put(item.getFieldName(), item); } /*获取表单的上传文件*/ FileItem uploadFile = (FileItem)fields.get("filedata"); /*获取文件上传路径名称*/ String fileNameLong = uploadFile.getName(); System.out.println("fileNameLong:" + fileNameLong); /*获取文件扩展名*/ /*索引加1的效果是只取xxx.jpg的jpg*/ String extensionName = fileNameLong.substring(fileNameLong.lastIndexOf(".") + 1); System.out.println("extensionName:" + extensionName); /*检查文件类型*/ if (("," + fileExt.toLowerCase() + ",").indexOf("," + extensionName.toLowerCase() + ",") < 0){ printInfo(response, "不允许上传此类型的文件", ""); return; } /*文件是否为空*/ if (uploadFile.getSize() == 0){ printInfo(response, "上传文件不能为空", ""); return; } /*检查文件大小*/ if (maxSize > 0 && uploadFile.getSize() > maxSize){ printInfo(response, "上传文件的大小超出限制", ""); return; } //0:不建目录, 1:按天存入目录, 2:按月存入目录, 3:按扩展名存目录.建议使用按天存. String fileFolder = ""; if (dirType.equalsIgnoreCase("1")) fileFolder = new SimpleDateFormat("yyyyMMdd").format(new Date());; if (dirType.equalsIgnoreCase("2")) fileFolder = new SimpleDateFormat("yyyyMM").format(new Date()); if (dirType.equalsIgnoreCase("3")) fileFolder = extensionName.toLowerCase(); //工程目录 String projectPath = SystemConstants.WEB_ROOT; File files = new File(projectPath); //上传文件保存目录 String uploadFilePath = files.getParent()+File.separator + "uploadFile"+File.separator +fileFolder+File.separator; //String uploadFilePath =files.getPath()+File.separator + "uploadFile"; /*文件存储的相对路径*/ //String saveDirPath = baseFileDir + fileFolder + "/"; //System.out.println("saveDirPath:" + saveDirPath); /*文件存储在容器中的绝对路径*/ //String saveFilePath = this.getServletConfig().getServletContext().getRealPath("") + baseFileDir + fileFolder + "/"; System.out.println("saveFilePath:" + uploadFilePath); /*构建文件目录以及目录文件*/ File fileDir = new File(uploadFilePath); if (!fileDir.exists()) {fileDir.mkdirs();} /*重命名文件*/ String filename = UUID.randomUUID().toString(); File savefile = new File(uploadFilePath + filename + "." + extensionName); /*存储上传文件*/ System.out.println(upload == null); uploadFile.write(savefile); //String projectBasePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath(); String projectBasePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort(); newFileName = projectBasePath + baseURLDir + fileFolder + "/" + filename + "." + extensionName; System.out.println("newFileName:" + newFileName); } catch (Exception ex) { System.out.println(ex.getMessage()); newFileName = ""; err = "错误: " + ex.getMessage(); } printInfo(response, err, newFileName); } /** * 使用I/O流输出 json格式的数据 * @param response * @param err * @param newFileName * @throws IOException */ public void printInfo(HttpServletResponse response, String err, String newFileName) throws IOException { PrintWriter out = response.getWriter(); //String filename = newFileName.substring(newFileName.lastIndexOf("/") + 1); out.println("{\"err\":\"" + err + "\",\"msg\":\"" + newFileName + "\"}"); out.flush(); out.close(); } }
六,web.xml,主要配置监听和上传文件的servlet
<listener> <listener-class>com.xheditor.listener.SystemListener</listener-class> </listener> <servlet> <servlet-name>UploadFileServlet</servlet-name> <servlet-class>com.xheditor.servlet.UploadFileServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>UploadFileServlet</servlet-name> <url-pattern>/servlet/UploadFileServlet</url-pattern> </servlet-mapping>
七,jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <c:set var="ctx" value="${pageContext.request.contextPath}" /> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>xheditor</title> <base href="<%=basePath%>"/> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <link rel="stylesheet" type="text/css" href="css/style.css"> <link rel="stylesheet" type="text/css" href="css/main.css"> <script type="text/javascript" src="${ctx}/xheditor-1.1.7/jquery/jquery-1.4.2.min.js"></script> <script type="text/javascript" src="${ctx}/xheditor-1.1.7/xheditor-1.1.7-zh-cn.min.js"></script> <script type="text/javascript" src="${ctx}/js/yz.js"></script> <script type="text/javascript"> $(document).ready(function() { //初始化xhEditor编辑器插件 $(‘#xh_editor‘).xheditor({ tools:‘full‘, skin:‘default‘, upMultiple:true, upImgUrl: "servlet/UploadFileServlet", upImgExt: "jpg,jpeg,gif,bmp,png", onUpload:insertUpload, html5Upload:false }); //xbhEditor编辑器图片上传回调函数 function insertUpload(msg) { var _msg = msg.toString(); //var _picture_name = _msg.substring(_msg.lastIndexOf("/")+1); //var _picture_path = Substring(_msg); //var _str = "<input type=‘checkbox‘ name=‘_pictures‘ value=‘"+_picture_path+"‘ checked=‘checked‘ onclick=‘return false‘/><label>"+_picture_name+"</label><br/>"; //alert("xh_editor==before="+$("#xh_editor").val()); $("#xh_editor").append(_msg); //$(""+_msg).appendTo($("#clubDesc")); //alert("xh_editor==end="+$("#xh_editor").val()); } //处理服务器返回到回调函数的字符串内容,格式是JSON的数据格式. function Substring(s){ return s.substring(s.substring(0,s.lastIndexOf("/")).lastIndexOf("/"),s.length); } //save $("#save").bind("click",function(){ // var xh_editor = $("#xh_editor").val().replace(/\s/g, ""); //alert("last=="+xh_editor); document.getElementById("froms").submit(); }); }); </script> </head> <body> <div class="contents"> <form method="POST" name ="froms" id="froms" action="test/add.html" class="dataForm"> <div class="form"> <ul> <li><label>简介:</label> <div class="fields-box"> <em></em><textarea rows="25" cols="160" name="clubDesc" id="xh_editor" style="border: 1px"></textarea> </div></li> <li><label></label> <div class="fields-box"> <input class="button_blue inputS" type="button" id="save" value="确定保存"> </div></li> </div> </ul> </div> </form> </div> <!-- <div id="uploadList"></div> --> </body> </html>
八,最后效果:
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。