(eblog)1、项目架构搭建、首页页面初始化

8,513 阅读7分钟

公众号:MarkerHub(关注获取更多项目资源)

eblog 代码仓库:github.com/markerhub/e…

eblog 项目视频: www.bilibili.com/video/BV1ri…


开发文档目录:

(eblog)1、项目架构搭建、首页页面初始化

(eblog)2、整合Redis,以及项目优雅的异常处理与返回结果封装

(eblog)3、用Redis的zset有序集合实现一个本周热议功能

(eblog)4、自定义 Freemaker 标签实现博客首页数据填充

(eblog)5、博客分类填充、登录注册逻辑

(eblog)6、博客发布收藏、用户中心的设置

(eblog)7、消息异步通知、细节调整

(eblog)8、博客搜索引擎开发、后台精选

(eblog)9、即时群聊开发,聊天记录等


前后端分离项目vueblog请点击这里:超详细!4小时开发一个SpringBoot+vue前后端分离博客项目!!


目录:

1、Github上最值得学习的Springboot开源博客项目eblog!


项目基本架构搭建

以下过程,我们以 idea 为开发工具,新建一个 springboot 项目。

开发环境:

  • idea

  • jdk 1.8

  • maven 3.3.9

  • mysql 5.7

1. 新建 springboot 项目

打开 idea,新建一个 project,选择 Spring Initializr。project 基本信息填写如下:

接下来,我们来选择一下我们需要集成的框架或中间件,就我们现在刚开发阶段,我们选择以下依赖就可以了:

  • web

  • Lombok

  • Devtools

  • freemaker

  • Mysql

  • Redis

当然了,有些依稀需要我们去完成一些配置,比如我们的 mysql、redis 需要配置连接信息,一般来说 springboot 有帮我们完成了很多默认配置,只要按照默认配置来,我们都不需要去修改或者写配置,比如 freemaker 的~

选择好了之后,idea 会自动我们添加依赖,打开项目如下:

pom.xml 的依赖包如下:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <scope>runtime</scope>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

现在,我们去一步步完成框架的集成。

2. 集成 lombok

刚才我们已经自动导入了 lombok 的依赖包

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency

如果你使用 lombok 注解还报错,说明你的 idea 还没有安装 lombok 插件,参考一下这个百度百科教程:

安装完毕后重启 idea,lombok 注解使用就不会再报错了~

3. 集成 mybatis plus

步骤 1:

首先我们来看下 mybatis plus 的官网并且找到整合包:mp.baomidou.com/guide/insta…

官网中提示 springboot 的集成包:

<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-boot-starter</artifactId>
    <version>3.1.0</version>
</dependency>

把 mybatis plus 导入 pom 中。然后在 application.yml 中写入我们的数据源链接信息:

# DataSource Config
spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/third-homework?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC
    username: root
    password: admin
