热门课程

免费试听

上课方式

开班时间

当前位置: 首页 -   文章 -   新闻动态 -   正文

SpringBoot整合富文本编辑器

知了堂姐
2024-07-09 11:12:24
0

1、数据库设计

article:文章表

| 字段      |          | 备注      || ------- | -------- | ------- || id      | int      | 文章的唯一ID || author  | varchar  | 作者      || title   | varchar  | 标题      || content | longtext | 文章的内容   |

见表SQL:

CREATE TABLE `article` (
`id` int(10) NOT NULL AUTO_INCREMENT COMMENT 'int文章的唯一ID',
`author` varchar(50) NOT NULL COMMENT '作者',
`title` varchar(100) NOT NULL COMMENT '标题',
`content` longtext NOT NULL COMMENT '文章的内容',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

2、基础项目搭建

2.1、建一个SpringBoot项目配置

spring:
datasource:
  username: root
  password: 123456
  #?serverTimezone=UTC解决时区的报错
  url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
  driver-class-name: com.mysql.cj.jdbc.Driver

   
       src/main/java
       
           **/*.xml
       
       true
   

2.2、实体类:

//文章类
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Article implements Serializable {
   private int id; //文章的唯一ID
   private String author; //作者名
   private String title; //标题
   private String content; //文章的内容
}

2.3、mapper接口:

@Mapper
@Repository
public interface ArticleMapper {
   //查询所有的文章
   List
queryArticles(); //新增一个文章 int addArticle(Article article); //根据文章id查询文章 Article getArticleById(int id); //根据文章id删除文章 int deleteArticleById(int id); } insert into article (author,title,content) values (#{author},#{title},#{content}); delete from article where id = #{id}

既然已经提供了 myBatis 的映射配置文件,自然要告诉 spring boot 这些文件的位置**

mybatis:
mapper-locations: classpath:com/kuang/mapper/*.xml
type-aliases-package: com.kuang.pojo

编写一个Controller测试下,是否ok;

3、文章编辑整合(重点)

3.1、导入 editor.md 资源 ,删除多余文件

3.2、编辑文章页面 editor.html、需要引入 jQuery;




   
   秦疆'Blog
   
   
   
   
   
   


标题:
作者:

3.3、编写Controller,进行跳转,以及保存文章

@Controller
@RequestMapping("/article")
public class ArticleController {
   @GetMapping("/toEditor")
   public String toEditor(){
       return "editor";
  }
   @PostMapping("/addArticle")
   public String addArticle(Article article){
       articleMapper.addArticle(article);
       return "editor";
  }
}
图片上传问题

1、前端js中添加配置

//图片上传
imageUpload : true,
imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL : "/article/file/upload", // //这个是上传图片时的访问地址

2、后端请求,接收保存这个图片, 需要导入 FastJson 的依赖

//博客图片上传问题
@RequestMapping("/file/upload")
@ResponseBody
public JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
   //上传路径保存设置
   //获得SpringBoot当前项目的路径:System.getProperty("user.dir")
   String path = System.getProperty("user.dir")+"/upload/";
   //按照月份进行分类:
   Calendar instance = Calendar.getInstance();
   String month = (instance.get(Calendar.MONTH) + 1)+"月";
   path = path+month;
   File realPath = new File(path);
   if (!realPath.exists()){
       realPath.mkdir();
  }
   //上传文件地址
   System.out.println("上传文件保存地址:"+realPath);
   //解决文件名字问题:我们使用uuid;
   String filename = "ks-"+UUID.randomUUID().toString().replaceAll("-", "");
   //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
   file.transferTo(new File(realPath +"/"+ filename));
   //给editormd进行回调
   JSONObject res = new JSONObject();
   res.put("url","/upload/"+month+"/"+ filename);
   res.put("success", 1);
   res.put("message", "upload success!");
   return res;
}

3、解决文件回显显示的问题,设置虚拟目录映射!在我们自己拓展的MvcConfig中进行配置即可!

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
   // 文件保存在真实目录/upload/下,
   // 访问的时候使用虚路径/upload,比如文件名为1.png,就直接/upload/1.png就ok了。
   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/upload/**")
          .addResourceLocations("file:"+System.getProperty("user.dir")+"/upload/");
  }
}
表情包问题

自己手动下载,emoji 表情包,放到图片路径下:

修改editormd.js文件

// Emoji graphics files url path
editormd.emoji     = {
   path : "../editormd/plugins/emoji-dialog/emoji/",
   ext   : ".png"
};

4、文章展示

4.1、Controller 中增加方法

@GetMapping("/{id}")
public String show(@PathVariable("id") int id,Model model){
   Article article = articleMapper.getArticleById(id);
   model.addAttribute("article",article);
   return "article";
}

4.2、编写页面 article.html




   
   
   


作者:

5、可能会出现的问题

上传图片,未找到上传数据

public class BinaryUploader {

	public static final State save(HttpServletRequest request,
								   Map conf) {

		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}


		try {
			//将request 转化成 MultipartHttpServletRequest
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());
			if(multipartFile==null){
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}

			String savePath = (String) conf.get("savePath");
			String originFileName = multipartFile.getOriginalFilename();
			String suffix = FileType.getSuffixByFilename(originFileName);

			originFileName = originFileName.substring(0,
					originFileName.length() - suffix.length());
			savePath = savePath + suffix;

			long maxSize = ((Long) conf.get("maxSize")).longValue();

			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}

			savePath = PathFormat.parse(savePath, originFileName);

			//此处为springboot中自定义 资源上传的硬盘路径,可以根据自己需求再controller中读取自定义配置设置
			String uploadPath = "";
			if(request.getAttribute("uploadPath")!=null){
				uploadPath = (String)request.getAttribute("uploadPath");
			}

			String physicalPath = uploadPath + savePath;

			InputStream is = multipartFile.getInputStream();
			State storageState = StorageManager.saveFileByInputStream(is,
					physicalPath, maxSize);
			is.close();

			if (storageState.isSuccess()) {
				storageState.putInfo("url",  PathFormat.format(savePath));
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName + suffix);
			}

			return storageState;
		} catch (IOException e) {
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	private static boolean validType(String type, String[] allowTypes) {
		List list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
}

重新编译后打包,我们再来测试一下;

6、测试

重启项目,浏览器地址栏输入http://localhost:8080/,访问进行测试!大功告成!

end~

大家都在看

在外企上班是一种什么体验

2024-07-09 浏览次数:0

有哪些免费的ai工具?按头推荐这6款

2024-07-09 浏览次数:0

Java程序员就业饱和了吗?Java市场环境了解...

2024-07-09 浏览次数:0

0基础怎么转行做网络安全?网安怎么学?

2024-07-09 浏览次数:0

互联网协议IPv6是什么?知了堂详解

2024-07-09 浏览次数:0

思科路由器的启动过程

2024-07-09 浏览次数:0
最新资讯
SpringBoot整合富文本... SpringBoot整合富文本编辑器
SpringBoot整合Dru... 1、Druid简介 Druid是阿里巴巴开发的号称为监控而生的数据库连接池,Druid是目前最好的数...
SpringBoot整合QQ邮... 前言 邮件服务是我们工作中常用的服务之一,作用是非常的多,对外可以给用户发送活动、营销广告等;对内可...
MybatisPlus介绍以及... MybatisPlus在Mybatis的基础上只做增强,不做改变,就像是魂斗罗中的红人和蓝人一样。 ...
SpringBoot 整合 E... Elasticsearch可以作为一个大型分布式集群(数百台服务器)技术,处理PB级数据,服务大公司...
SpringBoot整合Cap... 1. 基本结构 使用Captcha生成验证码, 利用Redis存储验证码; Redis中的结构为...
Springboot实现软件L... 在我们做系统级框架的时候,我们要一定程度上考虑系统的使用版权,不能随便一个人拿去在任何环境都能用,所...
SpringBoot 常见7大... 1、SpringBoot是什么 Spring Boot 是 Spring 开源组织下的子项目,是 S...
标题:
作者:

3.3、编写Controller,进行跳转,以及保存文章

@Controller
@RequestMapping("/article")
public class ArticleController {
   @GetMapping("/toEditor")
   public String toEditor(){
       return "editor";
  }
   @PostMapping("/addArticle")
   public String addArticle(Article article){
       articleMapper.addArticle(article);
       return "editor";
  }
}
图片上传问题

1、前端js中添加配置

//图片上传
imageUpload : true,
imageFormats : ["jpg", "jpeg", "gif", "png", "bmp", "webp"],
imageUploadURL : "/article/file/upload", // //这个是上传图片时的访问地址

2、后端请求,接收保存这个图片, 需要导入 FastJson 的依赖

//博客图片上传问题
@RequestMapping("/file/upload")
@ResponseBody
public JSONObject fileUpload(@RequestParam(value = "editormd-image-file", required = true) MultipartFile file, HttpServletRequest request) throws IOException {
   //上传路径保存设置
   //获得SpringBoot当前项目的路径:System.getProperty("user.dir")
   String path = System.getProperty("user.dir")+"/upload/";
   //按照月份进行分类:
   Calendar instance = Calendar.getInstance();
   String month = (instance.get(Calendar.MONTH) + 1)+"月";
   path = path+month;
   File realPath = new File(path);
   if (!realPath.exists()){
       realPath.mkdir();
  }
   //上传文件地址
   System.out.println("上传文件保存地址:"+realPath);
   //解决文件名字问题:我们使用uuid;
   String filename = "ks-"+UUID.randomUUID().toString().replaceAll("-", "");
   //通过CommonsMultipartFile的方法直接写文件(注意这个时候)
   file.transferTo(new File(realPath +"/"+ filename));
   //给editormd进行回调
   JSONObject res = new JSONObject();
   res.put("url","/upload/"+month+"/"+ filename);
   res.put("success", 1);
   res.put("message", "upload success!");
   return res;
}

3、解决文件回显显示的问题,设置虚拟目录映射!在我们自己拓展的MvcConfig中进行配置即可!

@Configuration
public class MyMvcConfig implements WebMvcConfigurer {
   // 文件保存在真实目录/upload/下,
   // 访问的时候使用虚路径/upload,比如文件名为1.png,就直接/upload/1.png就ok了。
   @Override
   public void addResourceHandlers(ResourceHandlerRegistry registry) {
       registry.addResourceHandler("/upload/**")
          .addResourceLocations("file:"+System.getProperty("user.dir")+"/upload/");
  }
}
表情包问题

自己手动下载,emoji 表情包,放到图片路径下:

修改editormd.js文件

// Emoji graphics files url path
editormd.emoji     = {
   path : "../editormd/plugins/emoji-dialog/emoji/",
   ext   : ".png"
};

4、文章展示

4.1、Controller 中增加方法

@GetMapping("/{id}")
public String show(@PathVariable("id") int id,Model model){
   Article article = articleMapper.getArticleById(id);
   model.addAttribute("article",article);
   return "article";
}

4.2、编写页面 article.html




   
   
   


作者:

5、可能会出现的问题

上传图片,未找到上传数据

public class BinaryUploader {

	public static final State save(HttpServletRequest request,
								   Map conf) {

		if (!ServletFileUpload.isMultipartContent(request)) {
			return new BaseState(false, AppInfo.NOT_MULTIPART_CONTENT);
		}


		try {
			//将request 转化成 MultipartHttpServletRequest
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			MultipartFile multipartFile = multipartRequest.getFile(conf.get("fieldName").toString());
			if(multipartFile==null){
				return new BaseState(false, AppInfo.NOTFOUND_UPLOAD_DATA);
			}

			String savePath = (String) conf.get("savePath");
			String originFileName = multipartFile.getOriginalFilename();
			String suffix = FileType.getSuffixByFilename(originFileName);

			originFileName = originFileName.substring(0,
					originFileName.length() - suffix.length());
			savePath = savePath + suffix;

			long maxSize = ((Long) conf.get("maxSize")).longValue();

			if (!validType(suffix, (String[]) conf.get("allowFiles"))) {
				return new BaseState(false, AppInfo.NOT_ALLOW_FILE_TYPE);
			}

			savePath = PathFormat.parse(savePath, originFileName);

			//此处为springboot中自定义 资源上传的硬盘路径,可以根据自己需求再controller中读取自定义配置设置
			String uploadPath = "";
			if(request.getAttribute("uploadPath")!=null){
				uploadPath = (String)request.getAttribute("uploadPath");
			}

			String physicalPath = uploadPath + savePath;

			InputStream is = multipartFile.getInputStream();
			State storageState = StorageManager.saveFileByInputStream(is,
					physicalPath, maxSize);
			is.close();

			if (storageState.isSuccess()) {
				storageState.putInfo("url",  PathFormat.format(savePath));
				storageState.putInfo("type", suffix);
				storageState.putInfo("original", originFileName + suffix);
			}

			return storageState;
		} catch (IOException e) {
		}
		return new BaseState(false, AppInfo.IO_ERROR);
	}

	private static boolean validType(String type, String[] allowTypes) {
		List list = Arrays.asList(allowTypes);

		return list.contains(type);
	}
}

重新编译后打包,我们再来测试一下;

6、测试

重启项目,浏览器地址栏输入http://localhost:8080/,访问进行测试!大功告成!

end~

Springboot

上一篇:动态代理和静态代理

下一篇:IDEA+Mybatis-generator代码生成工具

相关内容

SpringBoot整合富...
SpringBoot整合富文本编辑器
2024-07-09 11:12:24
SpringBoot整合D...
1、Druid简介 Druid是阿里巴巴开发的号称为监控而生的数据...
2024-07-09 11:12:24
SpringBoot整合Q...
前言 邮件服务是我们工作中常用的服务之一,作用是非常的多,对外可以...
2024-07-09 11:12:24
MybatisPlus介绍...
MybatisPlus在Mybatis的基础上只做增强,不做改变,...
2024-07-09 11:12:24
SpringBoot 整合...
Elasticsearch可以作为一个大型分布式集群(数百台服务器...
2024-07-09 11:12:24
SpringBoot整合C...
1. 基本结构 使用Captcha生成验证码, 利用Redis存...
2024-07-09 11:12:24

热门资讯

就业课程介绍(Java+前端+... Java+大数据,前端全栈,信息安全
关于我们 请输入文章描述
0基础转行信安,他如何做到月薪... 转行并非简单的换份工作,而是我们在职场进行自我认同、重塑身份的一个过程。今天知了小姐姐为大家介绍一位...
【前端每日一题】什么是BFC?... 秋招马上就要开始了,小伙伴们最近在准备面试的东西没呢,知了姐今天将蛋糕哥整理的前端面试题共享出来,同...
cisp考试费用多少?cisp... 随着网络技术的快速发展,网络安全问题变得越来越重要。那么,CISP考试费用多少?CISP报名条件是什...
pythone 文件和数据格式... 关于 Python 对文件的处理,以下选项中描述错误的是
img标签的onerror事件... 1.img 标签除了 onerror 属性外,还有其他获取管理员路径的办法吗? src 指定一个远程...
知了堂官网V3第一版内测邀请 经过几个月的加班加点,我们终于迎来了知了堂官网3.1.0版本 现正招募内测中
网络安全运维岗面试题及答案详解... 在当今数字化时代,网络安全运维工程师的角色变得愈发重要。为了保障网络安全,各个企业都需要拥有一支经验...
川农第一次线下拓展精彩瞬间 5月15日,知了堂的哥哥姐姐们携手企业拓展教练浩浩荡荡奔赴川农。
-->