項目結構如下:
準備工作:http://ckeditor.com/download下載ckeditor(本例中使用的是3.2版本),下載完後,解壓拷貝到WebContent目錄下,匯入smartupload.jar包,用於處理圖片和視頻的上傳。建立upload檔案夾用於存放圖片和上傳的視頻。
①修改ckeditor目錄下的config.js檔案
CKEDITOR.editorConfig = function( config ){// Define changes to default configuration here. For example:// config.language = 'fr';// config.uiColor = '#AADC6E';config.language='zh-cn';//配置語言config.uiColor='#FFF';//背景顏色config.width="auto";//寬度config.height='300px';//高度config.skin='office2003';config.toolbar='Full';//工具列風格Full,Basicconfig.font_names='宋體/宋體;黑體/黑體;仿宋/仿宋_GB2312;楷體/楷體_GB2312;隸書/隸書;幼圓/幼圓;'+config.font_names;//將中文字型添加到字型列表};
②index.jsp頁面如下:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <%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><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>線上編輯器CKeditor的應用</title></head><script type="text/javascript" src="<%=basePath%>ckeditor/ckeditor.js"></script><body><h2>線上編輯器CKeditor的應用</h2><form action="CKeditorContextSave" method="post" onsubmit="return checkEditor()"><textarea name="editor2" id="editor2" rows="10" cols="80"></textarea><br/><input type="submit" value="提交"/></form></body><!-- 注意此處javascript代碼要在後面,不然會找不到editor2 --><script type="text/javascript">CKEDITOR.replace('editor2',{filebrowserImageUploadUrl:'<%=basePath%>fileUpload?type=image',filebrowserFlashUploadUrl:'<%=basePath%>fileUpload?type=flash'});function checkEditor(){var editor_data = CKEDITOR.instances.editor2.getData();if(editor_data == ""){alert("編輯器內容不可為空,請輸入具體內容後提交");return false;}elsereturn true;}</script></html>
③CKeditorFileUpload.java代碼如下:(處理圖片和視頻的上傳)
package com.servlet;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletConfig;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.lxh.smart.SmartUpload;public class CKeditorFileUpload 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 {resp.setContentType("text/html");PrintWriter out = resp.getWriter();resp.setCharacterEncoding("utf-8");req.setCharacterEncoding("utf-8");StringBuffer sb = new StringBuffer();sb.append("<script type=\"text/javascript\">\n");String type=req.getParameter("type");String allowList = "rar,zip";String errMsg = "對不起,檔案上傳失敗!";if(type.equalsIgnoreCase("image")){allowList = "gif,jpg,png,bmp,tif";}else if(type.equalsIgnoreCase("video")){allowList = "flv";}else if(type.equalsIgnoreCase("flash")){allowList = "swf";}String basePath = getServletContext().getRealPath("/upload").replaceAll("\\\\", "/");try {ServletConfig config = getServletConfig();SmartUpload mySmartUpload = new SmartUpload();mySmartUpload.initialize(config,req,resp);mySmartUpload.setAllowedFilesList(allowList);mySmartUpload.upload();//實現檔案上傳if(mySmartUpload.getFiles().getFile(0).getFileName().trim().length()>0){System.out.println(new String(mySmartUpload.getFiles().getFile(0).getFileName().getBytes(),"utf-8"));String fileName = String.valueOf(System.currentTimeMillis())+"."+mySmartUpload.getFiles().getFile(0).getFileExt();mySmartUpload.getFiles().getFile(0).saveAs(basePath+"/"+fileName);//上傳成功後返迴文件的引用地址sb.append("window.parent.CKEDITOR.tools.callFunction(1,'"+req.getContextPath()+"/upload/"+fileName+"');\n");}else{//為選擇上傳檔案時提示錯誤資訊errMsg = "對不起,檔案不可為空,請選擇檔案後上傳!";errMsg = new String(errMsg.getBytes(),"utf-8");sb.append("window.parent.CKEDITOR.tools.callFunction(1,'"+errMsg+"');\n");}} catch (Exception e) {e.printStackTrace();errMsg = new String(errMsg.getBytes(),"iso8859-1");sb.append("window.parent.CKEDITOR.tools.callFunction(1,'"+errMsg+"');\n");}sb.append("</script>\n");out.println(sb.toString());out.flush();out.close();}}
④CKeditorContextSave.java代碼如下:(將輸入的內容儲存後顯示,此處執行個體沒儲存直接顯示)
package com.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class CKeditorContextSave extends HttpServlet{@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {doPost(req, resp);}protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException ,IOException {req.setCharacterEncoding("utf-8");String context = req.getParameter("editor2");System.out.println(context);req.setAttribute("context", context);req.getRequestDispatcher("process.jsp").forward(req, resp);};}
⑤web.xml檔案:
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <servlet> <servlet-name>CKeditorFileUpload</servlet-name> <servlet-class>com.servlet.CKeditorFileUpload</servlet-class> </servlet> <servlet-mapping> <servlet-name>CKeditorFileUpload</servlet-name> <url-pattern>/fileUpload</url-pattern> </servlet-mapping> <servlet> <servlet-name>CKeditorContextSave</servlet-name> <servlet-class>com.servlet.CKeditorContextSave</servlet-class> </servlet> <servlet-mapping> <servlet-name>CKeditorContextSave</servlet-name> <url-pattern>/CKeditorContextSave</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>/index.jsp</welcome-file> </welcome-file-list></web-app>
⑥process.jsp代碼如下:(僅用於顯示輸入的內容)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>Insert title here</title></head><body><%String context = (String)request.getAttribute("context");out.println(context);%></body></html>
⑦效果如下:
點擊提交後: