Spring Boot - 个人博客
文章目录
技术组合:
- 后端:Spring Boot +
JPA(mybatis) + thymeleaf模板 - 数据库:MySQL
- 前端UI:Semantic UI框架
工具与环境:
IDEAeclipse- Maven 3
- JDK 8
Axure RP 8- lombok - 简化代码
1.2 功能规划
2、页面设计与开发
2.1 设计
页面规划:
前端展示:首页、详情页、分类、标签、归档、关于我
后台管理:模板页
2.2 页面开发
2.3 插件集成
-
《给博客添加夜间模式》 - https://imjad.cn/archives/code/add-night-mode-to-blog/
-
[文字]图标生成
http://www.network-science.de/ascii/
http://patorjk.com/software/taag/#p=display&f=Graffiti&t=Type%20Something%20 -
小图标 - www.easyicon.net
2.4 目录结构
templates
│
│ application-dev.yml // 配置文件
│
├─pages // 公共页面 - thymeleaf 模板路径
│ │ /login - 登录
│ │ / - 主页
│ │ /about - 关于我
│ │
│ ├─admin // 管理页面
│ │ md //编辑
│ │
│ ├─article // 文章页面
│ │ details/xxxx
│ │
│ └─fragments // _part of page
│ _topnav.html
/doLoginUI --> 登录
/doIndexUI --> /article --> / - 主页
/about - 关于我
/article/details/xxxx - xxx文章路径
/doAdminUI --> 管理页面
/admin/md/?aritcleId=xxxxx - 修改xxx文章
/admin/
static
│
├─dist // 静态资源
│ ├─css
│ ├─js
│ ├─images // 图片
│ └─lib // 插件
-------------------------------------------------
3.1 构建与配置
1、引入Spring Boot模块:
- web
- Thymeleaf
JPAmybatis- MySQL
- Aspects
- DevTools
2、application.yml配置
- 使用 thymeleaf 3
pom.xml:
<thymeleaf.version>3.0.2.RELEASE</thymeleaf.version>
<thymeleaf-layout-dialect.version>2.1.1</thymeleaf-layout-dialect.version>
application.yml:
spring:
thymeleaf:
mode: HTML
# 暂时没用
# 默认 HTML5 、 这里改html3也能用
- 数据库连接配置
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf-8
username: root
password: root
# 用 mybatis
jpa:
hibernate:
ddl-auto: update
show-sql: true
#server
server:
port: 80
servlet:
context-path: /
-
日志配置
application.yml:
logging:
level:
root: info
com.imcoding: debug
file: log/imcoding.log
logback-spring.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<!--包含Spring boot对logback日志的默认配置-->
<include resource="org/springframework/boot/logging/logback/defaults.xml" />
<property name="LOG_FILE" value="${LOG_FILE:-${LOG_PATH:-${LOG_TEMP:-${java.io.tmpdir:-/tmp}}}/spring.log}"/>
<include resource="org/springframework/boot/logging/logback/console-appender.xml" />
<!--重写了Spring Boot框架 org/springframework/boot/logging/logback/file-appender.xml 配置-->
<appender name="TIME_FILE"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<encoder>
<pattern>${FILE_LOG_PATTERN}</pattern>
</encoder>
<file>${LOG_FILE}</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<fileNamePattern>${LOG_FILE}.%d{yyyy-MM-dd}.%i</fileNamePattern>
<!--保留历史日志一个月的时间-->
<maxHistory>30</maxHistory>
<!--
Spring Boot默认情况下,日志文件10M时,会切分日志文件,这样设置日志文件会在100M时切分日志
-->
<timeBasedFileNamingAndTriggeringPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>10MB</maxFileSize>
</timeBasedFileNamingAndTriggeringPolicy>
</rollingPolicy>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE" />
<appender-ref ref="TIME_FILE" />
</root>
</configuration>
<!--
1、继承Spring boot logback设置(可以在appliaction.yml或者application.properties设置logging.*属性)
2、重写了默认配置,设置日志文件大小在100MB时,按日期切分日志,切分后目录:
my.2017-08-01.0 80MB
my.2017-08-01.1 10MB
my.2017-08-02.0 56MB
my.2017-08-03.0 53MB
......
-->
- 生产环境与开发环境配置
- application-dev.yml
- application-pro.yml
SQL 语句
create database blogdb charset utf8 ;
3.2 异常处理
1、定义错误页面
404
500
error
2、全局处理异常
统一处理异常:
@ControllerAdvice
public class ControllerExceptionHandler {
private final Logger logger = LoggerFactory.getLogger(ControllerExceptionHandler.class);
/**
* 异常处理
* @param request
* @param e
* @return
*/
@ExceptionHandler({Exception.class})
public ModelAndView handleException(HttpServletRequest request, Exception e) throws Exception {
logger.error("Request URL : {} , Exception : {}", request.getRequestURL(), e);
if (AnnotationUtils.findAnnotation(e.getClass(), ResponseStatus.class) != null) {
throw e;
}
ModelAndView mav = new ModelAndView();
mav.addObject("url", request.getRequestURL());
mav.addObject("exception", e);
mav.setViewName("error/error");
return mav;
}
}
错误页面异常信息显示处理:
<div>
<div th:utext="'<!--'" th:remove="tag"></div>
<div th:utext="'Failed Request URL : ' + ${url}" th:remove="tag"></div>
<div th:utext="'Exception message : ' + ${exception.message}" th:remove="tag"></div>
<ul th:remove="tag">
<li th:each="st : ${exception.stackTrace}" th:remove="tag"><span th:utext="${st}" th:remove="tag"></span></li>
</ul>
<div th:utext="'-->'" th:remove="tag"></div>
</div>
3、资源找不到异常
@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundExcepiton extends RuntimeException {
public NotFoundExcepiton() {
}
public NotFoundExcepiton(String message) {
super(message);
}
public NotFoundExcepiton(String message, Throwable cause) {
super(message, cause);
}
}
3.3 日志处理
1、记录日志内容
- 请求 url
- 访问者 ip
- 调用方法 classMethod
- 参数 args
- 返回内容
2、记录日志类:
@Aspect
@Component
public class LogAspect {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 定义切面
*/
@Pointcut("execution(* com.imcoding.web.*.*(..))")
public void log() {
}
@Before("log()")
public void doBefore(JoinPoint joinPoint) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
ReqeustLog reqeustLog = new ReqeustLog(
request.getRequestURL().toString(),
request.getRemoteAddr(),
classMethod,
joinPoint.getArgs()
);
logger.info("Rquest ----- {}",reqeustLog);
}
@After("log()")
public void doAfter() {
//logger.info("---------- doAfter 2 ----------");
}
@AfterReturning(returning = "result",pointcut = "log()")
public void doAtfertRturning(Object result) {
logger.info("Return ------ {}",result );
}
private class ReqeustLog {
private String url;
private String ip;
private String classMethod;
private Object[] args;
public ReqeustLog(String url, String ip, String classMethod, Object[] args) {
this.url = url;
this.ip = ip;
this.classMethod = classMethod;
this.args = args;
}
@Override
public String toString() {
return "ReqeustLog{" +
"url='" + url + '\'' +
", ip='" + ip + '\'' +
", classMethod='" + classMethod + '\'' +
", args=" + Arrays.toString(args) +
'}';
}
}
}
3.4 页面处理
1、静态页面导入project
2、thymeleaf布局
- 定义fragment
- 使用fragment布局
3、错误页面美化
4、设计与规范
4.1 实体设计
实体类:
- 博客
Blog
- 博客分类
Type
- 博客标签
Tag
- 博客评论
Comment
- 用户
User
实体关系:
Blog类:
package com.cy.myblog.pojo.po;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
@Data
public class Blog implements Serializable {
private static final long serialVersionUID = -8759763340897328289L;
private Integer id ;
private String title ;
private String content ;
/**图片*/
private String imgUrl ;
/**转载 or 原创*/
private String flag ;
/**浏览次数*/
private Integer views ;
/**true-开启赞赏*/
private boolean isAppreciation ;
/**true-开启转载声明*/
private boolean isStatementShare;
/**true-开启评论*/
private boolean isCommentable;
/**true-开启推荐*/
private boolean isRecommend;//发布
private String createdUser ;
private Date createdTime ;
private String modifiedUser ;
private Date modifiedTime ;
}
use blogdb ;
create table b_blog (
id int primary key auto_increment ,
title varchar(200) ,
content text ,
img_url text ,
flag char(2) ,
views int ,
is_appreciation boolean ,
is_statement_share boolean ,
is_commentable boolean ,
is_recommend boolean ,
created_user varchar(60) ,
created_time datetime ,
modified_user varchar(60) ,
modified_time datetime
) charset utf8;
desc b_blog ;
Tag类:
package com.cy.myblog.pojo.po;
import java.io.Serializable;
import lombok.Data;
@Data
public class Tag implements Serializable {
private static final long serialVersionUID = 8705186748335833770L;
private Integer id ;
private String name ;
}
Type类:
package com.cy.myblog.pojo.po;
import java.io.Serializable;
import lombok.Data;
@Data
public class Type implements Serializable {
private static final long serialVersionUID = -5573877076633373728L;
private Integer id ;
private String name ;
}
use blogdb ;
create table if not exists b_type (
id int primary key auto_increment ,
name varchar(200)
) charset utf8;
desc b_type ;
Comment类:
评论类自关联关系:
package com.cy.myblog.pojo.po;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
@Data
public class Comment implements Serializable {
private static final long serialVersionUID = -6360401291243978852L;
private Integer id ;
/**上一级评论*/
private Integer parentId ;
/**根据userId,获取avatar头像、username、email*/
private Integer createUserId ;
private Date createdTime ;
private String content ;
}
use blogdb ;
create table if not exists b_comment (
id int primary key auto_increment ,
parent_id int ,
created_user_id int ,
created_time datetime ,
content text
) charset utf8;
desc b_comment ;
User类:
package com.cy.myblog.pojo.po;
import java.io.Serializable;
import java.util.Date;
import lombok.Data;
@Data
public class User implements Serializable {
private static final long serialVersionUID = 3952133709839414786L;
private Integer id ;
/**账号*/
private String username ;
/**密码*/
private String password ; //md5
/**盐值*/
private String salt ;
/**昵称*/
private String nickname ;
private String mobile ;
private String qq ;
private String email ;
/**头像-url*/
private String avatarUrl;
/**1=启用,0=禁用*/
private Integer valid=1; //状态 1=OK 0=禁用
private Date createdTime ;
private Date modifiedTime ;
}
use blogdb ;
create table if not exists b_user (
id int primary key auto_increment ,
username varchar(60) ,
password varchar(100) ,
salt varchar(60) ,
nickname varchar(60) ,
mobile char(13) ,
qq char(11) ,
email varchar(30) ,
avatar_url text ,
vaild tinyint(4) ,
created_time datetime ,
modified_time datetime
) charset utf8;
desc b_user ;
use blogdb ;
alter table b_user change vaild valid int ;
alter table b_user modify username varchar(60) unique not null ;
alter table b_user modify password varchar(100) not null ;
Role类
权限管理 ⇒ 未完待续.。。。
4.2 应用分层
4.3 命名约定
Service/DAO层命名约定:
- 获取单个对象的方法用
find
做前缀。Object - 获取多个对象的方法用
find
做前缀。Objects - 获取统计值的方法用
count
做前缀。 - 插入的方法用
或save
(推荐)insert
做前缀。 - 删除的方法用
或remove
(推荐)delete
做前缀。 - 修改的方法用
update
做前缀。
5、后台管理功能实现
5.1 登录
1、构建登录页面和后台管理首页
2、UserService和UserRepository
3、LoginController实现登录
4、MD5加密
5、登录拦截器
5.2 分类管理
1、分类管理页面
2、分类列表分页
{
"content":[
{"id":123,"title":"blog122","content":"this is blog content"},
{"id":122,"title":"blog121","content":"this is blog content"},
{"id":121,"title":"blog120","content":"this is blog content"},
{"id":120,"title":"blog119","content":"this is blog content"},
{"id":119,"title":"blog118","content":"this is blog content"},
{"id":118,"title":"blog117","content":"this is blog content"},
{"id":117,"title":"blog116","content":"this is blog content"},
{"id":116,"title":"blog115","content":"this is blog content"},
{"id":115,"title":"blog114","content":"this is blog content"},
{"id":114,"title":"blog113","content":"this is blog content"},
{"id":113,"title":"blog112","content":"this is blog content"},
{"id":112,"title":"blog111","content":"this is blog content"},
{"id":111,"title":"blog110","content":"this is blog content"},
{"id":110,"title":"blog109","content":"this is blog content"},
{"id":109,"title":"blog108","content":"this is blog content"}],
"last":false,
"totalPages":9,
"totalElements":123,
"size":15,
"number":0,
"first":true,
"sort":[{
"direction":"DESC",
"property":"id",
"ignoreCase":false,
"nullHandling":"NATIVE",
"ascending":false
}],
"numberOfElements":15
}
3、分类新增、修改、删除
5.3 标签管理
5.4 博客管理
1、博客分页查询
2、博客新增
3、博客修改
4、博客删除
6、前端展示功能实现
6.1 首页展示
1、博客列表
2、top分类
3、top标签
4、最新博客推荐
5、博客详情
1、Markdown 转换 HTML
- commonmark-java https://github.com/atlassian/commonmark-java
- pom.xml引用commonmark和扩展插件
<dependency>
<groupId>com.atlassian.commonmark</groupId>
<artifactId>commonmark</artifactId>
<version>0.10.0</version>
</dependency>
<dependency>
<groupId>com.atlassian.commonmark</groupId>
<artifactId>commonmark-ext-heading-anchor</artifactId>
<version>0.10.0</version>
</dependency>
<dependency>
<groupId>com.atlassian.commonmark</groupId>
<artifactId>commonmark-ext-gfm-tables</artifactId>
<version>0.10.0</version>
</dependency>
2、评论功能
- 评论信息提交与回复功能
- 评论信息列表展示功能
- 管理员回复评论功能