mybatis-plus:
  mapper-locations: classpath*:/mapper/**Mapper.xml

好了,我们的 mybatis plus 已经集成成功。

步骤 2:

我们借用官网给我们提供的代码生成工具:mp.baomidou.com/guide/gener…

注意 MyBatis-Plus 从 3.0.3 之后移除了代码生成器与模板引擎的默认依赖,需要手动添加相关依赖:

<!--代码生成器-->
<dependency>
    <groupId>com.baomidou</groupId>
    <artifactId>mybatis-plus-generator</artifactId>
    <version>3.1.0</version>
</dependency>

前面我们已经自动引入了 freemaker 的集成包,所以这里不需要再重复引入 freemaker 的引擎依赖。接着就是修改我们的代码生成器的相关配置,具体修改如下:

// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
package com.example;
import com.baomidou.mybatisplus.core.exceptions.MybatisPlusException;
import com.baomidou.mybatisplus.core.toolkit.StringPool;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.generator.AutoGenerator;
import com.baomidou.mybatisplus.generator.InjectionConfig;
import com.baomidou.mybatisplus.generator.config.*;
import com.baomidou.mybatisplus.generator.config.po.TableInfo;
import com.baomidou.mybatisplus.generator.config.rules.NamingStrategy;
import com.baomidou.mybatisplus.generator.engine.FreemarkerTemplateEngine;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
// 演示例子,执行 main 方法控制台输入模块表名回车自动生成对应项目目录中
public class CodeGenerator {
    /**
     * <p>
     * 读取控制台内容
     * </p>
     */
    public static String scanner(String tip) {
        Scanner scanner = new Scanner(System.in);
        StringBuilder help = new StringBuilder();
        help.append("请输入" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("请输入正确的" + tip + "!");
    }
    public static void main(String[] args) {
        // 代码生成器
        AutoGenerator mpg = new AutoGenerator();
        // 全局配置
        GlobalConfig gc = new GlobalConfig();
        String projectPath = System.getProperty("user.dir");
        gc.setOutputDir(projectPath + "/src/main/java");
//        gc.setOutputDir("D:\\test");
        gc.setAuthor("公众号:java思维导图");
        gc.setOpen(false);
        // gc.setSwagger2(true); 实体属性 Swagger2 注解
        gc.setServiceName("%sService");
        mpg.setGlobalConfig(gc);
        // 数据源配置
        DataSourceConfig dsc = new DataSourceConfig();
        dsc.setUrl("jdbc:mysql://localhost:3306/third-homework?useUnicode=true&useSSL=false&characterEncoding=utf8&serverTimezone=UTC");
        // dsc.setSchemaName("public");
        dsc.setDriverName("com.mysql.cj.jdbc.Driver");
        dsc.setUsername("root");
        dsc.setPassword("admin");
        mpg.setDataSource(dsc);
        // 包配置
        PackageConfig pc = new PackageConfig();
        pc.setModuleName(null);
        pc.setParent("com.example");
        mpg.setPackageInfo(pc);
        // 自定义配置
        InjectionConfig cfg = new InjectionConfig() {
            @Override
            public void initMap() {
                // to do nothing
            }
        };
        // 如果模板引擎是 freemarker
        String templatePath = "/templates/mapper.xml.ftl";
        // 如果模板引擎是 velocity
        // String templatePath = "/templates/mapper.xml.vm";
        // 自定义输出配置
        List<FileOutConfig> focList = new ArrayList<>();
        // 自定义配置会被优先输出
        focList.add(new FileOutConfig(templatePath) {
            @Override
            public String outputFile(TableInfo tableInfo) {
                // 自定义输出文件名 , 如果你 Entity 设置了前后缀、此处注意 xml 的名称会跟着发生变化!!
                return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML;
            }
        });
        cfg.setFileOutConfigList(focList);
        mpg.setCfg(cfg);
        // 配置模板
        TemplateConfig templateConfig = new TemplateConfig();
        // 配置自定义输出模板
        //指定自定义模板路径,注意不要带上.ftl/.vm, 会根据使用的模板引擎自动识别
        // templateConfig.setEntity("templates/entity2.java");
        // templateConfig.setService();
        // templateConfig.setController();
        templateConfig.setXml(null);
        mpg.setTemplate(templateConfig);
        // 策略配置
        StrategyConfig strategy = new StrategyConfig();
        strategy.setNaming(NamingStrategy.underline_to_camel);
        strategy.setColumnNaming(NamingStrategy.underline_to_camel);
        strategy.setSuperEntityClass("com.example.entity.BaseEntity");
        strategy.setEntityLombokModel(true);
        strategy.setRestControllerStyle(true);
        strategy.setSuperControllerClass("com.example.controller.BaseController");
        strategy.setInclude(scanner("表名,多个英文逗号分割").split(","));
        strategy.setSuperEntityColumns("id", "created", "modified", "status");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

}

注意安装配置来生成 BaseEntity、BaseController、还有包路径相关等东西。

BaseEntity:

@Data
public class BaseEntity implements Serializable {
    private static final long serialVersionUID = 1L;
    private Long id;
    private Date created;
    private Date modified;
}

BaseController:

public class BaseController {
    @Autowired
    HttpServletRequest req;
}

代码生成之后,看到 resource/mapper 这里,我们把这个 null 去掉。

修改之后结果:

到这里还没完成,注意一下:还需要配置 @MapperScan("com.example.mapper") 注解。说明 mapper 的扫描包。

接下来,我们去写一个小小测试,测试一下 mybatis plus 有没集成成功,能否查到数据了:

@RunWith(SpringRunner.class)
@SpringBootTest
public class ThirdHomeworkApplicationTests {
    @Autowired
    UserService userService;
    @Test
    public void contextLoads() {
        User user = userService.getById(1L);
        System.out.println(user.toString());
    }
}

test 之后的结果能够查出数据。注意在 mysql 中添加一条 id 为 1 的数据哈。

4. 集成 freemaker

前面我们已经自动集成了 freemaker 的依赖包,现在我们只需要一些简单配置,其实都不需要配置了:可以看到,我们再写配置的时候 springboot 已经帮我们完成了很多默认配置,修改自己需要修改的就行了。我这里其实不需要修改,后面需要我们再调整。

spring: 
  freemarker:
    cache: false    

然后我们现在去定义一下 freemaker 的模板。不熟悉 freemaker 标签的同学可以先去熟悉一下:

首先我们定义个全局 layout(宏),用于同一所有的页面。

  • templates/inc/layout.ftl
<#-- Layout -->
<#macro layout title>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta >
    <!--[if IE]>
    <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'/>
    <![endif]-->
    <title>${title?default('java思维导图')}</title>
</head>
<body>
<#nested>
</body>
</html>
</#macro>

上面我们用了几个标签,下面我简单讲解一下:

  • <#macro layout title> 定义一个宏(模板),名字是 loyout,title 是参数

  • <#nested> 表示在引入 loyout 这个宏的地方,标签内容的所有内容都会替换到这个标签中。

比如:

  • 首页 templates/index.ftl
<#include "/inc/layout.ftl"/>
<@layout "首页">
  hello world !!
</@layout>

得到的内容其实是:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta >
    <!--[if IE]>
    <meta http-equiv='X-UA-Compatible' content='IE=edge,chrome=1'/>
    <![endif]-->
    <title>首页</title>
</head>
<body>
 hello world !!
</body>
</html>

上面我们定义了一个 layout 宏,这要的好处是一些 css、js 文件我们直接放到 loyout 中,然后具体的页面我们直接 include,然后在标签 <@layout> 内写内容即可。ok,让我们写一个 IndexController 来跳到这个首页。

@Controller
public class IndexController extends BaseController {
    @RequestMapping({"", "/", "/index"})
    public String index () {
        return "index";
    }
}

渲染之后的效果如下:

好了,freemaker 可以正常显示页面,现在我们去把我们的博客主题集成进来,我们使用的是 layui 官方提供的社区模板

先下载下来,解压之后得到:

用 idea 打开 index.html,看下 div 的层次关系,可以得出以下:

ok,知道了 div 的层次之后,我们来一一分开来填入内容,该弄成模板的地方就弄成模板,比如头,尾,侧边栏等。我们先把原来的 index.html 页面的层次分开,分为 header.ftl、header-panel.ftl、footer.ftl、right.ftl。然后在 layout.ftl 中引入我们的 js、css 文件。得到的结果如下:

  • templates/inc/layout.ftl

页面分好之后,得到的打开 http://localhost:8080,效果如下:

**注意:**页面中我用到了一个 ${base} 的参数,我是在项目启动时候就初始化的一个项目路径参数,在 com.example.config.ContextStartup。大家注意一下。

servletContext.setAttribute("base", servletContext.getContextPath());

结束语

好啦,今天的框架先搭建到这里了哈,后续还有 10 多篇逐渐发布出来,已经学好了哈。从 0 到 1 搭建一个完整的高可用 Springboot 博客项目,最值得学习的 Springboot 博客项目。

项目地址:github.com/MarkerHub/e…

eblog 项目视频:www.bilibili.com/video/BV1ri…

写项目写文章都不易,别忘了给个 Star 哈,感谢支持!

(完)

MarkerHub 文章索引:

github.com/MarkerHub/J…