UEditor 是一款功能強大的富文本編輯器,在項目中應用廣泛。
Ueditor使用
引入 UEditor
- 下載 UEditor:從 UEditor 官方網站(ueditor 官網)下載適合項目需求的版本。
- 解壓文件:將下載的壓縮包解壓到項目的靜態資源目錄下,例如在 Web 項目中,可將其解壓到
webapp
目錄下的static
文件夾中。 - 引入相關文件:在需要使用 UEditor 的頁面中,通過 HTML 的
<script>
和<link>
標簽引入 UEditor 的 JavaScript 和 CSS 文件。
?初始化 UEditor
在頁面的 JavaScript 代碼中,使用以下代碼初始化 UEditor:
var ue = UE.getEditor('editor', {// 在這里可以配置UEditor的各種參數toolbars: [// 定義工具欄按鈕['source', '|', 'undo', 'redo', '|', 'bold', 'italic', 'underline', 'strikethrough', '|', 'fontsize']],// 其他配置項autoHeightEnabled: true,autoFloatEnabled: false
});
其中,'editor'是頁面中用于顯示 UEditor 的<textarea>或<div>元素的 ID。通過配置toolbars可以定義顯示哪些工具欄按鈕,還可以配置其他參數如autoHeightEnabled(自動調整高度)、autoFloatEnabled(自動浮動工具欄)等。
創建demo文件
解壓下載的包,在解壓后的目錄創建 demo.html 文件,填入下面的html代碼(如果不是本目錄下建立要在WEB—INF下的lib中添加ueditor-1.1.2.jar)
<!DOCTYPE HTML>
<html lang="en-US"><head><meta charset="UTF-8"><title>ueditor demo</title>
</head><body><!-- 加載編輯器的容器 --><script id="container" name="content" type="text/plain">這里寫你的初始化內容</script><!-- 配置文件 --><script type="text/javascript" src="ueditor.config.js"></script><!-- 編輯器源碼文件 --><script type="text/javascript" src="ueditor.all.js"></script><!-- 實例化編輯器 --><script type="text/javascript">var ue = UE.getEditor('container');</script>
</body></html>
在瀏覽器打開demo.html
如果看到了下面這樣的編輯器,恭喜你,初次部署成功!
?
內容獲取與提交
獲取內容:在表單提交或其他需要獲取 UEditor 內容的地方,使用ue.getContent()
方法獲取編輯器中的富文本內容。例如
var content = ue.getContent();
// 將內容設置到隱藏域或直接作為表單數據提交
document.getElementById('hiddenContent').value = content;
提交內容:將獲取到的內容作為表單數據提交到后端服務器。可以通過表單的submit
方法提交,也可以使用 AJAX 進行異步提交。例如,使用 AJAX 提交的代碼如下:
$.ajax({url: 'yourServletUrl',type: 'post',data: {content: content},success: function (result) {// 處理服務器返回的結果},error: function () {// 處理錯誤}
});
后端接收與處理
在后端的 Servlet 或其他處理程序中,通過request.getParameter("content")
獲取提交的 UEditor 內容。然后可以將其存儲到數據庫中,或者進行其他相應的處理。例如,在 Java Servlet 中:
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String content = request.getParameter("content");// 對content進行處理,如存儲到數據庫// ...response.getWriter().write("success");
}
完整項目代碼:?
student.sql數據表:
CREATE TABLE `student` (`id` int(11) NOT NULL AUTO_INCREMENT,`name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,`age` int(11) DEFAULT NULL,`sex` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,`introduce` text COLLATE utf8mb4_bin,PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=22 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
add.html代碼:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<script src="js/jquery-3.7.1.min.js"></script>
<script src="js/add.js" defer></script>
<style>
.addModel, .deleteModel, .updateModel {margin-top: 20px;border: 5px, solid yellow;padding;5px;
}
</style>
</head>
<body><div class='addModel'>姓名:<input type='text' class='addName'><br> 年齡:<input type='text' class='addAge'><br> 性別:<input type='text'class='addSex'><br> 自我介紹<br><!-- 加載編輯器的容器 --><script id="container" name="content" type="text/plain">這里寫你的初始化內容</script><!-- 配置文件 --><script type="text/javascript" src="utf8-jsp/ueditor.config.js"></script><!-- 編輯器源碼文件 --><script type="text/javascript" src="utf8-jsp/ueditor.all.js"></script><input type='button' value='添加'class='addBtn'> <input type='button' value='取消' class='back'></div>
</body>
</html>
add.js代碼:
var ue=UE.getEditor('container');
//點取消小模塊隱藏 $(".back").click(function(){
// $(".addModel").css("display","none")
// $(".updateModel").css("display","none")
// $(".deleteModel").css("display","none")location.href="student.html"})
//添加$(".addBtn").click(function(){var name = $(".addName").val().trim();var sex = $(".addSex").val().trim();var age = $(".addAge").val().trim();var introduce=ue.getContent();if (name === "") {alert("姓名不能為空");return;}if (sex === "") {alert("性別不能為空");return;}if (age === "") {alert("年齡不能為空");return;}$.ajax({url: "AddServlet1",type: "post", // 修正拼寫錯誤data: { name, age, sex,introduce},success: function (value) {alert(value);location.href="student.html"},error: function () {alert("出錯啦");}});
});
?servlet代碼:
package com.qcby.servlet;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.qcby.db.MysqlUtil;/*** Servlet implementation class AddServlet1*/
@WebServlet("/AddServlet1")
public class AddServlet1 extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public AddServlet1() {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 stubresponse.getWriter().append("Served at: ").append(request.getContextPath());}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {String name=request.getParameter("name");String age=request.getParameter("age");String sex=request.getParameter("sex");String introduce=request.getParameter("introduce");introduce=introduce.replaceAll("\"", "\'");String sql ="insert into student(name,age,sex,introduce) values(\""+name+"\","+age+",\""+sex+"\",\""+introduce+"\")";System.out.println(sql);int num=MysqlUtil.add(sql);String res="worng";if(num>0) {res="添加成功";}response.setCharacterEncoding("utf-8");response.getWriter().write(res);}}
package com.qcby.servlet;import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import com.qcby.db.MysqlUtil;/*** Servlet implementation class UpdateServlet1*/
@WebServlet("/UpdateServlet1")
public class UpdateServlet1 extends HttpServlet {private static final long serialVersionUID = 1L;/*** @see HttpServlet#HttpServlet()*/public UpdateServlet1() {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 stubresponse.getWriter().append("Served at: ").append(request.getContextPath());}/*** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)*/protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {System.out.println("update post成功");String id = request.getParameter("id");String name = request.getParameter("name");String age = request.getParameter("age");String sex = request.getParameter("sex");String introduce=request.getParameter("introduce");// 檢查 introduce 是否為 nullif (introduce != null) {introduce = introduce.replaceAll("\"", "\'");} else {introduce = ""; // 若為 null,將其設為一個空字符串}String sql = "UPDATE student set name=\""+name+"\",age="+age+",sex=\""+sex+"\",introduce=\""+introduce+"\" where id="+id+";";int num=MysqlUtil.update(sql);String res="worng";if(num>0) {res="歡迎入住!!";}response.setCharacterEncoding("utf-8");response.getWriter().write(res);}}
添加:?
?修改:
?
問題:
1 引入文件時會報錯
如上邊的圖所示,在引入Editor時會報錯,1.原因時jsp文件沒放到正確的位置2.??"imageUrlPrefix": "", /* 圖片訪問路徑前綴 */需要添加項目名。
?2. 空指針異常
在 UpdateServlet1 的 doPost 方法中,introduce=introduce.replaceAll("\"", "\'"); 這行代碼會報錯。原因是當 request.getParameter("introduce") 獲取到的 introduce 為 null(即前端請求未傳遞該參數)時,對 null 對象調用 replaceAll 方法會引發 NullPointerException。
3.SQL 注入風險
構建 SQL 語句時采用字符串拼接的方式,如?String sql = "UPDATE student set name=\"" + name + "\",age=" + age + ",sex=\"" + sex + "\",introduce=\"" + introduce + "\" where id=" + id + ";";
。這種方式存在嚴重的 SQL 注入風險,惡意用戶可通過構造特殊輸入改變 SQL 語句原意,執行非法操作。
4. 參數處理問題:
- 參數為空或格式錯誤:對于從請求中獲取的參數,如?
id
、name
、age
、sex
、introduce
?等,未進行充分的空值檢查和格式驗證。若?id
?或?age
?為空,或者?age
?無法轉換為整數(在?pstmt.setInt(2, Integer.parseInt(age));
?時),會拋出?NullPointerException
?或?NumberFormatException
。 - 參數名稱不匹配:前端傳遞參數的名稱可能與后端?
request.getParameter
?方法中使用的參數名稱不一致,導致獲取不到對應的值,如前端傳遞的?introduce
?參數名與后端獲取時使用的名稱不同。
5. “ ,‘ 問題:
introduce = introduce.replaceAll("\"", "\'");
?這行代碼的目的是將字符串?introduce
?里的所有雙引號?"
?替換為單引號?'
。不過,在實際運用時會存在一些問題和需要留意的地方,下面為你詳細分析。replaceAll
?是 Java 中?String
?類的一個方法,其功能是用指定的替換字符串替換原字符串里所有匹配給定正則表達式的子字符串。在這個代碼里,正則表達式?"\""
?代表雙引號,而?"\'"
?代表單引號。因此,這行代碼會把?introduce
?字符串里的所有雙引號替換成單引號。