Public account: MarkerHub (pay attention to get more project resources)

Eblog codebase: github.com/markerhub/e…

Eblog project video: www.bilibili.com/video/BV1ri…


Development Document Catalog:

(Eblog) 1. Set up the project architecture and initialized the home page

(EBLOG) 2. Integrate Redis and project elegant exception handling and return result encapsulation

(eblog) 3, using Redis zset ordered set to achieve a hot feature of the week

(EBLOG) 4, customize Freemaker label to achieve blog homepage data filling

(Eblog) 5, blog classification filling, login registration logic

(EBLOG) 6. Set up blog publishing collection and user center

(eblog) 7, message asynchronous notification, details adjustment

8. Blog search engine development and background selection

(Eblog) 9. Instant group chat development, chat history, etc


Front and back end separation project vueblog please click here: super detailed! 4 hours to develop a SpringBoot+ Vue front and back separated blog project!!


Directory:

1. Eblog is the most valuable Springboot open source blog project on Github!


Build the basic structure of the project

In the following process, we use IDEA as the development tool to create a Springboot project.

Development environment:

  • idea

  • JDK 1.8

  • Maven 3.3.9

  • Mysql 5.7

1. Create a SpringBoot project

Open idea, create a new project, and select Spring Initializr. Fill in the project basic information as follows:

Next, we choose the framework or middleware we need to integrate. At this stage of development, we choose the following dependencies:

  • web

  • Lombok

  • Devtools

  • freemaker

  • Mysql

  • Redis

Of course, we need to complete some configuration, such as our mysql, Redis need to configure connection information, generally speaking, Springboot has helped us complete a lot of default configuration, as long as the default configuration, we do not need to modify or write configuration, such as Freemaker ~

After selecting, IDEA will automatically add the dependency. Open the project as follows:

The following dependency packages are available for 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>

Copy the code

Now, let’s go through the framework integration step by step.

2. Integrated lombok

We just imported lombok’s dependencies automatically

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

Copy the code

Lombok plugin is not installed on your idea yet.

  • IntelliJ IDEA lombok plug-in installation and use (jingyan.baidu.com/article/0a5…

After the installation is complete, restart IDEA and lombok annotations will no longer report errors

3. Integrate MyBatis Plus

Step 1:

First of all, we’ll look at mybatis plus website and find integration package: mp.baomidou.com/guide/insta…

The springBoot integration package is shown on the official website:

< the dependency > < groupId > com. Baomidou < / groupId > < artifactId > mybatis - plus - the boot - starter < / artifactId > < version > 3.1.0 < / version >  </dependency>Copy the code

Import Mybatis Plus into poM. We then write our data source link information in application.yml:

# DataSource Configspring: 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

Copy the code

Ok, our Mybatis Plus has been integrated successfully.

Step 2:

We use website provides us with a code generation tool: mp.baomidou.com/guide/gener…

Note that MyBatis-Plus removed the default dependencies on code generators and template engines from 3.0.3, requiring manual addition of dependencies:

<! <dependency> <groupId>com.baomidou</groupId> <artifactId>mybatis-plus-generator</artifactId> The < version > 3.1.0 < / version > < / dependency >Copy the code

We already automatically introduced freemaker’s integration package earlier, so there’s no need to repeat the introduction of Freemaker’s engine dependencies here. The next step is to modify the configuration of our code generator as follows:

// Execute the main method, enter the module table name, and press Enter to automatically generate the corresponding project directory 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; // A sample, Public class CodeGenerator {/** * <p> * </p> */ public static String scanner(String tip) { Scanner scanner = new Scanner(System.in); StringBuilderhelp = new StringBuilder();
        help.append("Please enter" + tip + ":");
        System.out.println(help.toString());
        if (scanner.hasNext()) {
            String ipt = scanner.next();
            if (StringUtils.isNotEmpty(ipt)) {
                return ipt;
            }
        }
        throw new MybatisPlusException("Please enter the correct one" + 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(Public id: Java Mind Map);
        gc.setOpen(false);
        // gc.setSwagger2(true); Entity attribute Swagger2 annotation 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 = newInjectionConfig() {
            @Override
            public void initMap() {
                // to donothing } }; If the template engine is freemarker String templatePath ="/templates/mapper.xml.ftl"; If the template engine is velocity // String templatePath ="/templates/mapper.xml.vm"; List<FileOutConfig> focList = new ArrayList<>(); Add (new FileOutConfig(templatePath) {@override public String outputFile(TableInfo TableInfo) { // Customize the output file name. If your Entity has a prefix or suffix, note that the XML name will change accordingly!!return projectPath + "/src/main/resources/mapper/" + pc.getModuleName()
                        + "/" + tableInfo.getEntityName() + "Mapper"+ StringPool.DOT_XML; }}); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // TemplateConfig TemplateConfig = new TemplateConfig(); // Configure a custom output template. // Specify a custom template path without. FTL /. Vm, which is automatically identified according to the template engine used."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("Table name, separated by multiple Commas").split(","));
        strategy.setSuperEntityColumns("id"."created"."modified"."status");
        strategy.setControllerMappingHyphenStyle(true);
        strategy.setTablePrefix(pc.getModuleName() + "_");
        mpg.setStrategy(strategy);
        mpg.setTemplateEngine(new FreemarkerTemplateEngine());
        mpg.execute();
    }

