xhEditor与Java结合使用

xhEditor是一个轻量级的html编辑器,使用它可以非常方便的编辑图文内容,然而官方文档中只有php的演示,没有Java版的,最近两天参考网上各种各样的文档,琢磨了一下用法,现已可以正常运行,现在分享出来,不足之处,欢迎指正。
这里写图片描述

下载好xheditor之后,先在webcontent文件夹中新建目录xheditor,再把以上文件拷贝进去。

新建一个index.jsp文件:

<%@page import="lenve.test.Msg"%>
<%@page import="lenve.test.dao.Dao"%>
<%@ page language="java" import="java.util.*" 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">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>

<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" href="<%=path%>/xheditor/common.css"
    type="text/css" media="screen" />
<script type="text/javascript"
    src="<%=path%>/xheditor/jquery/jquery-1.4.2.min.js"></script>
<script type="text/javascript"
    src="<%=path%>/xheditor/xheditor-zh-cn.min.js?v=1.1.5"></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",
                            upFlashUrl : "servlet/UploadSwfServlet",
                            upFlashExt : "swf",
                            upMediaUrl : "servlet/UploadMediaServlet",
                            upMediaExt : "wmv,avi,wma,mp3,mid",
                            onUpload : insertUpload,
                            html5Upload : false
                        });
                        //xbhEditor编辑器图片上传回调函数  
                        function insertUpload(msg) {
                            var _msg = msg.toString();
                            var _picture_name = _msg.substring(_msg
                                    .lastIndexOf("/") + 1);
                            ///20150522/67c5f73e-5617-4fa0-a404-b3c2bdb1b01c.jpg
                            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/>";
                            $("#xh_editor").append(_msg);
                            $("#uploadList").append(_str);
                        }
                        //处理服务器返回到回调函数的字符串内容,格式是JSON的数据格式.  
                        function Substring(s) {
                            return s.substring(s.substring(0,
                                    s.lastIndexOf("/")).lastIndexOf("/"),
                                    s.length);
                        }
                    });
</script>
</head>

<body>
    <form action="<%=path%>/xheditorServlet" method="post">
        <div>
            标题:<input type="text" name="title" />
            <textarea id="xh_editor" name="contents" rows="25"
                style=" 100%; border: 1px"></textarea>
        </div>
        <div id="uploadList"></div>
        <br /> <input type="submit" value="提交" name="submit" /> <input
            type="reset" value="重置" name="reset" />
    </form>
</body>
</html>

图片上传servlet:

public class UploadFileServlet extends HttpServlet {

    // attached
    private static String baseFileDir = File.separator + "attached"
            + File.separator;// 上传文件存储目录
    // /attached/
    private static String baseURLDir = "/attached/";// 上传文件目录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 {
        /* 获取文件上传存储的相对路径 */
        // 如果配置文件中的baseDir不为空,就以配置文件为主,否则使用上文定义的地址
        if (!StringUtils.isBlank(this.getInitParameter("baseDir"))) {
            baseFileDir = this.getInitParameter("baseDir");
        }

        // 拿到baseFileDir的绝对路径
        // E:workspacests.metadata.pluginsorg.eclipse.wst.server.core	mp0wtpwebappsHTMLEditorattached
        String realBaseDir = this.getServletConfig().getServletContext()
                .getRealPath(baseFileDir);
        File baseFile = new File(realBaseDir);

        // 如果工程中不存在attached文件夹,则创建
        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");

        // 如果web.xml中未配置dirType,缺省值为1
        if (StringUtils.isBlank(dirType))
            dirType = "1";
        // 如果web.xml中配置了非法的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();
                /**
                 * isFormField方法用来判断FileItem对象里面封装的数据是一个普通文本表单字段,
                 * 还是一个文件表单字段。如果是普通文本表单字段,返回一个true否则返回一个false。
                 * 因此可以用该方法判断是否是普通表单域还是文件上传表单域。
                 */
                //  item.getFieldName()值为filedata
                if (item.isFormField()) {
                    fields.put(item.getFieldName(), item.getString());
                } else {
                    fields.put(item.getFieldName(), item);
                }
            }

            /* 获取表单的上传文件 */
            FileItem uploadFile = (FileItem) fields.get("filedata");

            //获取上传文件名称 如:Image 001.jpg
            String fileNameLong = uploadFile.getName();
            /* 获取文件扩展名 */
            /* 索引加1的效果是只取xxx.jpg的jpg */
            String extensionName = fileNameLong.substring(fileNameLong
                    .lastIndexOf(".") + 1);
            /* 检查文件类型 */
            // 返回指定字符在此字符串中第一次出现处的索引。如果没有找到,则返回-1
            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 saveDirPath = baseFileDir + fileFolder + "/";

            /* 文件存储在容器中的绝对路径 */
            String saveFilePath = this.getServletConfig().getServletContext()
                    .getRealPath("")
                    + baseFileDir + fileFolder + "/";

            /* 构建文件目录以及目录文件 */
            File fileDir = new File(saveFilePath);
            if (!fileDir.exists()) {
                fileDir.mkdirs();
            }

            /* 重命名文件 */
            String filename = UUID.randomUUID().toString();
            File savefile = new File(saveFilePath + filename + "."
                    + extensionName);

            /* 存储上传文件 */
            uploadFile.write(savefile);

            //  http://localhost:80/HTMLEditor
            String projectBasePath = request.getScheme() + "://"
                    + request.getServerName() + ":" + request.getServerPort()
                    + request.getContextPath();
            // 上传文件URL回调
            // newFileName =projectBasePath + baseURLDir + fileFolder + "/" +
            // filename + "." + extensionName;
            // 加上!表示为立即上传模式,不加!上传成功之后需要点击确定按钮才会在编辑器中显示
            newFileName = "!" + projectBasePath + baseURLDir + fileFolder + "/"
                    + filename + "." + extensionName;
            System.out.println(newFileName);
        } catch (Exception ex) {
            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();
    }
}

注释已经很详细了,不再赘述。

文本上传servlet:

@WebServlet("/xheditorServlet")
public class XHEditor extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private Dao msgDao;

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        response.setHeader("Cache-Control", "no-cache");
        String content = request.getParameter("contents");
        String title = request.getParameter("title");
        if (content == null || content.equals("")||title==null||title.equals(""))
            return;
        msgDao.addMsg(title,content);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

    @Override
    public void init() throws ServletException {
        msgDao = new Dao();
    }
}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  

    <servlet>  
        <servlet-name>XhEditor</servlet-name>  
        <servlet-class>lenve.test.UploadFileServlet</servlet-class>  
        <init-param>
            <param-name>baseDir</param-name>
            <param-value>/attached/</param-value>
        </init-param>
    </servlet>  
    <servlet-mapping>  
        <servlet-name>XhEditor</servlet-name>  
        <url-pattern>/servlet/UploadFileServlet</url-pattern>  
    </servlet-mapping>  

    <welcome-file-list>  
        <welcome-file>index.jsp</welcome-file>  
    </welcome-file-list>  
</web-app>  

本项目完整代码下载

原文地址:https://www.cnblogs.com/qitian1/p/6461837.html