spring boot 搭建博客

1、maven:

maven是项目构建和管理工具
它可以自动下载jar包
本地仓库
第三方仓库: 加速下载,国立公司(阿里等)
中央仓库:外网,国外的公司
配置指南:
打开 maven 的配置文件( windows 在 maven 安装目录的 conf/settings.xml ),在标签中添加 mirror 子节点:

<mirror>
  <id>aliyunmaven</id>
  <mirrorOf>*</mirrorOf>
  <name>阿里云公共仓库</name>
  <url>https://maven.aliyun.com/repository/public</url>
</mirror>

在系统变量中新建 变量名 MAVEN_HOME 变量值: C:\maven (根具自己的maven路径)
在系统变量中的path下创建变量为 %MAVEN_HOME%\bin
测试maven是否安装成功 cmd中 输入 mvn -version

2、idea

第一次使用时
配置jdk:configure -> structure for new project -> 选则本地jdk
配置maven: configure -> setting ->(Build ,Execution) ->Build Tools->mave
选择本地的maven: C:\maven

idea常用快捷键
Alt+ enter : 自动导包
Ctrl + shift + N :模糊匹配查找文件
Ctrl + / 和 Ctrl + shift + / 单行注释或多行注释
Ctrl + B : 快速 打开光标处的类
Tab 或 shift Tab: 缩进

3、spirng boot框架搭建

3.1构建项目的两种方式

1:基于本地服务器进行项目搭建 (有时候会失败)
2:基于官方网站进行项目搭建 https://strat.spring.io 进行项目的创建

3.2创建spring boot项目

改group组织机构 名称,项目名称
勾选spring web,模板thymeleaf,Spring Date JPA,MySQL Driver

在src/resources下将application.properties改名为application.yml
application.yml的配置为

spring:
  thymeleaf:
    mode: HTML
  profiles:
    active: pro

新建application-dev.yml (开发环境)

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456

  jpa:
    hibernate:
      ddl-auto: update
    show-sql: true

logging:
  level:
    root: info
    com.jlf: debug
  file:
    name: log/blog-dev.log

新建application-pro.yml (生产环境)

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://localhost:3306/blog?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
    username: root
    password: 123456
  jpa:
    hibernate:
      ddl-auto: none
    show-sql: true

logging:
  level:
    root: warn
    com.jlf: info
  file:
    name: log/blog-pro.log

server:
  port: 8081

源码

3.3 异常处理
3.3.1定义错误页面

404
500
error
在templates下创建 index.html
在templates下创建文件夹 error,
在error文件下创建404.html,500.html,error.html
在java的com.jlf 下创建 web的package,再包下创建IndexContro.java文件

package com.jlf.blog1.web;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexContro {
    @GetMapping("/")
    public String index(){
        int i = 9/0 ;
        return "index";
    }
}

测试页面是否成功

3.3.2定义拦截器

在java的com.jlf 下创建 handle的package,再包下创建ControllerExceptionHandler.java文件

package com.jlf.blog1.handle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.AnnotationUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;

@ControllerAdvice
public class ControllerExceptionHandler {
   private final Logger logger = LoggerFactory.getLogger(this.getClass());

   @ExceptionHandler(Exception.class)
   public ModelAndView exceptionHander(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 mv = new ModelAndView();
       mv.addObject("url",request.getRequestURL());
       mv.addObject("exception", e);
       mv.setViewName("error/error");
       return mv;
   }
}

测试拦截器是否成功
在error.html中,增加报错日志信息,报错信息可在网页中查看

<div>
       <div th:utext="'&lt;!--'" 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="'--&gt;'" th:remove="tag"></div>
   </div>
3.3.3修改

修改 IndexContro.java

package com.jlf.blog1.web;

import com.jlf.blog1.NotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class IndexContro {
   @GetMapping("/")
   public String index(){
       // int i = 9/0 ;
       String blog = null;
       if (blog == null) {
           throw new NotFoundException("博客不存在");
       }
       return "index";
   }
}

在blog1下新增加 NotFoundException.java

package com.jlf.blog1;

import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(HttpStatus.NOT_FOUND)
public class NotFoundException extends RuntimeException{
   public NotFoundException (){
   }

   public NotFoundException (String message){
       super(message);
   }

   public NotFoundException (String message,Throwable cause){
       super(message, cause);
   }

}
3.4 日志
3.4.1 日志流程

在 java的com.jlf 下创建 名为aspect的package,再在包下创建LogAspect.java文件

package com.jlf.blog1.aspect;

import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class LogAspect {

    private final Logger logger= LoggerFactory.getLogger(this.getClass());
    @Pointcut("execution(* com.jlf.blog1.web.*.*(..))")
    public void log(){}

    @Before("log()")
    public void doBefore(){
        logger.info("-------doBefore--------");
    }

    @After("log()")
    public void doAfter() {
        logger.info("--------doAfter--------");
    }

    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterRuturn(Object result) {
        logger.info("Result : {}" + result);
    }
}

修改IndexContro.java文件

package com.jlf.blog1.web;

import com.jlf.blog1.NotFoundException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

@Controller
public class IndexContro {
    @GetMapping("/{id}/{name}")
    public String index(@PathVariable Integer id,@PathVariable String name){
        // int i = 9/0 ;
//        String blog = null;
//        if (blog == null) {
//            throw new NotFoundException("博客不存在");
//        }
        System.out.println("---index---");
        return "index";
    }
}

在url中输入 http://127.0.0.1:8080/3/abc
测试是否成功

3.4.2 增加日志

修改LogAspect.java

package com.jlf.blog1.aspect;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;

