springboot中thymeleaf实现新闻页面静态化

整体结构:
在这里插入图片描述

1、实体类

package com.hdit.domain;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;

import java.util.Date;

/**
 * @基本功能:
 * @ClassName: News
 * @Description: TODO
 * @Author: lijiaming
 * @Date: 2021/3/17 15:43
 * @Version 1.0
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class News {
    
    
    private int id;
    private String newsId;
    private String newsTitle;
    private String newsContent;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date    newsDate;
}

2、thymeleaf模板引擎(TemplateEngine)实现数据与模板组合。

package com.hdit.util;

import com.hdit.domain.News;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import java.io.FileWriter;
import java.io.IOException;

/**
 * @author Administrator
 * @version v1.0
 * @className PageStaticUtil
 * @Date 2021/3/17
 */
@Component
public class PageStaticUtil {
    
    

    @Autowired
    private TemplateEngine  templateEngine;

    public  void  toHTML(News news){
    
    
//      thymeleaf上下文
        Context   context=new Context();
//        设置数据
        context.setVariable("news",news);

//        输出
        FileWriter   out=null;
        try {
    
    
            out=new FileWriter("C:\\Users\\ljm\\Desktop\\news\\"+news.getNewsId()+".html");
            templateEngine.process("news.html",context,out);
        }catch (Exception  e){
    
    

        }finally {
    
    
            try {
    
    
                out.close();
            } catch (IOException e) {
    
    
                e.printStackTrace();
            }
        }

    }

}

3、配置将生成的组合后的html文件分别存放在服务器下和本地。

package com.hdit.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

/**
 * @author Administrator
 * @version v1.0
 * @className PageStaticPathConfig
 * @Date 2021/3/17
 */
@Configuration
public class PageStaticPathConfig implements WebMvcConfigurer{
    
    
        @Override
        public void addResourceHandlers(ResourceHandlerRegistry registry) {
    
    
            registry.addResourceHandler("/news/**").addResourceLocations("file:C:/Users/ljm/Desktop/news/");
        }
}

4、controller层

package com.hdit.controller;

import com.hdit.domain.News;
import com.hdit.service.NewService;
import com.hdit.util.PageStaticUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.List;
import java.util.UUID;

/**
 * @基本功能:
 * @ClassName: NewsController
 * @Description: TODO
 * @Author: lijiaming
 * @Date: 2021/3/17 15:43
 * @Version 1.0
 */
@Controller
public class NewsController {
    
    
    @Autowired
    private PageStaticUtil pageStaticUtil;
    @Autowired
    private NewService newService;

    @PostMapping("/addNews")
    public String addNews(News news){
    
    
        System.out.println("添加新闻!!!");
        news.setNewsId(UUID.randomUUID().toString());
        int i = newService.addNews(news);
        System.out.println(news);
        pageStaticUtil.toHTML(news);
        return "addNews.html";
    }
    @GetMapping("/findAllNews")
    public String findAllNews(ModelMap map){
    
    
        System.out.println("查找所有新闻!!!");
        List<News> news_list =  newService.findAllNews();
        System.out.println(news_list);
        map.addAttribute("news_list",news_list);
        return "showNews.html";
    }
}

5、service层

service.impl接口类

package com.hdit.service;

import com.hdit.domain.News;

import java.util.List;


public interface NewService {
    
    
    public int  addNews(News news);
    public List<News> findAllNews();
 }

service.impl实现类

package com.hdit.service.impl;

import com.hdit.domain.News;
import com.hdit.mapper.NewsMapper;
import com.hdit.service.NewService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @基本功能:
 * @ClassName: NewsServiceImpl
 * @Description: TODO
 * @Author: lijiaming
 * @Date: 2021/3/17 15:44
 * @Version 1.0
 */
@Service
public class NewsServiceImpl implements NewService {
    
    
    @Autowired
    private NewsMapper newsMapper;
    @Override
    public int addNews(News news) {
    
    
        Map map = new HashMap();
        map.put("newsId",news.getNewsId());
        map.put("newsTitle",news.getNewsTitle());
        map.put("newsContent",news.getNewsContent());
        map.put("newsDate",news.getNewsDate());
        return newsMapper.addNews(map);
    }
    @Override
    public List<News> findAllNews() {
    
    
        return newsMapper.findAllNews();
    }
}

6、mapper层

package com.hdit.mapper;

import com.hdit.domain.News;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Map;


@Repository
public interface NewsMapper {
    
    
    @Insert("insert into news values(null,#{newsId},#{newsTitle},#{newsContent},#{newsDate})")
    public int  addNews(Map map);
    @Select("select * from news")
    public List<News> findAllNews();
}

7、springboot启动类

package com.hdit;

import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;

@SpringBootApplication
@MapperScan("/com.hdit.mapper") //扫描mapper
public class DemoApplication {
    
    
    public static void main(String[] args) {
    
    
        SpringApplication.run(DemoApplication.class, args);
    }

}

8、html模板

动态生成html页面模板:news.html

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    <title>新闻内容</title>
</head>
<body>
<h1>新闻内容</h1>
<p th:text="${news.newsId}"></p>
<p th:text="${news.newsTitle}"></p>
<p th:text="${news.newsContent}"></p>
<p th:text="${news.newsDate}"></p>
</body>
</html>

查看所有新闻信息模板:showNews.html

<!DOCTYPE html>
<html lang="en"  xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="utf-8"/>
    <title>新闻内容</title>
</head>
<body>
<h1>新闻内容</h1>
<table border="1" >
    <tr>
        <th>序号</th>
        <th>id</th>
        <th>新闻标题</th>
        <th>新闻内容</th>
        <th>时间</th>
        <th>查看详情信息</th>
    </tr>
    <tr th:each="news:${news_list}">
        <td th:text="${news.id}"></td>
        <td th:text="${news.newsId}"></td>
        <td th:text="${news.newsTitle}"></td>
        <td th:text="${news.newsContent}"></td>
        <td th:text="${news.newsDate}"></td>
        <td ><a th:href="'/SpringBootNews/news/'+${news.newsId}+'.html'">查看</a></td>
    </tr>
</table>
</body>
</html>

9、添加新闻信息页面:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="utf-8"/>
    <title>添加新闻</title>
</head>
<body>
<h1>添加新闻</h1>
<form action="/SpringBootNews/addNews" method="post">
    新闻标题:<input type="text" name="newsTitle"/><br>
    新闻内容:<input type="text" name="newsContent"/><br>
    时 间:<input type="date" name="newsDate"/><br>
    <input type="submit" value="添加">
</form>
<form action="/SpringBootNews/findAllNews" method="get">
    <input type="submit" value="查看新闻"/>
</form>
</body>
</html>

10、application.yml配置文件:

server:
  port: 8083
  servlet:
    context-path: /SpringBootNews
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC
    driver-class-name: com.mysql.cj.jdbc.Driver

11、pom.xml依赖文件:

       <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.1.4</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </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>

猜你喜欢

转载自blog.csdn.net/weixin_43605266/article/details/114951473