1. 程式人生 > >在web專案中使用MarkDown元件

在web專案中使用MarkDown元件

說明

      在專案中,要錄入圖文資訊,需要將圖片存到伺服器。本篇博文將介紹在javaweb專案中,怎樣使用MarkDown元件。在專案中使用了servlet,smartupload進行檔案的上傳。原始碼放在了github中,原始碼地址:https://github.com/Edenwds/component

正文

第一步 下載元件

在GitHub上下載editor.md,在本地解壓後,得到基本元件。在example中有simple.html,可以顯示基本編輯器。

這裡寫圖片描述

第二步 建立web專案

      LZ使用的是MyEclipse,建立MarkDown專案,這裡LZ將editor.md元件全部引入專案中

這裡寫圖片描述

第三步 建立編輯頁面

LZ根據example.html頁面將index.jsp頁面改造為編輯頁面,改造時,要注意檔案路徑的修改

<%@ 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>MarkDown</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 %>/editormd/examples/css/style.css" /> <link rel="stylesheet" href="<%=path %>/editormd/css/editormd.css" /> <link rel="shortcut icon" href="https://pandao.github.io/editor.md/favicon.ico" type="image/x-icon" /> </head> <body> <div id="layout"> <header> </header> <input type="submit" value="提交" onclick="tijiao()"/> <div id="test-editormd"> <textarea style="display:none;" class="editormd-html-textarea" id="editormd"></textarea> <textarea class="editormd-html-textarea" name="text" id="editormdhtml"></textarea> </div> </div> <script src="<%=path %>/editormd/examples/js/jquery.min.js"></script> <script src="<%=path %>/editormd/editormd.min.js"></script> <script type="text/javascript"> var testEditor; $(function() { testEditor = editormd("test-editormd", { width : "90%", height : 600, syncScrolling : "single", path : "<%=path %>/editormd/lib/", imageUpload : true, imageFormats : ["jpg","jpeg","gif","png","bmp","webp"], imageUploadURL : "<%=basePath%>PicSvl", saveHTMLToTextarea : true }); /* // or testEditor = editormd({ id : "test-editormd", width : "90%", height : 640, path : "../lib/" }); */ }); function tijiao(){ var htmlco = $("#editormdhtml").val(); //alert(htmlco); $.ajax( {data:{'text':htmlco}, dataType:'text', success: function(data){ alert(data); }, type:'post', url:'<%=basePath%>TextSvl' } ); } </script> </body> </html>

路徑的修改

這裡寫圖片描述
這裡寫圖片描述

指令碼的修改
修改指令碼,使編輯器的內容可以以html格式儲存,可以本地上傳圖片,這裡LZ使用ajax進行互動

這裡寫圖片描述

注意 要設定一個隱藏的文字域,用來構造生成了html程式碼,方便表單post提交,後臺以name獲取資訊

這裡寫圖片描述

AJAX的提交
這裡寫圖片描述

第四步 建立Servlet

上傳圖片的PicServlet

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jspsmart.upload.File;
import com.jspsmart.upload.SmartUpload;
import com.jspsmart.upload.SmartUploadException;

/**
 * Servlet implementation class PicSvl
 */
public class PicSvl extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public PicSvl() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        SmartUpload smu = new SmartUpload();
        String rootPath = request.getSession().getServletContext().getRealPath("/resources/upload/pic");
        java.io.File filePath = new java.io.File(rootPath);
        if(!filePath.exists()){
            filePath.mkdirs();   //建立檔案目錄
        }
        try {
            smu.initialize(this.getServletConfig(), request, response);
            smu.setCharset("utf-8");
            smu.setAllowedFilesList("gif,jpg,png,bmp");
            smu.setMaxFileSize(200*1024);
            smu.upload();
            for(int i = 0; i < smu.getFiles().getCount(); i++){
                File file = smu.getFiles().getFile(i);
                java.io.File realfile = new java.io.File(rootPath+"/"+file.getFileName());
                file.saveAs(realfile.toString());
                String path = request.getContextPath();
                String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
                //System.out.println(basePath+"resources/upload/pic/"+file.getFilePathName());
                //返回json串  url作為圖片的地址
                response.getWriter().write("{\"success\":1,\"messgae\":\"upload successful\",\"url\":\""+basePath+"resources/upload/pic/"+file.getFilePathName()+"\"}");
            }
        } catch (SmartUploadException e) {
            response.getWriter().write("{\"success\":0}");
            e.printStackTrace();
        }
    }

}

上傳文字TextSvl

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 TextSvl extends HttpServlet {

    /**
     * Constructor of the object.
     */
    public TextSvl() {
        super();
    }

    /**
     * Destruction of the servlet. <br>
     */
    public void destroy() {
        super.destroy(); // Just puts "destroy" string in log
        // Put your code here
    }

    /**
     * The doGet method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to get.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    /**
     * The doPost method of the servlet. <br>
     *
     * This method is called when a form has its tag value method equals to post.
     * 
     * @param request the request send by the client to the server
     * @param response the response send by the server to the client
     * @throws ServletException if an error occurred
     * @throws IOException if an error occurred
     */
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String text = request.getParameter("text");
        System.out.println(text);
        response.setCharacterEncoding("utf-8");
        response.getWriter().write("上傳成功");
    }

    /**
     * Initialization of the servlet. <br>
     *
     * @throws ServletException if an error occurs
     */
    public void init() throws ServletException {
        // Put your code here
    }

}

MarkDown可以自定義,大家可以按照examples中的例子進行修改