Copy the code

}

Note the setup configuration to generate BaseEntity, BaseController, package path, etc.

BaseEntity:

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

Copy the code

BaseController:

public class BaseController {
    @Autowired
    HttpServletRequest req;
}

Copy the code

So after the code is generated, if I see resource/mapper here, LET’s get rid of this null.

Results after modification:

I’m not done here, but note that the @mapperscan (“com.example.mapper”) annotation also needs to be configured. Note Scan package of mapper.

Next, we will write a small test to test whether the integration of Mybatis Plus is successful and whether the data can be checked:

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

The data can be found after the test result. Select * from mysql where id = 1;

4. Integration freemaker

Now that we’ve automatically integrated freemaker’s dependencies, we just need some simple configuration, but we don’t really need any configuration: SpringBoot has already done a lot of default configuration for us when we write the configuration, so just change what we need to change. I actually don’t need to modify here, we need to adjust later.

spring: 
  freemarker:
    cache: false    

Copy the code

And now we’re going to define freemaker’s template. For those unfamiliar with the Freemaker label, check it out:

First we define a global layout for all pages.

  • 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 mind map ')}</title>
</head>
<body>
<#nested>
</body>
</html>
</#macro>

Copy the code

We used a few tags above, but I’ll explain them briefly:

  • <#macro Layout title> defines a macro (template) with the name loyout and the title as the parameter

  • <#nested> means that where the macro loyout is introduced, all the contents of the tag content are replaced in the tag.

Such as:

  • Home page templates/index. FTL
<#include "/inc/layout.ftl"/>
<@layout "Home page">
  hello world !!
</@layout>

Copy the code

What you get is this:

<! 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> </head> <body> Hello world!! </body> </html>Copy the code

We have defined a layout macro, this advantage is that some CSS, JS files we put directly in loyout, and then specific pages we directly include, and then write content in the tag <@layout>. Ok, let’s write an IndexController to jump to the front page.

@Controller
public class IndexController extends BaseController {
    @RequestMapping({""."/"."/index"})
    public String index () {
        return "index"; }}Copy the code

The render looks like this:

Ok, Freemaker will display the page normally, now let’s go to integrate our blog theme, we are using layui official community template

  • Fly.layui.com/store/FlyTe…

Download it first and unzip it to get:

Open index. HTML with idea and look at the hierarchical relationship of div, you can get the following:

Ok, now that we know the div level, let’s go ahead and fill in the content separately. Make templates where you need them, like headers, tails, sidebars, etc. FTL, header-panel. FTL, footer. FTL, right.ftl. Then we introduce our JS and CSS files in layout. FTL. The results are as follows:

  • templates/inc/layout.ftl

After dividing the page, open http://localhost:8080 and the result is as follows:

Note: * * * * in the page I used a ${base} parameter, when I am in the project to start the initialization of a project path parameters, example. Config. ContextStartup. In com. Let me have your attention.

servletContext.setAttribute("base", servletContext.getContextPath());
Copy the code

conclusion

Well, today’s framework has been built here, and there are more than 10 articles to be released gradually. I have learned it well. Build a complete high availability Springboot blog project from 0 to 1, the most worth learning Springboot blog project.

Project address: github.com/MarkerHub/e…

Eblog project video: www.bilibili.com/video/BV1ri…

Writing projects and articles is not easy, don’t forget to give a Star ha, thank you for your support!

(after)

MarkerHub Article Index:

Github.com/MarkerHub/J…