kindeditor学习笔记之实现简单留言板

kindeditor实现简单留言板

没事干,研究点新玩意,今天就用kindeditor试试手,第一次接触。
官网:kindeditor官方网站,把插件下载到本地。当然谷歌的网站国内访问很是费劲,你也可以到这里下载我的kindeditor资源下载链接

步骤:

第一步:建立web工程messageApp


第二步:建立数据库

一张表message,简单点就四个字段mid(编号),author(作者)、posttime(发布时间)、message(内容)

这里写图片描述

第三步:连接数据库

连接数据库的方法有很多种,这里重新温习一下原生jdbc

写个工具类(BaseDao.java)对jdbc进行简单的封装

package com.hl.message.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 *  操作数据库的底层类
 * 
 * @author 浪丶荡
 *
 */
public class BaseDao {

    /**
     * 连接数据库的核心
     */
    //  1、驱动信息
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    //  2、URL
    private static final String URL = "jdbc:mysql://localhost:3306/message?userUnicode=ture&characterEncoding=utf8";
    //  3、用户名
    private static final String USERNAME = "root";
    //  4、密码
    private static final String PASSWORD = "123456";

    private static Connection connection = null;
    //操作sql的对象
    private static PreparedStatement preparedStatement = null;
    //结果集
    public static ResultSet resultSet = null;
    /**
     *  获取连接
     * @return
     * @throws SQLException
     * @throws ClassNotFoundException
     */
    public static Connection getConnection() throws SQLException, ClassNotFoundException{
        Class.forName(DRIVER);
        return DriverManager.getConnection(URL, USERNAME, PASSWORD);
    }
    /**
     *  公共查询方法
     * @param sql
     * @param params
     * @return
     * @throws SQLException 
     * @throws ClassNotFoundException 
     */
    public static ResultSet getQuery(String sql,String[] params) throws SQLException, ClassNotFoundException{
        connection = getConnection();
        preparedStatement = connection.prepareStatement(sql);
        if(params!=null&&params.length>0){
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setString(i+1,params[i]);
            }
        }
        //执行查询
        resultSet = preparedStatement.executeQuery();
        return resultSet;
    }
    /**
     *  底层变化方法(增删改)
     * @param sql
     * @param params
     * @return
     * @throws Exception 
     */
    public static int update(String sql,String[] params) throws ClassNotFoundException, Exception{
        int result = 0;
        connection = getConnection();
        preparedStatement = connection.prepareStatement(sql);
        if(params!=null&&params.length>0){
            for (int i = 0; i < params.length; i++) {
                preparedStatement.setString(i+1,params[i]);
            }
        }
        result = preparedStatement.executeUpdate();
        return result;

    }
    /**
     *  按顺序关闭资源
     * @throws Exception 
     */
    public static void closeAll() throws Exception {
        if(resultSet!=null){
            resultSet.close();
        }
        if(preparedStatement!=null){
            preparedStatement.close();
        }
        if(connection!=null){
            connection.close();
        }
    }
}


第四步:编写Java底层业务代码

构建一个Message实体

package com.hl.message.beans;

import java.util.Date;

/**
 *  留言实体
 * @author 浪丶荡
 *
 */
public class Message {
    //留言编号
    private Integer mid;
    //留言者
    private String author;
    //留言时间
    private Date postTime;
    //留言内容
    private String message;

    public Integer getMid() {
        return mid;
    }
    public void setMid(Integer mid) {
        this.mid = mid;
    }
    public String getAuthor() {
        return author;
    }
    public void setAuthor(String author) {
        this.author = author;
    }
    public Date getPostTime() {
        return postTime;
    }
    public void setPostTime(Date postTime) {
        this.postTime = postTime;
    }
    public String getMessage() {
        return message;
    }
    public void setMessage(String message) {
        this.message = message;
    }
    public Message() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Message(String author, Date postTime, String message) {
        super();
        this.author = author;
        this.postTime = postTime;
        this.message = message;
    }
    @Override
    public String toString() {
        return "Message [mid=" + mid + ", author=" + author + ", postTime="
                + postTime + ", message=" + message + "]";
    }


}


处理Message业务类接口

package com.hl.message.dao;

import java.util.List;

import com.hl.message.beans.Message;

/**
 *  业务Dao
 *  定义Message的操作规范
 * @author 浪丶荡
 *
 */
public interface MessageDao {