@Aspect
@Component
public class LogAspect {

    // private final Logger logger = (Logger) LoggerFactory.getLogger(this.getClass());
    // private final Logger logger = (Logger) LoggerFactory.getLogger(this.getClass());
    private final Logger logger= LoggerFactory.getLogger(this.getClass());
    @Pointcut("execution(* com.jlf.blog1.web.*.*(..))")
    public void log(){}

    @Before("log()")
    public void doBefore(JoinPoint joinPoint){
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        String url = request.getRequestURL().toString();
        String ip = request.getRemoteAddr();
        String classMethod = joinPoint.getSignature().getDeclaringTypeName() + "." + joinPoint.getSignature().getName();
        Object[] args = joinPoint.getArgs();
        RequestLog requestLog = new RequestLog(url, ip, classMethod, args);
        logger.info("Request :{}",requestLog);
    }

    @After("log()")
    public void doAfter() {
        //logger.info("--------doAfter--------");
    }

    @AfterReturning(returning = "result",pointcut = "log()")
    public void doAfterRuturn(Object result) {
        logger.info("Result : {}" + result);
    }

    private class RequestLog{
        private String url;
        private String ip;
        private String classMethod;
        private Object[] args;

        public RequestLog(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 "{" +
                    "url='" + url + '\'' +
                    ", ip='" + ip + '\'' +
                    ", classMethod='" + classMethod + '\'' +
                    ", args=" + Arrays.toString(args) +
                    '}';
        }
    }

}
3.4 页面处理
3.4.1导入静态页面

导入需要修改 css,图片的引入地址

3.4.2thymeleaf布局

css: th:href="@{/css/me.css}"
图片:th:src="@{/image/22.gif}"
templates下新增_fargments.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:fragment="head(title)">
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title th:replace="${title}">博客详情</title>
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.css">
  <link rel="stylesheet" href="../static/css/typo.css" th:href="@{/css/typo.css}">
  <link rel="stylesheet" href="../static/css/animate.css" th:href="@{/css/animate.css}">
  <link rel="stylesheet" href="../static/lib/prism/prism.css" th:href="@{/lib/prism/prism.css}">
  <link rel="stylesheet" href="../static/lib/tocbot/tocbot.css" th:href="@{/lib/tocbot/tocbot.css}">
  <link rel="stylesheet" href="../static/css/me.css" th:href="@{/css/me.css}">
</head>
<body>
  <nav th:fragment="menu(n)" class="ui inverted attached segment m-padded-tb-mini">

      <div class="ui container">
          <div class="ui inverted secondary stackable menu">
              <h2 class="ui teal header item">Blog</h2>
              <a href="#" class="m-item item white m-moblle-hide" th:classappend="${n==1} ? 'active'"><i class=" home  icon"></i> 首页</a>
              <a href="#" class="m-item item white m-moblle-hide" th:classappend="${n==2} ? 'active'"><i class=" idea  icon"></i> 分类</a>
              <a href="#" class="m-item item white m-moblle-hide" th:classappend="${n==3} ? 'active'"><i class=" tags  icon"></i> 标签</a>
              <a href="#" class="m-item item white m-moblle-hide" th:classappend="${n==4} ? 'active'"><i class=" clone  icon"></i> 归档</a>
              <a href="#" class="m-item item white m-moblle-hide" th:classappend="${n==5} ? 'active'"><i class=" info  icon"></i> 关于我</a>
              <div class="right m-item item m-moblle-hide">
                  <div class="ui icon  input inverted transparent">
                      <input type="text" placeholder="Search.....">
                      <i class="search icon"></i>
                  </div>
              </div>
          </div>
      </div>
      <a href="#" class="ui menu toggle black button m-right-top m-moblile-show">
          <i class="sidebar icon"></i>
      </a>
  </nav>
<!-- ---------------------- -->
  <footer th:fragment="footer" class="ui inverted  vertical segment m-padded-tb-massive">     <!--11 vertical -->   <!--16 把框相框变大 自定义css  m-padded-tb-massive-->
      <div class="ui center aligned container">          <!-- 13 center aligned 居中文字-->
          <div class="ui grid stackable inverted divided">                      <!--11 grid 默认把文件分成16单位  现在分成3单位*3 加7单位  divided 添加线条 还要继续反色-->
              <div class="three wide column ">
                  <div class="ui inverted link list">
                      <div class="item">
                          <img src="../static/images/me.jpg" th:src="@{/images/me.jpg}" class="ui rounded image" alt="" style="width: 10em;">    <!--12 rounded圆角 width调节大小-->
                      </div>
                  </div>
              </div>
              <div class="three wide column">
                  <h4 class="ui inverted header">最新博客</h4>    <!-- 13 添加文字-->
                  <div class="ui inverted link list">
                      <a href="#" class="item">用户故事(user stroy)</a>        <!-- 14 要写三行内容-->
                      <a href="#" class="item">用户故事(user stroy)</a>
                      <a href="#" class="item">用户故事(user stroy)</a>
                  </div>
              </div>
              <div class="three wide column">
                  <h4 class="ui inverted header">联系我</h4>                <!-- 15 复制1份在另一个 three wide column中 -->
                  <div class="ui inverted link list">
                      <a href="#" class="item">Email: 2280606899@qq.com</a>
                      <a href="#" class="item">用户故事(user stroy)</a>
                      <a href="#" class="item">用户故事(user stroy)</a>
                  </div>
              </div>
              <div class="seven wide column">
                  <h4 class="ui inverted header">最新博客</h4>
                  <p class="m-opacity-mini "> 博客是一个面向开发者的知识分享社区。自创建以来,博客一直致力并专注于为开发者打造一个纯净的技术交流社区</p>
              </div>
          </div>
          <div class="ui inverted section divider "></div>                   <!--17 添加分隔线 -->
          <p class="m-text-spaced m-opacity-tiny"> Copyright@2020-2025 jianglf Design by jianglf</p>     <!-- 18 自定义一些样式 透明度等-->
      </div>
  </footer>
