一开始我不懂这个ConnectorServlet是何用处,后来发现是专门用于文件上传的,因为fckeditor默认是不支持这个功能的。

ConnectorServlet:

/*
* FCKeditor - The text editor for Internet - http://www.fckeditor.net
* Copyright (C) 2003-2008 Frederico Caldeira Knabben
*
* == BEGIN LICENSE ==
*
* Licensed under the terms of any of the following licenses at your
* choice:
*
* - GNU General Public License Version 2 or later (the "GPL")
* http://www.gnu.org/licenses/gpl.html
*
* - GNU Lesser General Public License Version 2.1 or later (the "LGPL")
* http://www.gnu.org/licenses/lgpl.html
*
* - Mozilla Public License Version 1.1 or later (the "MPL")
* http://www.mozilla.org/MPL/MPL-1.1.html
*
* == END LICENSE ==
*/
package com.sanqing.fckeditor; import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.UUID; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; import net.fckeditor.connector.Messages;
import net.fckeditor.handlers.CommandHandler;
import net.fckeditor.handlers.ConnectorHandler;
import net.fckeditor.handlers.ExtensionsHandler;
import net.fckeditor.handlers.RequestCycleHandler;
import net.fckeditor.handlers.ResourceTypeHandler;
import net.fckeditor.response.UploadResponse;
import net.fckeditor.response.XmlResponse;
import net.fckeditor.tool.Utils;
import net.fckeditor.tool.UtilsFile;
import net.fckeditor.tool.UtilsResponse; import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory; /**
* Servlet to upload and browse files.<br />
*
* This servlet accepts 4 commands which interact with the server-side
* filesystem.<br />
* The allowed commands are:
* <ul>
* <li><code>GetFolders</code>: Retrieves a list of folders in the current
* folder</li>
* <li><code>GetFoldersAndFiles</code>: Retrives a list of files and folders
* in the current folder</li>
* <li><code>CreateFolder</code>: Creates a new folder in the current folder</li>
* <li><code>FileUpload</code>: Stores an uploaded file into the current
* folder. (must be sent with POST)</li>
* </ul>
*
* @version $Id: ConnectorServlet.java 2101 2008-06-22 22:00:48Z mosipov $
*/
public class ConnectorServlet extends HttpServlet { private static final long serialVersionUID = -5742008970929377161L;
private static final Logger logger = LoggerFactory.getLogger(ConnectorServlet.class); /**
* Initialize the servlet: <code>mkdir</code> &lt;DefaultUserFilesPath&gt;
*/
public void init() throws ServletException, IllegalArgumentException {
String realDefaultUserFilesPath = getServletContext().getRealPath(
ConnectorHandler.getDefaultUserFilesPath()); File defaultUserFilesDir = new File(realDefaultUserFilesPath);
UtilsFile.checkDirAndCreate(defaultUserFilesDir); logger.info("ConnectorServlet successfully initialized!");
} /**
* Manage the <code>GET</code> requests (<code>GetFolders</code>,
* <code>GetFoldersAndFiles</code>, <code>CreateFolder</code>).<br/>
*
* The servlet accepts commands sent in the following format:<br/>
* <code>connector?Command=&lt;CommandName&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
* <p>
* It executes the commands and then returns the result to the client in XML
* format.
* </p>
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
logger.debug("Entering ConnectorServlet#doGet"); response.setCharacterEncoding("UTF-8");
response.setContentType("application/xml; charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command");
String typeStr = request.getParameter("Type");
String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr);
logger.debug("Parameter Type: {}", typeStr);
logger.debug("Parameter CurrentFolder: {}", currentFolderStr); XmlResponse xr; if (!RequestCycleHandler.isEnabledForFileBrowsing(request))
xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.NOT_AUTHORIZED_FOR_BROWSING);
else if (!CommandHandler.isValidForGet(commandStr))
xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_COMMAND);
else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_TYPE);
else if (!UtilsFile.isValidPath(currentFolderStr))
xr = new XmlResponse(XmlResponse.EN_ERROR, Messages.INVALID_CURRENT_FOLDER);
else {
CommandHandler command = CommandHandler.getCommand(commandStr);
ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = UtilsFile.constructServerSidePath(request, resourceType);
String typeDirPath = getServletContext().getRealPath(typePath); File typeDir = new File(typeDirPath);
UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists())
xr = new XmlResponse(XmlResponse.EN_INVALID_FOLDER_NAME);
else { xr = new XmlResponse(command, resourceType, currentFolderStr, UtilsResponse
.constructResponseUrl(request, resourceType, currentFolderStr, true,
ConnectorHandler.isFullUrl())); if (command.equals(CommandHandler.GET_FOLDERS))
xr.setFolders(currentDir);
else if (command.equals(CommandHandler.GET_FOLDERS_AND_FILES))
xr.setFoldersAndFiles(currentDir);
else if (command.equals(CommandHandler.CREATE_FOLDER)) {
String newFolderStr = UtilsFile.sanitizeFolderName(
new String(request.getParameter("NewFolderName").getBytes("ISO8859-1"),"UTF-8")
);
logger.debug("Parameter NewFolderName: {}", newFolderStr); File newFolder = new File(currentDir, newFolderStr);
int errorNumber = XmlResponse.EN_UKNOWN; if (newFolder.exists())
errorNumber = XmlResponse.EN_ALREADY_EXISTS;
else {
try {
errorNumber = (newFolder.mkdir()) ? XmlResponse.EN_OK
: XmlResponse.EN_INVALID_FOLDER_NAME;
} catch (SecurityException e) {
errorNumber = XmlResponse.EN_SECURITY_ERROR;
}
}
xr.setError(errorNumber);
}
}
} out.print(xr);
out.flush();
out.close();
logger.debug("Exiting ConnectorServlet#doGet");
} /**
* Manage the <code>POST</code> requests (<code>FileUpload</code>).<br />
*
* The servlet accepts commands sent in the following format:<br />
* <code>connector?Command=&lt;FileUpload&gt;&Type=&lt;ResourceType&gt;&CurrentFolder=&lt;FolderPath&gt;</code>
* with the file in the <code>POST</code> body.<br />
* <br>
* It stores an uploaded file (renames a file if another exists with the
* same name) and then returns the JavaScript callback.
*/
@SuppressWarnings("unchecked")
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
logger.debug("Entering Connector#doPost"); response.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
response.setHeader("Cache-Control", "no-cache");
PrintWriter out = response.getWriter(); String commandStr = request.getParameter("Command");
String typeStr = request.getParameter("Type");
String currentFolderStr = request.getParameter("CurrentFolder"); logger.debug("Parameter Command: {}", commandStr);
logger.debug("Parameter Type: {}", typeStr);
logger.debug("Parameter CurrentFolder: {}", currentFolderStr); UploadResponse ur; // if this is a QuickUpload request, 'commandStr' and 'currentFolderStr'
// are empty
if (Utils.isEmpty(commandStr) && Utils.isEmpty(currentFolderStr)) {
commandStr = "QuickUpload";
currentFolderStr = "/";
} if (!RequestCycleHandler.isEnabledForFileUpload(request))
ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR, null, null,
Messages.NOT_AUTHORIZED_FOR_UPLOAD);
else if (!CommandHandler.isValidForPost(commandStr))
ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_COMMAND);
else if (typeStr != null && !ResourceTypeHandler.isValid(typeStr))
ur = new UploadResponse(UploadResponse.SC_ERROR, null, null, Messages.INVALID_TYPE);
else if (!UtilsFile.isValidPath(currentFolderStr))
ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
else {
ResourceTypeHandler resourceType = ResourceTypeHandler.getDefaultResourceType(typeStr); String typePath = UtilsFile.constructServerSidePath(request, resourceType);
String typeDirPath = getServletContext().getRealPath(typePath); File typeDir = new File(typeDirPath);
UtilsFile.checkDirAndCreate(typeDir); File currentDir = new File(typeDir, currentFolderStr); if (!currentDir.exists())
ur = UploadResponse.UR_INVALID_CURRENT_FOLDER;
else { String newFilename = null;
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
//设置编码格式
upload.setHeaderEncoding("UTF-8");
try { List<FileItem> items = upload.parseRequest(request); // We upload only one file at the same time
FileItem uplFile = items.get(0);
String rawName = UtilsFile.sanitizeFileName(uplFile.getName());
String filename = FilenameUtils.getName(rawName);
String baseName = FilenameUtils.removeExtension(filename);
String extension = FilenameUtils.getExtension(filename);
//文件名自动替换
filename = UUID.randomUUID().toString() + "."+ extension; if (!ExtensionsHandler.isAllowed(resourceType, extension))
ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
else { // construct an unique file name
File pathToSave = new File(currentDir, filename);
int counter = 1;
while (pathToSave.exists()) {
newFilename = baseName.concat("(").concat(String.valueOf(counter))
.concat(")").concat(".").concat(extension);
pathToSave = new File(currentDir, newFilename);
counter++;
} if (Utils.isEmpty(newFilename))
ur = new UploadResponse(UploadResponse.SC_OK, UtilsResponse
.constructResponseUrl(request, resourceType, currentFolderStr,
true, ConnectorHandler.isFullUrl()).concat(filename));
else
ur = new UploadResponse(UploadResponse.SC_RENAMED,
UtilsResponse.constructResponseUrl(request, resourceType,
currentFolderStr, true, ConnectorHandler.isFullUrl())
.concat(newFilename), newFilename); // secure image check
if (resourceType.equals(ResourceTypeHandler.IMAGE)
&& ConnectorHandler.isSecureImageUploads()) {
if (UtilsFile.isImage(uplFile.getInputStream()))
uplFile.write(pathToSave);
else {
uplFile.delete();
ur = new UploadResponse(UploadResponse.SC_INVALID_EXTENSION);
}
} else
uplFile.write(pathToSave); }
} catch (Exception e) {
ur = new UploadResponse(UploadResponse.SC_SECURITY_ERROR);
}
} } out.print(ur);
out.flush();
out.close(); logger.debug("Exiting Connector#doPost");
} }