    /**
     *  获取所有留言
     * @return List
     */
    public  List<Message> getAllMessages();
    /**
     *  根据编号查找留言
     * @param mid
     * @return
     */
    //public Message getMessageByID(String mid);
    /**
     *  添加留言
     * @param message
     * @return 
     */
    public int addMessage(Message message)throws Exception;
}


处理Message业务类接口的实现类

package com.hl.message.dao.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import com.hl.message.beans.Message;
import com.hl.message.dao.BaseDao;
import com.hl.message.dao.MessageDao;

/**
 * 实现类
 * 
 * @author 浪丶荡
 * 
 */
public class MessageDaoImpl extends BaseDao implements MessageDao {

    @Override
    public List<Message> getAllMessages() {
        List<Message> list = new ArrayList<Message>();
        String sql = "select * from message";
        try {
            resultSet = this.getQuery(sql, null);
            while (resultSet.next()) {
                Message message = new Message();
                message.setMid(resultSet.getInt("mid"));
                message.setAuthor(resultSet.getString("author"));
                message.setPostTime(resultSet.getDate("postTime"));
                message.setMessage(resultSet.getString("message"));
                list.add(message);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                closeAll();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return list;
    }

    @Override
    public int addMessage(Message message) throws Exception {
        String slq = "insert into message (author,postTime,message) values(?,?,?)";
        //转换日期格式
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String date = simpleDateFormat.format(message.getPostTime());
        System.out.println(message.getPostTime());

        return this.update(slq, new String[]{message.getAuthor(),date,message.getMessage()});
    }

}


第五部:连接前后台处理数据

为了简单起见,数据处理都放在jsp中

index.jsp中获取数据库数据代码片段

<!-- 获取后台数据 -->
    <h2 align="center">留言板</h2>
    <%
        MessageDao messageDao = new MessageDaoImpl();
        List<Message> list = messageDao.getAllMessages();
        for(Message m : list){
    %>
    <table align="center" border="1" bordercolor="#CCCCFF" width="1150">
        <tr bgcolor="#CCCC99">
            <td><font color="white">作者:<%=m.getAuthor() %>&nbsp;&nbsp;&nbsp;发表时间:<%=m.getPostTime() %></font></td>
        </tr>
        <tr bgcolor="#FFFFCC">
            <td>内容:<%=m.getMessage() %></td>
        </tr>
    </table>
    <p></p>
    <%
    }   
    %>


第六步:引用编辑器插件

把下载的插件解压后拷贝到项目中

这里写图片描述

引入对应js和css

<link rel="stylesheet" href="kindeditor/themes/default/default.css" />
<link rel="stylesheet" href="kindeditor/plugins/code/prettify.css" />
<script charset="utf-8" src="kindeditor/kindeditor.js"></script>
<script charset="utf-8" src="kindeditor/lang/zh_CN.js"></script>
<script charset="utf-8" src="kindeditor/plugins/code/prettify.js"></script>


引入对应js和css时路径一定要保证正确

完整index.jsp代码

<%@ page language="java" import="java.util.*" import="com.hl.message.dao.impl.*" import="com.hl.message.dao.*"
import="com.hl.message.beans.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String htmlData = request.getParameter("message")!=null ? request.getParameter("message") : "";
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
    <title>留言板</title>
    <link rel="stylesheet" href="kindeditor/themes/default/default.css" />
    <link rel="stylesheet" href="kindeditor/plugins/code/prettify.css" />
    <style type="text/css">
        table{
            border-collapse: collapse;
            border-spacing: 0;
            padd:expression(this.cellpadding=0);
        }
    </style>
    <script charset="utf-8" src="kindeditor/kindeditor.js"></script>
    <script charset="utf-8" src="kindeditor/lang/zh_CN.js"></script>
    <script charset="utf-8" src="kindeditor/plugins/code/prettify.js"></script>
    <script>
        KindEditor.ready(function(K) {
            var editor1 = K.create('textarea[name="message"]', {
                cssPath : 'kindeditor/plugins/code/prettify.css',
                uploadJson : 'kindeditor/jsp/upload_json.jsp',
                fileManagerJson : 'kindeditor/jsp/file_manager_json.jsp',
                allowFileManager : true,
                afterCreate : function() {
                    var self = this;
                    K.ctrl(document, 13, function() {
                        self.sync();
                        document.forms['example'].submit();
                    });
                    K.ctrl(self.edit.doc, 13, function() {
                        self.sync();
                        document.forms['example'].submit();
                    });
                }
            });
            prettyPrint();
        });
    </script>
</head>
<body>
    <!-- 获取后台数据 -->
    <h2 align="center">留言板</h2>
    <%
        MessageDao messageDao = new MessageDaoImpl();
        List<Message> list = messageDao.getAllMessages();
        for(Message m : list){
    %>
    <table align="center" border="1" bordercolor="#CCCCFF" width="1150">
        <tr bgcolor="#CCCC99">
            <td><font color="white">作者:<%=m.getAuthor() %>&nbsp;&nbsp;&nbsp;发表时间:<%=m.getPostTime() %></font></td>
        </tr>
        <tr bgcolor="#FFFFCC">
            <td>内容:<%=m.getMessage() %></td>
        </tr>
    </table>
    <p></p>
    <%
    }   
    %>

    <%=htmlData%>
    <!-- 发布留言 -->
    <form action="<%=path %>/add.jsp" method="post">
        <table align="center" width="100%">
            <tr>
                <td>作者:</td>
                <td><input type="text" name="author"/></td>
            </tr>
            <tr>
                <td>留言:</td>
                <td>
                    <textarea id="test" name="message" rows="8" cols="100" style="width: 700px;height: 200px;visibility: hidden;"><%=htmlspecialchars(htmlData)%></textarea>
                </td>
            </tr>
            <tr>
                <td><input type="submit" value="提交"/></td>
                <td><input type="reset" value="重置"/></td>
            </tr>
        </table>
    </form>
</body>
</html>
<!-- 处理特殊字符 -->
<%!
private String htmlspecialchars(String str) {
    str = str.replaceAll("&", "&amp;");
    str = str.replaceAll("<", "&lt;");
    str = str.replaceAll(">", "&gt;");
    str = str.replaceAll("\"", "&quot;");
    return str;
}
%>


处理数据的add.jsp完整代码

<%@ page language="java" import="java.util.*" import="com.hl.message.beans.*" import="com.hl.message.dao.*" import="com.hl.message.dao.impl.*" pageEncoding="utf-8"%>
<%
    String author = new String(request.getParameter("author").getBytes("iso-8859-1"),"utf-8");
    String message = new String(request.getParameter("message").getBytes("iso-8859-1"),"utf-8");
    Message m = new Message();
    m.setAuthor(author);
    m.setMessage(message);
    m.setPostTime(new Date());
    MessageDao messageDao = new MessageDaoImpl();

    int result = messageDao.addMessage(m);
    if(result>0){
        response.sendRedirect("index.jsp");
    }else{
        response.sendRedirect("error.jsp");
    }

%>


第七步:测试
这里写图片描述

第八步:搞定

  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
KindEditor是一款基于JavaScript的富文本编辑器,它可以方便地集成到网站中,并支持图片上传功能。在Spring Boot中实现KindEditor图片上传可以按照以下步骤进行: 1. 在Spring Boot中添加以下依赖: ```xml <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.4</version> </dependency> ``` 2. 创建一个Controller用于处理图片上传请求,代码如下: ```java @RestController @RequestMapping("/upload") public class FileUploadController { @PostMapping("/image") public String uploadImage(HttpServletRequest request) throws Exception { MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request; MultipartFile file = multipartRequest.getFile("imgFile"); String filename = file.getOriginalFilename(); String suffix = filename.substring(filename.lastIndexOf(".") + 1); String newFilename = UUID.randomUUID().toString() + "." + suffix; String savePath = "D:/upload/images/" + newFilename; // 上传文件保存路径,根据实际情况修改 File destFile = new File(savePath); if (!destFile.getParentFile().exists()) { destFile.getParentFile().mkdirs(); } file.transferTo(destFile); String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/upload/images/" + newFilename; // 图片访问URL,根据实际情况修改 return "{\"error\":0,\"url\":\"" + url + "\"}"; } } ``` 3. 在HTML页面中集成KindEditor,并设置图片上传的请求地址,代码如下: ```html <!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>KindEditor图片上传示例</title> <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/kindeditor/4.1.11/kindeditor-all.min.css" /> <script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://cdn.bootcdn.net/ajax/libs/kindeditor/4.1.11/kindeditor-all.min.js"></script> </head> <body> <textarea id="editor"></textarea> <script> KindEditor.ready(function(K) { K.create('#editor', { uploadJson: '/upload/image', allowFileManager: false }); }); </script> </body> </html> ``` 4. 启动Spring Boot应用,访问HTML页面即可进行图片上传。上传的图片会保存在指定的路径中,并返回图片的访问URL给KindEditor进行显示。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值