<th:block th:fragment="script">
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2/dist/jquery.min.js"></script>  <!--2.引入jqurey-->
  <script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script> <!-- 1.引入cdn-->
  <script src="./static/lib/prism/prism.js" th:src="@{/lib/prism/prism.js}"></script>
  <script src="./static/lib/tocbot/tocbot.min.js" th:src="@{/lib/tocbot/tocbot.min.js}"></script>
  <script>
      $('.menu.toggle').click(function(){
          $('.m-item').toggleClass('m-mobile-hide');
      });

      $('#payButton').popup({
          popup : $('.payQR.popup'),
          on : 'click',
          position:'bottom center'
      });

      tocbot.init({
          // Where to render the table of contents.
          tocSelector: '.js-toc',
          // Where to grab the headings to build the table of contents.
          contentSelector: '.js-toc-content',
          // Which headings to grab inside of the contentSelector element.
          headingSelector: 'h1, h2, h3',
          // For headings inside relative or absolute positioned containers within content.
          hasInnerContainers: true,
      });

      $('.toc.button').popup({
          popup : $('.toc-container.popup'),
          on : 'click',
          position:'left center'
      });
  </script>
</th:block>
</body>
</html>
3.5 设计表结构

在com.jlf.blog1新建po包,创建Blog.java,comment.java,tag.java,type.java,user.java

3.5.1blog.java
package com.jlf.blog1.po;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Entity
@Table(name = "t_blog")
public class Blog {

    @Id
    @GeneratedValue
    private Long id;
    private String title;
    private String content;
    private String firstPicture;
    private String flag;  // 标记
    private Integer views; // 浏览次数
    private boolean appreciation; // 赞赏次数
    private boolean shareStatement; // 版权开启
    private boolean commentabled; // 评论开启
    private boolean published;
    private boolean recommend; // 推荐
    private Date createTime;
    private Date updateTime;

    @ManyToOne
    private Type type;

    @ManyToMany(cascade = {CascadeType.PERSIST})
    private List<Tag> tags = new ArrayList<>();

    @ManyToOne
    private User user;

    @OneToMany(mappedBy = "blog")
    private List<Comment> comments = new ArrayList<>();

