之前用過ueditor,結果這兩天要用又忘了怎么用了,寫個文檔記錄下來
1. UEditor簡介
UEditor是由百度web前端研發部開發所見即所得富文本web編輯器,具有輕量,可定制,注重用戶體驗等特點,開源基於MIT協議,允許自由使用和修改代碼
2. 使用環境說明
java語言 ssh框架,但這個應該任何框架方法都通用
ueditor: 我使用的是當前最新的1.4.3.3版本
開發工具:eclipse
3.先期准備
下載UEditor
下載UEditor(不是UMEditor)1.4.3.3 jsp utf-8版本壓縮包
新建web項目,將web.xml,struts等文件配置好,在此不再多說。
整合
解壓,將ueditor/jsp/lib下的jar包放入web項目的WEB-INF下的lib文件夾內
(使用maven的童鞋注意:由於maven中央倉庫沒有ueditor,所以可直接下載的源碼src包,將源碼復制進項目,不用導入ueditor-1.1.2.jar了)
4. UEditor在項目里的配置
1)前端項配置
前端項的配置比較簡單,只需要引入幾個js
這里加載編輯器的容器那段js就是會呈現在頁面的富文本編輯器,我這里直接將它包含到表單里,這樣可以直接提交。
2) 后端項配置
其實這時候啟動服務器已經可以看到編輯器的效果了,可是現在上傳圖片的時候會顯示上傳不成功,查看服務器目錄也會發現沒有圖片,這是由於
在配置struts過濾器,過濾路徑設置/*方式時,由於struts2框架默認使用apache的Commons FileUpload組件和內建的FileUploadInterceptor攔截器實現上傳,會將request文件域封裝到action中一個File類型的屬性中,並刪除request中的文件域,因此會上傳文件失敗。
– 引用自https://my.oschina.net/jiangli0502/blog/210263
為了避免這種情況,我們需要自定義一個servlet攔截器先攔截一次請求,判斷若請求地址是ueditor上傳圖片調用的jsp則可以放行:
xxx/ueditor/jsp/controller.jsp
定義的攔截器代碼:public class UeditorFilter extends StrutsPrepareAndExecuteFilter {
public void doFilter(ServletRequest req,ServletResponse res,FilterChain chain) throws IOException,ServletException{
Properties p = new Properties();
InputStream in = UeditorFilter.class.getResourceAsStream("pic.properties");
p.load(in);
String dir = p.getProperty("url");
HttpServletRequest request =(HttpServletRequest) req;
String url = request.getRequestURI();
System.out.println(url);
if(("/" + dir + "/ueditor/jsp/controller.jsp").equals(url)) {
chain.doFilter(req, res);
} else {
super.doFilter(req, res, chain);
}
}
}
web.xml需要將struts攔截器的配置改成如下:
struts2
xxx.UeditorFilter
這里由於我的項目需要在本機和服務器兩個地方部署,所以根目錄不一樣,我用propertis配置文件配置根目錄dir。
/ueditor/jsp/controller.jsp是ueditor自帶的處理上傳圖片邏輯的jsp。
這樣上傳圖片就可以成功了。我們也可以看到服務器目錄里的圖片上傳成功了。
寫一個action接收表單項並跳轉頁面顯示結果public class PublishAction extends BaseAction {
private String content;
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String saveArticle() {
System.out.println(content);
putSession("content", content);
return SUCCESS;
}
}
代碼寫好之后,需要在struts.xml里配置
res.jsp
res.jsp代碼如下${sessionScope.content }
這樣顯示內容
配置好之后,我發現上傳的圖片沒有顯示,查看html源碼后發現路徑不正確,
localhost:8080/ueditor/jsp/upload/image/20… .jpg
路徑中沒有項目目錄,打開/ueditor/jsp/config.json找到
"imagePathFormat": "/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}"
這一項,前面添加上項目目錄,變成
"imagePathFormat": "EditorTest/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}",
EditorTest是我的項目目錄,這次圖片正常顯示,但圖片目錄變成
localhost:8080/EditorTest/EditorTest/ueditor/jsp/upload/image/20… .jpg,
這可能是個bug,我最終將目錄改成如下:
"imagePathFormat": "upload/image/{yyyy}{mm}{dd}/{time}{rand:6}"
這樣圖片就上傳到項目根目錄的upload文件夾內,顯示也很正常。
配置結束,有問題歡迎留言。