fckeditor.properties:

connector.userActionImpl=net.fckeditor.requestcycle.impl.UserActionImpl
connector.userPathBuilderImpl=com.fckeditor.fckeditor.MyUserPath

web.xml下当然要加入servlet的配置:

<servlet>
    <servlet-name>Connector</servlet-name>
    <servlet-class>
          com.sanqing.fckeditor.ConnectorServlet
      </servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>Connector</servlet-name>
    <url-pattern>
        /user/fckeditor/editor/filemanager/connectors/*
      </url-pattern>
  </servlet-mapping>

fckeditor主要是用作前端的插件,以下是fckeditor的主体:

参考文章:http://huaxia524151.iteye.com/blog/846520

最前面的引入:<%@ taglib uri="http://java.fckeditor.net" prefix="FCK"%>

页面中的使用:

<div>
                  <label>内容:</label>
                  <FCK:editor instanceName="content" basePath="/user/fckeditor" toolbarSet="myToolbar" height="400"></FCK:editor>
              </div>

<%@ page language="java" contentType="text/html; charset=gb2312"
pageEncoding="gb2312"%>
<%@ taglib uri="http://java.fckeditor.net" prefix="FCK"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>添加文章</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link type="text/css" rel="stylesheet" href="../css/main.css" media="all" />
<!--[if IE 6]><link type="text/css" rel="stylesheet" href="css/ie6.css" media="all" /><![endif]-->
<script type="text/javascript" src="../js/mootools.js"></script>
<script type="text/javascript" src="../js/site.js"></script>
</head>
<body>
<div id="wrapper">
<div id="container">
<div id="scene"> <img src="../images/scene.jpg" alt="" />
<h1>${empty sessionScope.blogtitle ? "博客网站系统":sessionScope.blogtitle} <br/>
<font size="8">${empty sessionScope.idiograph ? "我的签名":sessionScope.idiograph}</font>
</h1>
<div id="scale_area">
<div id="scale_knob">&raquo; Font Size &laquo;</div>
</div>
<div id="menu">
<div class="holder"> <a href="../showAllArticle.action">博客首页</a> </div>
<div class="holder"> <a href="showUserAllArticle.action">用户首页</a> </div>
<div class="holder"> <a href="editbloginfo.jsp">个性化设置</a> </div>
<div class="holder"> <a href="addArticle.jsp">写日志</a> </div>
<div class="holder"> <a href="showPhoto.action">相册</a> </div>
</div>
</div>
<div id="content">
<div id="col_left">
<div class="post">
<div class="meta"></div>
<div class="comments"><div class="comment"></div>
<h2>添加文章</h2>
<form class="h" action="addArticle.action" method="post">
<div>
<label>标题:</label>
<input type="text" name="title" />
</div>
<div>
<label>内容:</label>
<FCK:editor instanceName="content" basePath="/user/fckeditor" toolbarSet="myToolbar" height="400"></FCK:editor>
</div>
<div>
<label></label>
<div class="clear"> </div>
</div>
<div class="button_wrapper">
<input name="提交" type="submit" class="button" value="提交" />
</div>
</form>
</div>
</div>
</div>
<div id="col_right">
<div id="search_box">
<form action="http://www.865171.cn/" method="post">
<div>
<input type="text" name="search" />
</div>
<div class="button_wrapper">
<input type="submit" value="Search" class="button" />
</div>
<div class="clear"> </div>
</form>
</div>
<div id="sidebar">
<h2>页面导航</h2>
<ul>
<li><a href="../showAllArticle.action">博客首页</a></li>
<li><a href="showUserAllArticle.action">用户首页</a></li>
<li><a href="editbloginfo.jsp">个性化设置</a></li>
<li><a href="addArticle.jsp">写日志</a></li>
<li><a href="showPhoto.action">相册</a></li>
</ul>
</div>
</div>
<div class="clear"> </div>
</div>
<div id="footer">
<div class="clear"> </div>
<hr />
<p class="credit">博客网站系统</p>
</div>
</div>
</div>
</body>
</html>

我的fckeditor实践的更多相关文章

  1. 项目管理实践【五】自动编译和发布网站【Using Visual Studio with Source Control System to build and publish website automatically】

    在上一篇教程项目管理实践[三]每日构建[Daily Build Using CruiseControl.NET and MSBuild] 中,我们讲解了如何使用CCNET+MSBuild来自动编译项目 ...

  2. 项目管理实践教程二、源代码控制【Source Control Using VisualSVN Server and TortoiseSVN】

    在第一篇文章 项目管理实践教程一.工欲善其事,必先利其器[Basic Tools]发布后,根据大家的回复,我需要向大家说明几个问题: 1.为什么要用VisualSVN Server,而不用Subver ...

  3. webp图片实践之路

    最近,我们在项目中实践了webp图片,并且抽离出了工具模块,整合到了项目的基础模板中.传闻IOS10也将要支持webp,那么使用webp带来的性能提升将更加明显.估计在不久的将来,webp会成为标配. ...

  4. Hangfire项目实践分享

    Hangfire项目实践分享 目录 Hangfire项目实践分享 目录 什么是Hangfire Hangfire基础 基于队列的任务处理(Fire-and-forget jobs) 延迟任务执行(De ...

  5. TDD在Unity3D游戏项目开发中的实践

    0x00 前言 关于TDD测试驱动开发的文章已经有很多了,但是在游戏开发尤其是使用Unity3D开发游戏时,却听不到特别多关于TDD的声音.那么本文就来简单聊一聊TDD如何在U3D项目中使用以及如何使 ...

  6. Logstash实践: 分布式系统的日志监控

    文/赵杰 2015.11.04 1. 前言 服务端日志你有多重视? 我们没有日志 有日志,但基本不去控制需要输出的内容 经常微调日志,只输出我们想看和有用的 经常监控日志,一方面帮助日志微调,一方面及 ...

  7. 【大型网站技术实践】初级篇:借助Nginx搭建反向代理服务器

    一.反向代理:Web服务器的“经纪人” 1.1 反向代理初印象 反向代理(Reverse Proxy)方式是指以代理服务器来接受internet上的连接请求,然后将请求转发给内部网络上的服务器,并将从 ...

  8. Windows平台分布式架构实践 - 负载均衡

    概述 最近.NET的世界开始闹腾了,微软官方终于加入到了对.NET跨平台的支持,并且在不久的将来,我们在VS里面写的代码可能就可以通过Mono直接在Linux和Mac上运行.那么大家(开发者和企业)为 ...

  9. Mysql事务探索及其在Django中的实践(二)

    继上一篇<Mysql事务探索及其在Django中的实践(一)>交代完问题的背景和Mysql事务基础后,这一篇主要想介绍一下事务在Django中的使用以及实际应用给我们带来的效率提升. 首先 ...

随机推荐

  1. Spring HtmlUtils把HTML编码转义,可将HTML标签互相转义

    Spring HtmlUtils把HTML编码转义,可将HTML标签互相转义 2014年09月05日 ⁄ 综合 ⁄ 共 372字 ⁄ 字号 小 中 大 ⁄ 评论关闭   org.springframe ...

  2. 设置input 内容居中显示 .

    text-align:center  水平居中显示 <style type="text/css"> input.text{text-align:center;paddi ...

  3. [整理]PCB阻抗控制

    之前一直听说PCB设计中信号完整性及阻抗方面的要求,但是本人对此还是有很多的不了解,每次和别人讨论到这里后就不知道该怎么继续就这个问题交谈下去.正巧最近手头有一点工作有这方面的一些需求,就拿来花了一点 ...

  4. 算法与数据结构实验题 5.2 Missile

    1.题目: 2.解题思路: 把每个点对应的两条半径求出,之后对d1进行升序排序,对应d2也改变位置.其中一个圆心的半径r1确定之后,除去第一个圆包围的点,在其余点中找到另外一个圆的最长的半径r2,此时 ...

  5. Block的copy和循环引用的问题

    在实际开发中,发现使用Block有着比delegate和notification更简洁的优势.于是在目前的项目中大量的使用block. 在我的头文件我是这样声明使用block的. 我将block声明为 ...

  6. P1-概率论基础(Primer on Probability Theory)

    2.1概率密度函数 2.1.1定义 设p(x)为随机变量x在区间[a,b]的概率密度函数,p(x)是一个非负函数,且满足 注意概率与概率密度函数的区别. 概率是在概率密度函数下对应区域的面积,如上图右 ...

  7. iOS 16进制字符串转换成int十进制

    NSRange rangeErr; rangeErr.location = 6; rangeErr.length = 2; NSString *strings = [value substringWi ...

  8. NDK开发总结

    NDK开发差不多结束了, 估计后面也不会再碰了诶, 想着还是写个总结什么的,以后捡起来也方便哈.既然是总结,我这里就不会谈具体的细节,只会记录下我觉得重要的东西, 所以这篇随笔不是为萌新学习新知识准备 ...

  9. handlebars

    Handlebars 是 JavaScript 一个语义模板库,通过对view和data的分离来快速构建Web模板.它采用"Logic-less template"(无逻辑模版)的 ...

  10. iis+php+mysql

    来源:http://www.ttjcnet.com/forum.php?mod=viewthread&tid=137&extra= 首先下载php-5.2.0-win32.zip,my ...