    public Blog(){
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public Type getType() {
        return type;
    }

    public void setType(Type type) {
        this.type = type;
    }

    public String getFirstPicture() {
        return firstPicture;
    }

    public void setFirstPicture(String firstPicture) {
        this.firstPicture = firstPicture;
    }

    public String getFlag() {
        return flag;
    }

    public void setFlag(String flag) {
        this.flag = flag;
    }

    public Integer getViews() {
        return views;
    }

    public void setViews(Integer views) {
        this.views = views;
    }

    public boolean isAppreciation() {
        return appreciation;
    }

    public void setAppreciation(boolean appreciation) {
        this.appreciation = appreciation;
    }

    public boolean isShareStatement() {
        return shareStatement;
    }

    public void setShareStatement(boolean shareStatement) {
        this.shareStatement = shareStatement;
    }

    public boolean isCommentabled() {
        return commentabled;
    }

    public void setCommentabled(boolean commentabled) {
        this.commentabled = commentabled;
    }

    public boolean isPublished() {
        return published;
    }

    public void setPublished(boolean published) {
        this.published = published;
    }

    public boolean isRecommend() {
        return recommend;
    }

    public void setRecommend(boolean recommend) {
        this.recommend = recommend;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public List<Tag> getTags() {
        return tags;
    }

    public void setTags(List<Tag> tags) {
        this.tags = tags;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public List<Comment> getComments() {
        return comments;
    }

    public void setComments(List<Comment> comments) {
        this.comments = comments;
    }

    @Override
    public String toString() {
        return "Blog{" +
                "id=" + id +
                ", title='" + title + '\'' +
                ", content='" + content + '\'' +
                ", firstPicture='" + firstPicture + '\'' +
                ", flag='" + flag + '\'' +
                ", views=" + views +
                ", appreciation=" + appreciation +
                ", shareStatement=" + shareStatement +
                ", commentabled=" + commentabled +
                ", published=" + published +
                ", recommend=" + recommend +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                '}';
    }
}
3.5.2 Comment.java
package com.jlf.blog1.po;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Entity
@Table(name = "t_comment")
public class Comment {

    @Id
    @GeneratedValue
    private Long id;
    private String nickname;
    private String email;
    private String content;
    private String avatar;
    @Temporal(TemporalType.TIMESTAMP)
    private Date createTime;
    @Temporal(TemporalType.TIMESTAMP)
    private Date updateTime;

    @ManyToOne
    private Blog blog;

    @OneToMany(mappedBy = "parentComment")
    private List<Comment> replyComments = new ArrayList<>();

    @ManyToOne
    private Comment parentComment;

    public Comment(){
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getContent() {
        return content;
    }

    public void setContent(String content) {
        this.content = content;
    }

    public String getAvatar() {
        return avatar;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public Blog getBlog() {
        return blog;
    }

    public void setBlog(Blog blog) {
        this.blog = blog;
    }

    public List<Comment> getReplyComments() {
        return replyComments;
    }

    public void setReplyComments(List<Comment> replyComments) {
        this.replyComments = replyComments;
    }

    public Comment getParentComment() {
        return parentComment;
    }

    public void setParentComment(Comment parentComment) {
        this.parentComment = parentComment;
    }

    @Override
    public String toString() {
        return "Comment{" +
                "id=" + id +
                ", nickname='" + nickname + '\'' +
                ", email='" + email + '\'' +
                ", content='" + content + '\'' +
                ", avatar='" + avatar + '\'' +
                ", createTime=" + createTime +
                '}';
    }
}
3.5.3Tag.java
package com.jlf.blog1.po;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "t_tag")
public class Tag {

    @Id
    @GeneratedValue
    private Long id;
    private String name;

    @ManyToMany(mappedBy = "tags")
    private List<Blog> blogs = new ArrayList<>();

    public List<Blog> getBlogs() {
        return blogs;
    }

    public void setBlogs(List<Blog> blogs) {
        this.blogs = blogs;
    }

    public Tag(){
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Tag{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
3.5.4 type.java
package com.jlf.blog1.po;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;

@Entity
@Table(name = "t_type")
public class Type {

    @Id
    @GeneratedValue
    private Long id;
    private String name;

    @OneToMany(mappedBy = "type")
    private List<Blog> blogs = new ArrayList<>();
    public Type() {
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public List<Blog> getBlogs() {
        return blogs;
    }

    public void setBlogs(List<Blog> blogs) {
        this.blogs = blogs;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "Type{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }
}
3.5.5 User.java
package com.jlf.blog1.po;

import javax.persistence.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Entity
@Table(name = "t_user")
public class User {

    @Id
    @GeneratedValue
    private Long id;
    private String nickname;
    private String username;
    private String password;
    private String email;
    private String avatar;
    private Integer type;
    @Temporal(TemporalType.TIMESTAMP)
    private Date CreateTime;
    @Temporal(TemporalType.TIMESTAMP)
    private Date UpdateTime;


    @OneToMany(mappedBy = "user")
    private List<Blog> blogs = new ArrayList<>();

    public User(){
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getAvatar() {
        return avatar;
    }

    public void setAvatar(String avatar) {
        this.avatar = avatar;
    }

    public Integer getType() {
        return type;
    }

    public void setType(Integer type) {
        this.type = type;
    }

    public Date getCreateTime() {
        return CreateTime;
    }

    public void setCreateTime(Date createTime) {
        CreateTime = createTime;
    }

    public Date getUpdateTime() {
        return UpdateTime;
    }

    public void setUpdateTime(Date updateTime) {
        UpdateTime = updateTime;
    }

    public List<Blog> getBlogs() {
        return blogs;
    }

    public void setBlogs(List<Blog> blogs) {
        this.blogs = blogs;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", nickname='" + nickname + '\'' +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", email='" + email + '\'' +
                ", avatar='" + avatar + '\'' +
                ", type=" + type +
                ", CreateTime=" + CreateTime +
                ", UpdateTime=" + UpdateTime +
                '}';
    }
}
3.6 后台登录
3.6.1 构建网页

在template下构建login.html,_fragments.html,index.html

login.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:replace="admin/_fragments :: head(~{::title})">
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>博客管理登录</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
    <link rel="stylesheet" href="../../static/css/me.css">
</head>
<body>
<br>
<br>
<br>
<br><br>
<br><br>
    <div class="m-container m-padded-tb-massive" style="max-width: 30em !important;">
        <div class="ur container">
            <div class="column">
                <h2 class="ui teal image header">

                    <div class="content">
                        管理后台登录
                    </div>
                </h2>
                <form class="ui large form" method="post" action="#" th:action="@{/admin/login}">
                    <div class="ui stacked segment">
                        <div class="field">
                            <div class="ui left icon input">
                                <i class="user icon"></i>
                                <input type="text" name="username" placeholder="用户名">
                            </div>
                        </div>
                        <div class="field">
                            <div class="ui left icon input">
                                <i class="lock icon"></i>
                                <input type="password" name="password" placeholder="密码">
                            </div>
                        </div>
                        <div class="ui fluid large teal submit button">登   录</div>
                    </div>

                    <div class="ui error message"></div>

                </form>


            </div>
        </div>
    </div>

<script src="https://cdn.jsdelivr.net/npm/jquery@3.2/dist/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script>
</body>
</html>

_fragments.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:fragment="head(title)">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title th:replace="${title}">博客详情</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/semantic-ui/2.2.4/semantic.min.css">
    <link rel="stylesheet" href="../static/css/typo.css" th:href="@{/css/typo.css}">
    <link rel="stylesheet" href="../static/css/animate.css" th:href="@{/css/animate.css}">
    <link rel="stylesheet" href="../static/lib/prism/prism.css" th:href="@{/lib/prism/prism.css}">
    <link rel="stylesheet" href="../static/lib/tocbot/tocbot.css" th:href="@{/lib/tocbot/tocbot.css}">
    <link rel="stylesheet" href="../static/css/me.css" th:href="@{/css/me.css}">
</head>
<body>
    <nav th:fragment="menu(n)" class="ui inverted attached segment m-padded-tb-mini m-shadow-small m-shadow-small">

        <div class="ui container">
            <div class="ui inverted secondary stackable menu">
                <h2 class="ui teal header item">管理后台</h2>
                <a href="#" class="m-item item white m-mobile-hide" th:classappend="${n==1} ? 'active'"><i class=" home  icon"></i> 博客</a>
                <a href="#" class="m-item item white m-mobile-hide" th:classappend="${n==2} ? 'active'"><i class=" idea  icon"></i> 分类</a>
                <a href="#" class="m-item item white m-mobile-hide" th:classappend="${n==3} ? 'active'"><i class=" tags  icon"></i> 标签</a>
                <div class="right m-item menu m-mobile-hide">
                    <div class="ui dropdown m-item item">
                        <div class="text">
                            <img class="ui avatar image" src="../../static/images/me.jpg">
                            anonymous
                        </div>
                        <i class="dropdown icon "></i>
                        <div class="menu">
                            <a href="#" class="item">注销</a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <a href="#" class="ui menu toggle black button m-right-top m-moblile-show">
            <i class="sidebar icon"></i>
        </a>
    </nav>


<!-- ---------------------- -->
    <footer th:fragment="footer" class="ui inverted  vertical segment m-padded-tb-massive">     <!--11 vertical -->   <!--16 把框相框变大 自定义css  m-padded-tb-massive-->
        <div class="ui center aligned container">          <!-- 13 center aligned 居中文字-->
            <div class="ui grid stackable inverted divided">                      <!--11 grid 默认把文件分成16单位  现在分成3单位*3 加7单位  divided 添加线条 还要继续反色-->
                <div class="three wide column ">
                    <div class="ui inverted link list">
                        <div class="item">
                            <img src="../static/images/me.jpg" th:src="@{/images/me.jpg}" class="ui rounded image" alt="" style="width: 10em;">    <!--12 rounded圆角 width调节大小-->
                        </div>
                    </div>
                </div>
                <div class="three wide column">
                    <h4 class="ui inverted header">最新博客</h4>    <!-- 13 添加文字-->
                    <div class="ui inverted link list">
                        <a href="#" class="item">用户故事(user stroy)</a>        <!-- 14 要写三行内容-->
                        <a href="#" class="item">用户故事(user stroy)</a>
                        <a href="#" class="item">用户故事(user stroy)</a>
                    </div>
                </div>
                <div class="three wide column">
                    <h4 class="ui inverted header">联系我</h4>                <!-- 15 复制1份在另一个 three wide column中 -->
                    <div class="ui inverted link list">
                        <a href="#" class="item">Email: 2280606899@qq.com</a>
                        <a href="#" class="item">用户故事(user stroy)</a>
                        <a href="#" class="item">用户故事(user stroy)</a>
                    </div>
                </div>
                <div class="seven wide column">
                    <h4 class="ui inverted header">最新博客</h4>
                    <p class="m-opacity-mini "> 博客是一个面向开发者的知识分享社区。自创建以来,博客一直致力并专注于为开发者打造一个纯净的技术交流社区</p>
                </div>
            </div>
            <div class="ui inverted section divider "></div>                   <!--17 添加分隔线 -->
            <p class="m-text-spaced m-opacity-tiny"> Copyright@2020-2025 jianglf Design by jianglf</p>     <!-- 18 自定义一些样式 透明度等-->
        </div>
    </footer>
<th:block th:fragment="script">
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.2/dist/jquery.min.js"></script>  <!--2.引入jqurey-->
    <script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script> <!-- 1.引入cdn-->
    <script src="../static/lib/prism/prism.js" th:src="@{/lib/prism/prism.js}"></script>
    <script src="../static/lib/tocbot/tocbot.min.js" th:src="@{/lib/tocbot/tocbot.min.js}"></script>
    <script>
        $('.menu.toggle').click(function(){
            $('.m-item').toggleClass('m-mobile-hide');
        });


        $('#payButton').popup({
            popup : $('.payQR.popup'),
            on : 'click',
            position:'bottom center'
        });

        tocbot.init({
            // Where to render the table of contents.
            tocSelector: '.js-toc',
            // Where to grab the headings to build the table of contents.
            contentSelector: '.js-toc-content',
            // Which headings to grab inside of the contentSelector element.
            headingSelector: 'h1, h2, h3',
            // For headings inside relative or absolute positioned containers within content.
            hasInnerContainers: true,
        });

        $('.toc.button').popup({
            popup : $('.toc-container.popup'),
            on : 'click',
            position:'left center'
        });


    </script>
</th:block>

</body>
</html>

index.html

<!DOCTYPE html>
<html xmlns:th="http://www.w3.org/1999/xhtml">
<head th:replace="admin/_fragments :: head(~{::title})">
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>博客管理</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' type='text/css' media='screen' href='main.css'>
    <script src='main.js'></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
    <link rel="stylesheet" href="../../static/css/me.css">  
</head>
<body>
    <!--导航-->                                                   
    <nav th:replace="admin/_fragments :: menu(0)" class="ui inverted attached segment m-padded-tb-mini m-shadow-small m-shadow-small">
        
        <div class="ui container">          
            <div class="ui inverted secondary stackable menu"> 
                <h2 class="ui teal header item">管理后台</h2>   
                <a href="#" class="m-item item white m-mobile-hide"><i class=" home  icon"></i> 博客</a>       
                <a href="#" class="m-item item white m-mobile-hide"><i class=" idea  icon"></i> 分类</a> 
                <a href="#" class="m-item item white m-mobile-hide"><i class=" tags  icon"></i> 标签</a>
               <div class="right m-item menu m-mobile-hide">
                   <div class="ui dropdown m-item item">
                      <div class="text">
                        <img class="ui avatar image" src="../../static/images/me.jpg">
                        anonymous
                      </div>
                      <i class="dropdown icon "></i>
                      <div class="menu">
                          <a href="#" class="item">注销</a>
                      </div>
                   </div>
               </div>
            </div> 
        </div> 
        <a href="#" class="ui menu toggle black button m-right-top m-moblile-show">
            <i class="sidebar icon"></i>
        </a> 
    </nav>

    <div class="ui attached pointing  menu">
        <div class="ui container">
            <div class="right menu">
                <a href="#" class=" item">发布</a>
                <a href="#" class="active item teal">列表</a>
            </div>
        </div>
    </div>

    <div class="m-container-small m-padded-tb-massive">
        <div class="ui container">
            <div class="ui success large message">
                <h3>Hi</h3>
                <p>jianglinfu,welcome</p>
            </div>

            <div >
                <img src="../../static/images/login.jpg" class="ui rounded bordered fluid image">
            </div>
        </div>
    </div>



        <script src="https://cdn.jsdelivr.net/npm/jquery@3.2/dist/jquery.min.js"></script>  <!--2.引入jqurey-->
    <script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script> <!-- 1.引入cdn-->

    <script>
        $('.menu.toggle').click(function(){
            $('.m-item').toggleClass('m-mobile-hide'); 
        });

        $('.ui.dropdown').dropdown();

    </script>
</body>
</html>
3.6.2 登录的实现

构建dao层
新建UserRepository.java

package com.jlf.blog1.Dao;

import com.jlf.blog1.po.User;
import org.springframework.data.jpa.repository.JpaRepository;

public interface UserRepository extends JpaRepository<User,Long> {

 User findByUsernameAndPassword (String username,String password);
}

构建service层
新建 UserService.java

package com.jlf.blog1.service;

import com.jlf.blog1.po.User;

public interface UserService {
 User checkUser(String username,String password);
}

新建UserServiceimpl.java

package com.jlf.blog1.service;

import com.jlf.blog1.Dao.UserRepository;
import com.jlf.blog1.po.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class UserServiceimpl implements UserService{

 @Autowired
 private UserRepository userRepository;

 @Override
 public User checkUser(String username, String password) {
     User user = userRepository.findByUsernameAndPassword(username, password);
     return user;
 }
}

构建web层
新建LoginController.java

package com.jlf.blog1.web.admin;

import com.jlf.blog1.po.User;
import com.jlf.blog1.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin")
public class LoginController {

 @Autowired
 private UserService userService;

 @GetMapping
 public String loginPage() {
     return "admin/login";
 }

 @PostMapping("/login")
 public String login(@RequestParam String username,
                     @RequestParam String password,
                     HttpSession session,
                     RedirectAttributes attributes) {
     User user = userService.checkUser(username, password);
     if (user != null) {
         user.setPassword(null);
         session.setAttribute("user",user);
         return "admin/index";
     } else {
         attributes.addFlashAttribute("message", "用户名和密码错误");
         return "redirect:/admin";
     }
 }

 @GetMapping("/logout")
 public String logout(HttpSession session) {
     session.removeAttribute("user");
     return "redirect:/admin";
 }
}
3.6.3 MD5加密

新增util包,建立MD5Utils.java

package com.jlf.blog1.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;


public class MD5Utils {


 public static String code(String str){
     try {
         MessageDigest md = MessageDigest.getInstance("MD5");
         md.update(str.getBytes());
         byte[]byteDigest = md.digest();
         int i;
         StringBuffer buf = new StringBuffer("");
         for (int offset = 0; offset < byteDigest.length; offset++) {
             i = byteDigest[offset];
             if (i < 0)
                 i += 256;
             if (i < 16)
                 buf.append("0");
             buf.append(Integer.toHexString(i));
         }
         //32位加密
         return buf.toString();
         // 16位的加密
         //return buf.toString().substring(8, 24);
     } catch (NoSuchAlgorithmException e) {
         e.printStackTrace();
         return null;
     }

 }

 public static void main(String[] args) {
     System.out.println(code("jlfjlf"));
 }
}

修改数据库的为MD5密码
修改UserServiceimpl.java

@Override
 public User checkUser(String username, String password) {
     User user = userRepository.findByUsernameAndPassword(username, MD5Utils.code(password));
     return user;
 }
3.6.5 登录拦截器

新建interceptor包,创建
LoginInterceptor.java

package com.jlf.blog1.interceptor;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor extends HandlerInterceptorAdapter {
 @Override
 public boolean preHandle(HttpServletRequest request,
                          HttpServletResponse response,
                          Object handler) throws Exception {
     if (request.getSession().getAttribute("user") == null) {
         response.sendRedirect("/admin");
         return false;
     }
     return true;
 }
}

创建 WebConfig.java

package com.jlf.blog1.interceptor;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginInterceptor extends HandlerInterceptorAdapter {
 @Override
 public boolean preHandle(HttpServletRequest request,
                          HttpServletResponse response,
                          Object handler) throws Exception {
     if (request.getSession().getAttribute("user") == null) {
         response.sendRedirect("/admin");
         return false;
     }
     return true;
 }
}
package com.jlf.blog1.web.admin;


import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/admin")
public class BlogController {

  @GetMapping("/blogs")
  public String blogs(){
      return "admin/blogs";
  }
}
3.7 后台分类管理
3.7.1 构建dao层

创建TypeRepository.java

package com.jlf.blog1.Dao;

import com.jlf.blog1.po.Type;
import org.springframework.data.jpa.repository.JpaRepository;

public interface TypeRepository extends JpaRepository<Type, Long> {

 Type findByName(String name); // 查重名
}
3.7.2 构建Service层

TypeService.java

package com.jlf.blog1.service;

import com.jlf.blog1.po.Type;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

public interface TypeService {

    Type saveType(Type type);

    Type getType(Long id);

    Type getTypeByName(String name); // 不能提交重名

    Page<Type> listType(Pageable pageable);

    Type updateType(Long id,Type type);

    void deleteType(Long id);

}

TypeServiceImpl.java

package com.jlf.blog1.service;

import com.jlf.blog1.Dao.TypeRepository;
import com.jlf.blog1.NotFoundException;

import com.jlf.blog1.po.Type;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;

@Service
public class TypeServiceImpl implements TypeService{

    @Autowired
    private TypeRepository typeRepository;

    @Transactional
    @Override
    public Type saveType(Type type) {
        return typeRepository.save(type);
    }

    @Transactional
    @Override
    public Type getType(Long id) {
        return typeRepository.findOne(id);
    }

   @Override
    public Type getTypeByName(String name) {
        return typeRepository.findByName(name);   // 查是否重名
    }


    @Transactional
    @Override
    public Page<Type> listType(Pageable pageable) {
        return typeRepository.findAll(pageable);
    }

    @Transactional
    @Override
    public Type updateType(Long id, Type type) {
        Type t = typeRepository.findOne(id);
        if (t == null){
            throw new NotFoundException("不存在该类型");
        }
        BeanUtils.copyProperties(type,t);

        return typeRepository.save(t);
    }

    @Transactional
    @Override
    public void deleteType(Long id) {
        typeRepository.delete(id);
    }
}
3.7.3 构建control层
package com.jlf.blog1.web.admin;



import com.jlf.blog1.po.Type;
import com.jlf.blog1.service.TypeService;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Controller;

import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;

import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;

import org.springframework.ui.Model;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.jws.WebParam;
import javax.validation.Valid;

@Controller
@RequestMapping("/admin")
public class TypeController {

    @Autowired
    private TypeService typeService;


    @GetMapping("/types")
    public String list(@PageableDefault(size = 3,sort = {"id"}, direction = Sort.Direction.DESC)
                               Pageable pageable, Model model){
        model.addAttribute("page",typeService.listType(pageable));
        typeService.listType(pageable);
        return "admin/types";
    }

    @GetMapping("/types/input")
    public String input(Model model)
    {
        model.addAttribute("type",new Type());
        return "admin/types-input";
    }

    @GetMapping("/types/{id}/input")
    public String editInput(@PathVariable Long id, Model model){
        model.addAttribute("type",typeService.getType(id));
        return "admin/types-input";
    }

    @PostMapping("/types")
    public String post(@Valid Type type, BindingResult result, RedirectAttributes attributes){
        Type type1 = typeService.getTypeByName(type.getName());
        if (type1 != null){
            result.rejectValue("name","nameError","不能重复添加分类");
        }   // 判断是否重复添加
        if (result.hasErrors()){
            return "admin/types-input";
        }
        
        Type t = typeService.saveType(type);
        if (t == null){
            attributes.addFlashAttribute("message","操作失败");
        } else {
            attributes.addFlashAttribute("message","操作成功");
        }

        return "redirect:/admin/types";
    }

    @PostMapping("/types/{id}")
    public String editPost(@Valid Type type, BindingResult result,@PathVariable Long id, RedirectAttributes attributes) {
        Type type1 = typeService.getTypeByName(type.getName());
        if (type1 != null) {
            result.rejectValue("name","nameError","不能添加重复的分类");
        }
        if (result.hasErrors()) {
            return "admin/types-input";
        }
        Type t = typeService.updateType(id,type);
        if (t == null ) {
            attributes.addFlashAttribute("message", "更新失败");
        } else {
            attributes.addFlashAttribute("message", "更新成功");
        }
        return "redirect:/admin/types";
    }

    @GetMapping("/types/{id}/delete")
    public String delete(@PathVariable Long id,RedirectAttributes attributes) {
        typeService.deleteType(id);
        attributes.addFlashAttribute("message", "删除成功");
        return "redirect:/admin/types";
    }

}
3.7.4 重构types.html,types-input.html

types.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:replace="admin/_fragments :: head(~{::title})">
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>分类管理</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' type='text/css' media='screen' href='main.css'>
    <script src='main.js'></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
    <link rel="stylesheet" href="../../static/css/me.css">  
</head>
<body>
    <!--导航-->                                                   
    <nav th:replace="admin/_fragments :: menu(2)" class="ui inverted attached segment m-padded-tb-mini m-shadow-small m-shadow-small">
        
        <div class="ui container">          
            <div class="ui inverted secondary stackable menu"> 
                <h2 class="ui teal header item">管理后台</h2>   
                <a href="#" class="m-item item white m-mobile-hide"><i class=" home  icon"></i> 博客</a>       
                <a href="#"  class="m-item item white m-mobile-hide"><i class=" idea  icon"></i> 分类</a>
                <a href="#" class="m-item item white m-mobile-hide"><i class=" tags  icon"></i> 标签</a>
               <div class="right m-item menu m-mobile-hide">
                   <div class="ui dropdown m-item item">
                      <div class="text">
                        <img class="ui avatar image" src="../../static/images/me.jpg">
                        anonymous
                      </div>
                      <i class="dropdown icon "></i>
                      <div class="menu">
                          <a href="#" class="item">注销</a>
                      </div>
                   </div>
               </div>
            </div> 
        </div> 
        <a href="#" class="ui menu toggle black button m-right-top m-moblile-show">
            <i class="sidebar icon"></i>
        </a> 
    </nav>

    <div class="ui attached pointing  menu">
        <div class="ui container">
            <div class="right menu">
                <a href="#" class=" item">新增</a>
                <a href="#" class="active item teal">列表</a>
            </div>
        </div>
    </div>


    <!--中间内容-->
    <div class="m-container-small m-padded-tb-massive">
        <div class="ui container">
            <div class="ui success message" th:unless="${#strings.isEmpty(message)}">
                <i class="close icon"></i>
                <div class="header">提示:</div>
                <p th:text="${message}">恭喜,操作成功!</p>
            </div>
            <table class="ui table celled compact teal">
                <thead>
                    <tr>
                        <th></th>
                        <th>名称</th>
                        <th>操作</th>
                    </tr>
                </thead>
                <tbody>
                    <tr th:each="type,iterStat : ${page.content}">
                        <td th:text="${iterStat.count}">1</td>
                        <td th:text="${type.name}">什么是spirng</td>
                        <td>
                            <a href="#" th:href="@{/admin/types/{id}/input(id=${type.id})}" class="ui mini teal basic button">编辑</a>
                            <a href="#" th:href="@{/admin/types/{id}/delete(id=${type.id})}" class="ui mini red basic button">删除</a>
                        </td>
                    </tr>

                </tbody>
                <tfoot>
                    <tr>
                        <th colspan="6" >
                            <div class="ui mini  pagination menu" th:if="${page.totalPages}>1">
                                <a th:href="@{/admin/types(page=${page.number}-1)}" class="item" th:unless="${page.first}">上一页</a>
                                <a th:href="@{/admin/types(page=${page.number}+1)}" class="item" th:unless="${page.last}">下一页</a>
                            </div>
                            <a href="#" th:href="@{/admin/types/input}" class="ui teal right floated mini basic button">新增</a>
                        </th>
                    </tr>
                </tfoot>
            </table>
        </div>
    </div>
        <br>  
        <br>
        <br><br>  
    
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.2/dist/jquery.min.js"></script>  <!--2.引入jqurey-->
    <script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script> <!-- 1.引入cdn-->

    <script>
        $('.menu.toggle').click(function(){
            $('.m-item').toggleClass('m-mobile-hide'); 
        });

        $('.ui.dropdown').dropdown();


        $('.message .close')
            .on('click', function () {
                $(this)
                    .closest('.message')
                    .transition('fade');
            });
    </script>
</body>
</html>

types-input.html

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.w3.org/1999/xhtml">
<head th:replace="admin/_fragments :: head(~{::title})">
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>
    <title>分类新增</title>
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <link rel='stylesheet' type='text/css' media='screen' href='main.css'>
    <script src='main.js'></script>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.css">
    <link rel="stylesheet" href="../../static/css/me.css">  
</head>
<body>
    <!--导航-->                                                   
    <nav th:replace="admin/_fragments :: menu(2)" class="ui inverted attached segment m-padded-tb-mini m-shadow-small m-shadow-small">
        
        <div class="ui container">          
            <div class="ui inverted secondary stackable menu"> 
                <h2 class="ui teal header item">管理后台</h2>   
                <a href="#" class="m-item item white m-mobile-hide"><i class=" home  icon"></i> 博客</a>       
                <a href="#" class="m-item item white m-mobile-hide"><i class=" idea  icon"></i> 分类</a> 
                <a href="#" class="m-item item white m-mobile-hide"><i class=" tags  icon"></i> 标签</a>
               <div class="right m-item menu m-mobile-hide">
                   <div class="ui dropdown m-item item">
                      <div class="text">
                        <img class="ui avatar image" src="../../static/images/me.jpg">
                        anonymous
                      </div>
                      <i class="dropdown icon "></i>
                      <div class="menu">
                          <a href="#" class="item">注销</a>
                      </div>
                   </div>
               </div>
            </div> 
        </div> 
        <a href="#" class="ui menu toggle black button m-right-top m-moblile-show">
            <i class="sidebar icon"></i>
        </a> 
    </nav>

    <div class="ui attached pointing  menu">
        <div class="ui container">
            <div class="right menu">
                <a href="#" class=" item">发布</a>
                <a href="#" class="active item teal">列表</a>
            </div>
        </div>
    </div>


    <!--中间内容-->
    <div class="m-container-small m-padded-tb-massive">
        <div class="ui container">
            <form action="#" method="post" th:action="@{/admin/types}" th:object="${type}"   class="ui form">
                <input type="hidden" name="id">
                <div class="required field">
                    <div class="ui left labeled input">
                        <label class="ui teal basic label">名称</label>
                        <input type="text" name="name" placeholder="分类名称" th:value="*{name}" >
                    </div>
                </div>

                <div class="ui error message"></div>
                <!--/*/
                        <div class="ui negative message" th:if="${#fields.hasErrors('name')}"  >
                          <i class="close icon"></i>
                          <div class="header">验证失败</div>
                          <p th:errors="*{name}">提交信息不符合规则</p>
                        </div>
                 /*/-->
                <div class="ui right aligned container">
                    <button type="button" class="ui button" onclick="window.history.go(-1)" >返回</button>
                    <button class="ui teal submit button">提交</button>
                </div>

            </form>
        </div>
    </div>
        <br>  
        <br>
        <br><br>         
       
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.2/dist/jquery.min.js"></script>  <!--2.引入jqurey-->
    <script src="https://cdn.jsdelivr.net/npm/semantic-ui@2.4.2/dist/semantic.min.js"></script> <!-- 1.引入cdn-->

    <script>
        $('.menu.toggle').click(function(){
            $('.m-item').toggleClass('m-mobile-hide'); 
        });

        $('.ui.dropdown').dropdown();

        $('.ui.form').form({
            fields : {
                title : {
                    identifier: 'name',
                    rules: [{
                        type : 'empty',
                        prompt: '请输入分类名称'
                    }]
                }
            }
        });

    </script>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值