[记录学习]分析学习第一个SSM项目:ForestBlog _03

2.7 service、serviceImpl 业务逻辑层

├─service
│ │ ArticleService.java
│ │ CategoryService.java
│ │ CommentService.java
│ │ LinkService.java
│ │ MenuService.java
│ │ NoticeService.java
│ │ OptionsService.java
│ │ PageService.java
│ │ TagService.java
│ │ UserService.java
│ │
│ └─impl
│ ArticleServiceImpl.java
│ CategoryServiceImpl.java
│ CommentServiceImpl.java
│ LinkServiceImpl.java
│ MenuServiceImpl.java
│ NoticeServiceImpl.java
│ OptionsServiceImpl.java
│ PageServiceImpl.java
│ TagServiceImpl.java
│ UserServiceImpl.java

2.7.1 ArticleService
  1. com.liuyanzhao.ssm.blog.service.ArticleService

    package com.liuyanzhao.ssm.blog.service;
    
    import com.github.pagehelper.PageInfo;
    import com.liuyanzhao.ssm.blog.entity.Article;
    
    import java.util.HashMap;
    import java.util.List;
    
    /**
     * 文章Service
     *
     * @author 言曌
     * @date 2017/8/24
     */
    public interface ArticleService {
    
        /**
         * 获取文章总数
         *
         * @param status 状态
         * @return 数量
         */
        Integer countArticle(Integer status);
    
        /**
         * 获取评论总数
         *
         * @return 数量
         */
        Integer countArticleComment();
    
        /**
         * 获得浏览量总数
         *
         * @return 数量
         */
        Integer countArticleView();
    
        /**
         * 统计有这个分类的文章数
         *
         * @param categoryId 分类ID
         * @return 数量
         */
        Integer countArticleByCategoryId(Integer categoryId);
    
        /**
         * 统计有这个表情的文章数
         *
         * @param tagId 标签ID
         * @return 数量
         */
        Integer countArticleByTagId(Integer tagId);
    
    
        /**
         * 获得所有文章不分页
         *
         * @param criteria 查询条件
         * @return 列表
         */
        List<Article> listArticle(HashMap<String, Object> criteria);
    
        /**
         * 获得最新文章
         *
         * @param limit 查询数量
         * @return 列表
         */
        List<Article> listRecentArticle(Integer userId, Integer limit);
    
    
        /**
         * 修改文章详细信息
         *
         * @param article 文章
         */
        void updateArticleDetail(Article article);
    
        /**
         * 修改文章简单信息
         *
         * @param article 文章
         */
        void updateArticle(Article article);
    
        /**
         * 批量删除文章
         *
         * @param ids 文章ID
         */
        void deleteArticleBatch(List<Integer> ids);
    
        /**
         * 删除文章
         *
         * @param id 文章ID
         */
        void deleteArticle(Integer id);
    
        /**
         * 分页显示
         *
         * @param pageIndex 第几页开始
         * @param pageSize  一页显示多少
         * @param criteria  查询条件
         * @return 文章列表
         */
        PageInfo<Article> pageArticle(Integer pageIndex,
                                      Integer pageSize,
                                      HashMap<String, Object> criteria);
    
        /**
         * 文章详情页面显示
         *
         * @param status 状态
         * @param id     文章ID
         * @return 文章
         */
        Article getArticleByStatusAndId(Integer status, Integer id);
    
        /**
         * 获取访问量较多的文章
         *
         * @param limit 查询数量
         * @return 列表
         */
        List<Article> listArticleByViewCount(Integer limit);
    
        /**
         * 获得上一篇文章
         *
         * @param id 文章ID
         * @return 文章
         */
        Article getAfterArticle(Integer id);
    
        /**
         * 获得下一篇文章
         *
         * @param id 文章ID
         * @return 文章
         */
        Article getPreArticle(Integer id);
    
        /**
         * 获得随机文章
         *
         * @param limit 查询数量
         * @return 列表
         */
        List<Article> listRandomArticle(Integer limit);
    
        /**
         * 获得评论数较多的文章
         *
         * @param limit 查询数量
         * @return 列表
         */
        List<Article> listArticleByCommentCount(Integer limit);
    
        /**
         * 添加文章
         *
         * @param article 文章
         */
        void insertArticle(Article article);
    
    
        /**
         * 更新文章的评论数
         *
         * @param articleId 文章ID
         */
        void updateCommentCount(Integer articleId);
    
        /**
         * 获得最后更新记录
         *
         * @return 文章
         */
        Article getLastUpdateArticle();
    
        /**
         * 获得相关文章
         *
         * @param cateId 分类ID
         * @param limit  查询数量
         * @return 列表
         */
        List<Article> listArticleByCategoryId(Integer cateId, Integer limit);
    
        /**
         * 获得相关文章
         *
         * @param cateIds 分类ID集合
         * @param limit   数量
         * @return 列表
         */
        List<Article> listArticleByCategoryIds(List<Integer> cateIds, Integer limit);
    
    
        /**
         * 根据文章ID获得分类ID列表
         *
         * @param articleId 文章Id
         * @return 列表
         */
        List<Integer> listCategoryIdByArticleId(Integer articleId);
    
        /**
         * 获得所有的文章
         *
         * @return 列表
         */
        List<Article> listAllNotWithContent();
    }
    
  2. com.liuyanzhao.ssm.blog.service.impl.ArticleServiceImpl

    package com.liuyanzhao.ssm.blog.service.impl;
    
    import cn.hutool.core.util.RandomUtil;
    import com.github.pagehelper.PageHelper;
    import com.github.pagehelper.PageInfo;
    import com.liuyanzhao.ssm.blog.enums.ArticleCommentStatus;
    import com.liuyanzhao.ssm.blog.mapper.*;
    import com.liuyanzhao.ssm.blog.service.ArticleService;
    import com.liuyanzhao.ssm.blog.entity.*;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.util.StringUtils;
    
    import java.util.ArrayList;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    
    /**
     * 文章Servie实现
     *
     * @author 言曌
     * @date 2017/8/24
     */
    @Service
    @Slf4j
    public class ArticleServiceImpl implements ArticleService {
    
        @Autowired
        private ArticleMapper articleMapper;
    
        @Autowired
        private ArticleCategoryRefMapper articleCategoryRefMapper;
    
        @Autowired
        private ArticleTagRefMapper articleTagRefMapper;
    
        @Autowired
        private UserMapper userMapper;
    
        @Autowired
        private CommentMapper commentMapper;
    
        /**
         * 获取文章总数
         *
         * @param status 状态
         * @return 数量
         */
        @Override
        public Integer countArticle(Integer status) {
            Integer count = 0;
            try {
                count = articleMapper.countArticle(status);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("根据状态统计文章数, status:{}, cause:{}", status, e);
            }
            return count;
        }
    
        /**
         * 获取评论总数
         *
         * @return 数量
         */
        @Override
        public Integer countArticleComment() {
            Integer count = 0;
            try {
                count = articleMapper.countArticleComment();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("统计文章评论数失败, cause:{}", e);
            }
            return count;
        }
    
    
        /**
         * 获得浏览量总数
         *
         * @return 数量
         */
        @Override
        public Integer countArticleView() {
            Integer count = 0;
            try {
                count = articleMapper.countArticleView();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("统计文章访问量失败, cause:{}", e);
            }
            return count;
        }
    
        /**
         * 统计有这个分类的文章数
         *
         * @param categoryId 分类ID
         * @return 数量
         */
        @Override
        public Integer countArticleByCategoryId(Integer categoryId) {
            Integer count = 0;
            try {
                count = articleCategoryRefMapper.countArticleByCategoryId(categoryId);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("根据分类统计文章数量失败, categoryId:{}, cause:{}", categoryId, e);
            }
            return count;
        }
    
        /**
         * 统计有这个标签的文章数
         *
         * @param tagId 标签ID
         * @return 数量
         */
        @Override
        public Integer countArticleByTagId(Integer tagId) {
            return articleTagRefMapper.countArticleByTagId(tagId);
    
        }
    
        /**
         * 根据查询条件获得所有文章不分页
         *
         * @param criteria 查询条件
         * @return 列表
         */
        @Override
        public List<Article> listArticle(HashMap<String, Object> criteria) {
            return articleMapper.findAll(criteria);
        }
    
        /**
         * 获得最新文章
         *
         * @param limit 查询数量
         * @return 列表
         */
        @Override
        public List<Article> listRecentArticle(Integer userId, Integer limit) {
            return articleMapper.listArticleByLimit(userId, limit);
        }
    
        /**
         * 修改文章详细信息
         *
         * @param article 文章
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void updateArticleDetail(Article article) {
            article.setArticleUpdateTime(new Date());
            articleMapper.update(article);
    
            if (article.getTagList() != null) {
                //删除标签和文章关联
                articleTagRefMapper.deleteByArticleId(article.getArticleId());
                //添加标签和文章关联
                for (int i = 0; i < article.getTagList().size(); i++) {
                    ArticleTagRef articleTagRef = new ArticleTagRef(article.getArticleId(), article.getTagList().get(i).getTagId());
                    articleTagRefMapper.insert(articleTagRef);
                }
            }
    
            if (article.getCategoryList() != null) {
                //添加分类和文章关联
                articleCategoryRefMapper.deleteByArticleId(article.getArticleId());
                //删除分类和文章关联
                for (int i = 0; i < article.getCategoryList().size(); i++) {
                    ArticleCategoryRef articleCategoryRef = new ArticleCategoryRef(article.getArticleId(), article.getCategoryList().get(i).getCategoryId());
                    articleCategoryRefMapper.insert(articleCategoryRef);
                }
            }
        }
    
        /**
         * 修改文章简单信息
         *
         * @param article 文章
         */
        @Override
        public void updateArticle(Article article) {
            articleMapper.update(article);
        }
    
        /**
         * 批量删除文章
         *
         * @param ids 文章ID
         */
        @Override
        public void deleteArticleBatch(List<Integer> ids) {
            articleMapper.deleteBatch(ids);
        }
    
        /**
         * 删除文章
         *
         * @param id 文章ID
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void deleteArticle(Integer id) {
            articleMapper.deleteById(id);
            // 删除分类关联
            articleCategoryRefMapper.deleteByArticleId(id);
            // 删除标签管理
            articleTagRefMapper.deleteByArticleId(id);
            // 删除评论
            commentMapper.deleteByArticleId(id);
        }
    
    
        /**
         * 分页显示
         *
         * @param pageIndex 第几页开始
         * @param pageSize  一页显示多少
         * @param criteria  查询条件
         * @return 文章列表
         */
        @Override
        public PageInfo<Article> pageArticle(Integer pageIndex,
                                  Integer pageSize,
                                  HashMap<String, Object> criteria) {
            PageHelper.startPage(pageIndex, pageSize);
            List<Article> articleList = articleMapper.findAll(criteria);
            for (int i = 0; i < articleList.size(); i++) {
                //封装CategoryList
                List<Category> categoryList = articleCategoryRefMapper.listCategoryByArticleId(articleList.get(i).getArticleId());
                if (categoryList == null || categoryList.size() == 0) {
                    categoryList = new ArrayList<>();
                    categoryList.add(Category.Default());
                }
                articleList.get(i).setCategoryList(categoryList);
    
                articleList.get(i).setUser(userMapper.getUserById(articleList.get(i).getArticleUserId()));
    //            //封装TagList
    //            List<Tag> tagList = articleTagRefMapper.listTagByArticleId(articleList.get(i).getArticleId());
    //            articleList.get(i).setTagList(tagList);
            }
            return new PageInfo<>(articleList);
        }
    
        /**
         * 文章详情页面显示
         *
         * @param status 状态
         * @param id     文章ID
         * @return 文章
         */
        @Override
        public Article getArticleByStatusAndId(Integer status, Integer id) {
            Article article = articleMapper.getArticleByStatusAndId(status, id);
            if (article != null) {
                List<Category> categoryList = articleCategoryRefMapper.listCategoryByArticleId(article.getArticleId());
                List<Tag> tagList = articleTagRefMapper.listTagByArticleId(article.getArticleId());
                article.setCategoryList(categoryList);
                article.setTagList(tagList);
            }
            return article;
        }
    
    
        /**
         * 获取访问量较多的文章
         *
         * @param limit 查询数量
         * @return 列表
         */
        @Override
        public List<Article> listArticleByViewCount(Integer limit) {
            return articleMapper.listArticleByViewCount(limit);
        }
    
        /**
         * 获得上一篇文章
         *
         * @param id 文章ID
         * @return 文章
         */
        @Override
        public Article getAfterArticle(Integer id) {
            return articleMapper.getAfterArticle(id);
        }
    
        /**
         * 获得下一篇文章
         *
         * @param id 文章ID
         * @return 文章
         */
        @Override
        public Article getPreArticle(Integer id) {
            return articleMapper.getPreArticle(id);
        }
    
        /**
         * 获得随机文章
         *
         * @param limit 查询数量
         * @return 列表
         */
        @Override
        public List<Article> listRandomArticle(Integer limit) {
            return articleMapper.listRandomArticle(limit);
        }
    
        /**
         * 获得评论数较多的文章
         *
         * @param limit 查询数量
         * @return 列表
         */
        @Override
        public List<Article> listArticleByCommentCount(Integer limit) {
            return articleMapper.listArticleByCommentCount(limit);
        }
    
    
        /**
         * 添加文章
         *
         * @param article 文章
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void insertArticle(Article article) {
            //添加文章
            article.setArticleCreateTime(new Date());
            article.setArticleUpdateTime(new Date());
            article.setArticleIsComment(ArticleCommentStatus.ALLOW.getValue());
            article.setArticleViewCount(0);
            article.setArticleLikeCount(0);
            article.setArticleCommentCount(0);
            article.setArticleOrder(1);
            if (StringUtils.isEmpty(article.getArticleThumbnail())) {
                article.setArticleThumbnail("/img/thumbnail/random/img_" + RandomUtil.randomNumbers(1) + ".jpg");
            }
    
            articleMapper.insert(article);
            //添加分类和文章关联
            for (int i = 0; i < article.getCategoryList().size(); i++) {
                ArticleCategoryRef articleCategoryRef = new ArticleCategoryRef(article.getArticleId(), article.getCategoryList().get(i).getCategoryId());
                articleCategoryRefMapper.insert(articleCategoryRef);
            }
            //添加标签和文章关联
            for (int i = 0; i < article.getTagList().size(); i++) {
                ArticleTagRef articleTagRef = new ArticleTagRef(article.getArticleId(), article.getTagList().get(i).getTagId());
                articleTagRefMapper.insert(articleTagRef);
            }
        }
    
        /**
         * 更新文章的评论数
         *
         * @param articleId 文章ID
         */
        @Override
        public void updateCommentCount(Integer articleId) {
            articleMapper.updateCommentCount(articleId);
        }
    
        /**
         * 获得最后更新记录
         *
         * @return 文章
         */
        @Override
        public Article getLastUpdateArticle() {
            return articleMapper.getLastUpdateArticle();
        }
    
        /**
         * 获得相关文章
         *
         * @param cateId 分类ID
         * @param limit  查询数量
         * @return 列表
         */
        @Override
        public List<Article> listArticleByCategoryId(Integer cateId, Integer limit) {
            return articleMapper.findArticleByCategoryId(cateId, limit);
        }
    
        @Override
        public List<Article> listArticleByCategoryIds(List<Integer> cateIds, Integer limit) {
            if (cateIds == null || cateIds.size() == 0) {
                return null;
            }
            return articleMapper.findArticleByCategoryIds(cateIds, limit);
        }
    
        /**
         * 获得相关文章
         *
         * @param cateIds 分类ID集合
         * @param limit   数量
         * @return 列表
         */
        @Override
        public List<Integer> listCategoryIdByArticleId(Integer articleId) {
            return articleCategoryRefMapper.selectCategoryIdByArticleId(articleId);
        }
    
        /**
         * 根据文章ID获得分类ID列表
         *
         * @param articleId 文章Id
         * @return 列表
         */
        @Override
        public List<Article> listAllNotWithContent() {
            return articleMapper.listAllNotWithContent();
        }
    
    }
    
2.7.2 CategoryService
  1. com.liuyanzhao.ssm.blog.service.CategoryService

    package com.liuyanzhao.ssm.blog.service;
    
    
    import com.liuyanzhao.ssm.blog.entity.Category;
    
    
    import java.util.List;
    
    /**
     * @author 言曌
     * @date 2017/8/24
     */
    public interface CategoryService {
        /**
         * 获得分类总数
         *
         * @return
         */
        Integer countCategory();
    
    
        /**
         * 获得分类列表
         *
         * @return 分类列表
         */
        List<Category> listCategory();
    
        /**
         * 获得分类列表
         *
         * @return 分类列表
         */
        List<Category> listCategoryWithCount();
    
        /**
         * 删除分类
         *
         * @param id ID
         */
    
        void deleteCategory(Integer id);
    
        /**
         * 根据id查询分类信息
         *
         * @param id     ID
         * @return 分类
         */
        Category getCategoryById(Integer id);
    
        /**
         * 添加分类
         *
         * @param category 分类
         * @return 分类
         */
        Category insertCategory(Category category);
    
        /**
         * 更新分类
         *
         * @param category 分类
         */
        void updateCategory(Category category);
    
        /**
         * 根据分类名获取分类
         *
         * @param name 名称
         * @return 分类
         */
        Category getCategoryByName(String name);
    
    }
    
  2. com.liuyanzhao.ssm.blog.service.impl.CategoryServiceImpl

    package com.liuyanzhao.ssm.blog.service.impl;
    
    import com.liuyanzhao.ssm.blog.mapper.ArticleCategoryRefMapper;
    import com.liuyanzhao.ssm.blog.mapper.CategoryMapper;
    import com.liuyanzhao.ssm.blog.entity.Category;
    import com.liuyanzhao.ssm.blog.service.CategoryService;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.transaction.interceptor.TransactionAspectSupport;
    
    import java.util.List;
    
    
    /**
     *
     * @author 言曌
     * @date 2017/8/24
     */
    @Service
    @Slf4j
    public class CategoryServiceImpl implements CategoryService {
    
        @Autowired
        private CategoryMapper categoryMapper;
    
        @Autowired
        private ArticleCategoryRefMapper articleCategoryRefMapper;
    
        /**
         * 删除分类
         *
         * @param id ID
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void deleteCategory(Integer id) {
            try {
                categoryMapper.deleteCategory(id);
                articleCategoryRefMapper.deleteByCategoryId(id);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("删除分类失败, id:{}, cause:{}", id, e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
        }
    
        /**
         * 根据id查询分类信息
         *
         * @param id     ID
         * @return 分类
         */
        @Override
        public Category getCategoryById(Integer id) {
            Category category = null;
            try {
                category = categoryMapper.getCategoryById(id);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("根据分类ID获得分类, id:{}, cause:{}", id, e);
            }
            return category;
        }
    
        /**
         * 更新分类
         *
         * @param category 分类
         */
        @Override
        public void updateCategory(Category category) {
            try {
                categoryMapper.update(category);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("更新分类失败, category:{}, cause:{}", category, e);
            }
        }
    
        /**
         * 添加分类
         *
         * @param category 分类
         * @return 分类
         */
        @Override
        public Category insertCategory(Category category) {
            try {
                categoryMapper.insert(category);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("创建分类失败, category:{}, cause:{}", category, e);
            }
            return category;
        }
    
        /**
         * 获得分类总数
         *
         * @return
         */
        @Override
        public Integer countCategory() {
            Integer count = 0;
            try {
                count = categoryMapper.countCategory();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("统计分类失败, cause:{}", e);
            }
            return count;
        }
    
    
        /**
         * 获得分类列表
         *
         * @return 分类列表
         */
        @Override
        public List<Category> listCategory() {
            List<Category> categoryList = null;
            try {
                categoryList = categoryMapper.listCategory();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("根据文章获得分类列表失败, cause:{}", e);
            }
            return categoryList;
        }
    
        /**
         * 获得分类列表
         *
         * @return 分类列表
         */
        @Override
        public List<Category> listCategoryWithCount() {
            List<Category> categoryList = null;
            try {
                categoryList = categoryMapper.listCategory();
                for (int i = 0; i < categoryList.size(); i++) {
                    Integer count = articleCategoryRefMapper.countArticleByCategoryId(categoryList.get(i).getCategoryId());
                    categoryList.get(i).setArticleCount(count);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("根据文章获得分类列表失败, cause:{}", e);
            }
            return categoryList;
        }
    
        /**
         * 根据分类名获取分类
         *
         * @param name 名称
         * @return 分类
         */
        @Override
        public Category getCategoryByName(String name) {
            Category category = null;
            try {
                category = categoryMapper.getCategoryByName(name);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("更新分类失败, category:{}, cause:{}", category, e);
            }
            return category;
        }
        
    }
    
2.7.3 CommentService
  1. com.liuyanzhao.ssm.blog.service.CommentService

    package com.liuyanzhao.ssm.blog.service;
    
    import com.github.pagehelper.PageInfo;
    import com.liuyanzhao.ssm.blog.entity.Comment;
    import org.springframework.stereotype.Service;
    
    import java.util.HashMap;
    import java.util.List;
    
    
    /**
     * @author 言曌
     * @date 2017/9/10
     */
    @Service
    public interface CommentService {
    
        /**
         * 添加评论
         *
         * @param comment 评论
         */
        void insertComment(Comment comment);
    
        /**
         * 根据文章id获取评论列表
         *
         * @param articleId 文章ID
         * @return 列表
         */
        List<Comment> listCommentByArticleId(Integer articleId);
    
        /**
         * 根据id获取评论
         *
         * @param id
         * @return
         */
        Comment getCommentById(Integer id);
    
    
        /**
         * 获取所有评论列表
         *
         * @param pageIndex 第几页开始
         * @param pageSize  一页显示数量
         * @return 列表
         */
        PageInfo<Comment> listCommentByPage(
                Integer pageIndex,
                Integer pageSize,
                HashMap<String, Object> criteria);
    
        /**
         * 获得某个用户收到的评论
         *
         * @param pageIndex 第几页开始
         * @param pageSize  一页显示数量
         * @return 列表
         */
        PageInfo<Comment> listReceiveCommentByPage(
                Integer pageIndex,
                Integer pageSize,
                Integer userId);
    
    
        /**
         * 删除评论
         *
         * @param id ID
         */
        void deleteComment(Integer id);
    
        /**
         * 修改评论
         *
         * @param comment 评论
         */
        void updateComment(Comment comment);
    
        /**
         * 统计评论数
         *
         * @return 数量
         */
        Integer countComment();
    
        /**
         * 获得最近评论
         *
         * @param limit 查询数量
         * @return 列表
         */
        List<Comment> listRecentComment(Integer userId, Integer limit);
    
        /**
         * 获得评论的子评论
         *
         * @param id 评论ID
         * @return 列表
         */
        List<Comment> listChildComment(Integer id);
    
    }
    
  2. com.liuyanzhao.ssm.blog.service.impl.CommentServiceImpl

    package com.liuyanzhao.ssm.blog.service.impl;
    
    import com.github.pagehelper.PageHelper;
    import com.github.pagehelper.PageInfo;
    import com.liuyanzhao.ssm.blog.entity.Article;
    import com.liuyanzhao.ssm.blog.entity.Comment;
    import com.liuyanzhao.ssm.blog.enums.ArticleStatus;
    import com.liuyanzhao.ssm.blog.mapper.CommentMapper;
    import com.liuyanzhao.ssm.blog.mapper.ArticleMapper;
    import com.liuyanzhao.ssm.blog.service.CommentService;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    
    import org.springframework.stereotype.Service;
    
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    
    /**
     * @author 言曌
     * @date 2017/9/10
     */
    @Service
    @Slf4j
    public class CommentServiceImpl implements CommentService {
    
        @Autowired
        private CommentMapper commentMapper;
    
        @Autowired
        private ArticleMapper articleMapper;
    
        /**
         * 添加评论
         *
         * @param comment 评论
         */
        @Override
        public void insertComment(Comment comment) {
            try {
                commentMapper.insert(comment);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("创建评论失败:comment:{}, cause:{}", comment, e);
            }
        }
    
        /**
         * 根据文章id获取评论列表
         *
         * @param articleId 文章ID
         * @return 列表
         */
        @Override
        public List<Comment> listCommentByArticleId(Integer articleId) {
            List<Comment> commentList = null;
            try {
                commentList = commentMapper.listCommentByArticleId(articleId);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("根据文章ID获得评论列表失败,articleId:{},cause:{}", articleId, e);
            }
            return commentList;
        }
    
        /**
         * 根据id获取评论
         *
         * @param id
         * @return
         */
        @Override
        public Comment getCommentById(Integer id) {
            Comment comment = null;
            try {
                comment = commentMapper.getCommentById(id);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("根据评论ID获得评论,id:{}, cause:{}", id, e);
            }
            return comment;
        }
    
        /**
         * 获取所有评论列表
         *
         * @param pageIndex 第几页开始
         * @param pageSize  一页显示数量
         * @return 列表
         */
        @Override
        public PageInfo<Comment> listCommentByPage(Integer pageIndex, Integer pageSize, HashMap<String, Object> criteria) {
            PageHelper.startPage(pageIndex, pageSize);
            List<Comment> commentList = null;
            try {
                commentList = commentMapper.listComment(criteria);
                for (int i = 0; i < commentList.size(); i++) {
                    Article article = articleMapper.getArticleByStatusAndId(ArticleStatus.PUBLISH.getValue(), commentList.get(i).getCommentArticleId());
                    commentList.get(i).setArticle(article);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("分页获得评论失败,pageIndex:{}, pageSize:{}, cause:{}", pageIndex, pageSize, e);
            }
            return new PageInfo<>(commentList);
        }
    
        /**
         * 获得某个用户收到的评论
         *
         * @param pageIndex 第几页开始
         * @param pageSize  一页显示数量
         * @param userId 用户ID
         * @return 列表
         */
        @Override
        public PageInfo<Comment> listReceiveCommentByPage(Integer pageIndex, Integer pageSize, Integer userId) {
            PageHelper.startPage(pageIndex, pageSize);
            List<Comment> commentList = new ArrayList<>();
            try {
                List<Integer> articleIds = articleMapper.listArticleIdsByUserId(userId);
                if (articleIds != null && articleIds.size() > 0) {
                    commentList = commentMapper.getReceiveComment(articleIds);
                    for (int i = 0; i < commentList.size(); i++) {
                        Article article = articleMapper.getArticleByStatusAndId(ArticleStatus.PUBLISH.getValue(), commentList.get(i).getCommentArticleId());
                        commentList.get(i).setArticle(article);
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("分页获得评论失败,pageIndex:{}, pageSize:{}, cause:{}", pageIndex, pageSize, e);
            }
            return new PageInfo<>(commentList);
        }
    
        /**
         * 删除评论
         *
         * @param id ID
         */
        @Override
        public void deleteComment(Integer id) {
            try {
                commentMapper.deleteById(id);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("删除评论失败, id:{}, cause:{}", id, e);
            }
        }
    
        /**
         * 修改评论
         *
         * @param comment 评论
         */
        @Override
        public void updateComment(Comment comment) {
            try {
                commentMapper.update(comment);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("更新评论,comment:{}, cause:{}", comment, e);
            }
        }
    
        /**
         * 统计评论数
         *
         * @return 数量
         */
        @Override
        public Integer countComment() {
            Integer commentCount = null;
            try {
                commentCount = commentMapper.countComment();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("统计评论数量失败, cause:{}", e);
            }
            return commentCount;
        }
    
        /**
         * 获得最近评论
         *
         * @param userId 用户ID
         * @param limit 查询数量
         * @return 列表
         */
        @Override
        public List<Comment> listRecentComment(Integer userId, Integer limit) {
            List<Comment> commentList = null;
            try {
                commentList = commentMapper.listRecentComment(userId, limit);
                for (int i = 0; i < commentList.size(); i++) {
                    Article article = articleMapper.getArticleByStatusAndId(ArticleStatus.PUBLISH.getValue(), commentList.get(i).getCommentArticleId());
                    commentList.get(i).setArticle(article);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获得最新评论失败, limit:{}, cause:{}", limit, e);
            }
            return commentList;
        }
    
        /**
         * 获得评论的子评论
         *
         * @param id 评论ID
         * @return 列表
         */
        @Override
        public List<Comment> listChildComment(Integer id) {
            List<Comment> childCommentList = null;
            try {
                childCommentList = commentMapper.listChildComment(id);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获得子评论失败, id:{}, cause:{}", id, e);
            }
            return childCommentList;
        }
    
    }
    
2.7.4 LinkService
  1. com.liuyanzhao.ssm.blog.service.LinkService

    package com.liuyanzhao.ssm.blog.service;
    
    import com.liuyanzhao.ssm.blog.entity.Link;
    
    import java.util.List;
    
    /**
     *
     * @author 言曌
     * @date 2017/9/4
     */
    public interface LinkService {
    
        /**
         * 获得链接总数
         * 
         * @param status 状态
         * @return 数量
         */
        Integer countLink(Integer status);
    
        /**
         * 获得链接列表
         * 
         * @param status 状态
         * @return 链接列表
         */
        List<Link> listLink(Integer status);
    
        /**
         * 添加链接
         * 
         * @param link 链接
         */
        void insertLink(Link link);
    
        /**
         * 删除链接
         * 
         * @param id 链接ID
         */
        void deleteLink(Integer id);
    
        /**
         * 更新链接
         * 
         * @param link 链接
         */
        void updateLink(Link link);
    
        /**
         * 根据id查询链接
         * 
         * @param id 链接ID
         * @return 链接
         */
        Link getLinkById(Integer id);
    
    }
    
  2. com.liuyanzhao.ssm.blog.service.impl.LinkServiceImpl

    package com.liuyanzhao.ssm.blog.service.impl;
    
    import com.liuyanzhao.ssm.blog.entity.Link;
    import com.liuyanzhao.ssm.blog.mapper.LinkMapper;
    import com.liuyanzhao.ssm.blog.service.LinkService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    
    import java.util.List;
    
    /**
     *
     * @author 言曌
     * @date 2017/9/4
     */
    @Service
    public class LinkServiceImpl implements LinkService {
    	
    	@Autowired
    	private LinkMapper linkMapper;
    
        /**
         * 获得链接总数
         * 
         * @param status 状态
         * @return 数量
         */
    	@Override
    	public Integer countLink(Integer status)  {
    		return linkMapper.countLink(status);
    	}
        
    	/**
         * 获得链接列表
         * 
         * @param status 状态
         * @return 链接列表
         */
    	@Override
    	public List<Link> listLink(Integer status)  {
    		return linkMapper.listLink(status);
    	}
    
        /**
         * 添加链接
         * 
         * @param link 链接
         */
    	@Override
    	public void insertLink(Link link)  {
    		linkMapper.insert(link);
    	}
    
        /**
         * 删除链接
         * 
         * @param id 链接ID
         */
    	@Override
    	public void deleteLink(Integer id)  {
    		linkMapper.deleteById(id);
    	}
    
        /**
         * 更新链接
         * 
         * @param link 链接
         */
    	@Override
    	public void updateLink(Link link)  {
    		linkMapper.update(link);
    	}
    
        /**
         * 根据id查询链接
         * 
         * @param id 链接ID
         * @return 链接
         */
    	@Override
    	public Link getLinkById(Integer id)  {
    		return linkMapper.getLinkById(id);
    	}
    
    }
    
2.7.5 MenuService
  1. com.liuyanzhao.ssm.blog.service.MenuService

    package com.liuyanzhao.ssm.blog.service;
    
    import com.liuyanzhao.ssm.blog.entity.Menu;
    
    import java.util.List;
    
     /**
      * @author liuyanzhao
      */
     public interface MenuService {
         /**
          * 获得菜单列表
          * 
          * @return 列表
          */
         List<Menu> listMenu() ;
    
         /**
          * 添加菜单项目
          * 
          * @param menu 菜单
          */
         Menu insertMenu(Menu menu) ;
    
         /**
          * 删除菜单项目
          * 
          * @param id 菜单ID
          */
         void deleteMenu(Integer id) ;
    
         /**
          * 更新菜单项目
          * 
          * @param menu 菜单
          */
         void updateMenu(Menu menu) ;
    
         /**
          * 根据id获得菜单项目信息
          * 
          * @param id 菜单ID
          * @return 菜单
          */
         Menu getMenuById(Integer id) ;
    }
    
  2. com.liuyanzhao.ssm.blog.service.impl.MenuServiceImpl

    package com.liuyanzhao.ssm.blog.service.impl;
    
    import com.liuyanzhao.ssm.blog.entity.Menu;
    import com.liuyanzhao.ssm.blog.mapper.MenuMapper;
    import com.liuyanzhao.ssm.blog.service.MenuService;
    import org.springframework.beans.factory.annotation.Autowired;
    
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    /**
     * @author liuyanzhao
     */
    @Service
    public class MenuServiceImpl implements MenuService {
    
    
        @Autowired
        private MenuMapper menuMapper;
    
        /**
          * 获得菜单列表
          * 
          * @return 列表
          */
        @Override
        public List<Menu> listMenu() {
            List<Menu> menuList = menuMapper.listMenu();
            return menuList;
        }
    
        /**
          * 添加菜单项目
          * 
          * @param menu 菜单
          */
        @Override
        public Menu insertMenu(Menu menu) {
            menuMapper.insert(menu);
            return menu;
        }
    
        /**
          * 删除菜单项目
          * 
          * @param id 菜单ID
          */
        @Override
        public void deleteMenu(Integer id) {
            menuMapper.deleteById(id);
        }
    
        /**
          * 更新菜单项目
          * 
          * @param menu 菜单
          */
        @Override
        public void updateMenu(Menu menu) {
            menuMapper.update(menu);
        }
    
        /**
          * 根据id获得菜单项目信息
          * 
          * @param id 菜单ID
          * @return 菜单
          */
        @Override
        public Menu getMenuById(Integer id) {
            return menuMapper.getMenuById(id);
        }
    }
    
2.7.6 NoticeService
  1. com.liuyanzhao.ssm.blog.service.NoticeService

    package com.liuyanzhao.ssm.blog.service;
    
    import com.liuyanzhao.ssm.blog.entity.Notice;
    
    import java.util.List;
    
    /**
     * @author liuyanzhao
     */
    public interface NoticeService {
    
    
        /**
         * 获得公告列表
         * 
         * @param status 状态
         * @return 列表
         */
        List<Notice> listNotice(Integer status);
    
        /**
         * 添加公告
         * 
         * @param notice 公告
         */
        void insertNotice(Notice notice);
    
        /**
         * 删除公告
         * 
         * @param id
         */
        void deleteNotice(Integer id);
    
        /**
         * 更新公告
         * 
         * @param notice
         */
        void updateNotice(Notice notice);
    
        /**
         * 根据id查询公告
         * 
         * @param id ID
         * @return 公告
         */
        Notice getNoticeById(Integer id);
    
    }
    
  2. com.liuyanzhao.ssm.blog.service.impl.NoticeServiceImpl

    package com.liuyanzhao.ssm.blog.service.impl;
    
    import com.liuyanzhao.ssm.blog.entity.Notice;
    import com.liuyanzhao.ssm.blog.mapper.NoticeMapper;
    import com.liuyanzhao.ssm.blog.service.NoticeService;
    import org.springframework.beans.factory.annotation.Autowired;
    
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    /**
     * @author liuyanzhao
     */
    @Service
    public class NoticeServiceImpl implements NoticeService {
    
        @Autowired
        private NoticeMapper noticeMapper;
    
        /**
         * 获得公告列表
         * 
         * @param status 状态
         * @return 列表
         */
        @Override
        public List<Notice> listNotice(Integer status)  {
            return noticeMapper.listNotice(status);
        }
    
        /**
         * 添加公告
         * 
         * @param notice 公告
         */
        @Override
        public void insertNotice(Notice notice)  {
            noticeMapper.insert(notice);
        }
    
        /**
         * 删除公告
         * 
         * @param id
         */
        @Override
        public void deleteNotice(Integer id)  {
            noticeMapper.deleteById(id);
        }
    
        /**
         * 更新公告
         * 
         * @param notice
         */
        @Override
        public void updateNotice(Notice notice)  {
            noticeMapper.update(notice);
        }
    
        /**
         * 根据id查询公告
         * 
         * @param id ID
         * @return 公告
         */
        @Override
        public Notice getNoticeById(Integer id)  {
            return noticeMapper.getNoticeById(id);
        }
    
    }
    
2.7.7 OptionsService
  1. com.liuyanzhao.ssm.blog.service.OptionsService

    package com.liuyanzhao.ssm.blog.service;
    
    import com.liuyanzhao.ssm.blog.entity.Options;
    
    
    /**
     *
     * @author 言曌
     * @date 2017/9/7
     */
    public interface OptionsService {
        /**
         * 获得基本信息
         *
         * @return 系统设置
         */
        Options getOptions();
    
        /**
         * 新建基本信息
         * 
         * @param options 系统设置
         */
        void insertOptions(Options options);
    
        /**
         * 更新基本信息
         * 
         * @param options 系统设置
         */
        void updateOptions(Options options);
    }
    
  2. com.liuyanzhao.ssm.blog.service.impl.OptionsServiceImpl

    package com.liuyanzhao.ssm.blog.service.impl;
    
    import com.liuyanzhao.ssm.blog.entity.Options;
    import com.liuyanzhao.ssm.blog.mapper.OptionsMapper;
    import com.liuyanzhao.ssm.blog.service.OptionsService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.cache.annotation.CacheEvict;
    import org.springframework.cache.annotation.Cacheable;
    import org.springframework.stereotype.Service;
    
    /**
     *
     * @author 言曌
     * @date 2017/9/7
     */
    @Service
    public class OptionsServiceImpl implements OptionsService {
    
    
        @Autowired
        private OptionsMapper optionsMapper;
    
        /**
         * 获得基本信息
         *
         * @return 系统设置
         */
        @Override
        @Cacheable(value = "default", key = "'options'")
        public Options getOptions() {
            return optionsMapper.getOptions();
        }
    
        /**
         * 新建基本信息
         * 
         * @param options 系统设置
         */
        @Override
        @CacheEvict(value = "default", key = "'options'")
        public void insertOptions(Options options) {
            optionsMapper.insert(options);
        }
    
        /**
         * 更新基本信息
         * 
         * @param options 系统设置
         */
        @Override
        @CacheEvict(value = "default", key = "'options'")
        public void updateOptions(Options options) {
            optionsMapper.update(options);
        }
    }
    
2.7.8 PageService
  1. com.liuyanzhao.ssm.blog.service.PageService

    package com.liuyanzhao.ssm.blog.service;
    
    import com.liuyanzhao.ssm.blog.entity.Page;
    
    import java.util.List;
    
    /**
     *
     * @author 言曌
     * @date 2017/9/7
     */
    public interface PageService {
        /**
         * 获得页面列表
         *
         * @param status 状态
         * @return 列表
         */
        List<Page> listPage(Integer status);
    
        /**
         * 根据页面key获得页面
         * 
         * @param status 状态
         * @param key 别名
         * @return 页面
         */
        Page getPageByKey(Integer status, String key);
    
        /**
         * 根据id获取页面
         * 
         * @param id 页面ID
         * @return 页面
         */
        Page getPageById(Integer id);
    
        /**
         * 添加页面
         * 
         * @param page 页面
         */
        void insertPage(Page page);
    
        /**
         * 删除页面
         * 
         * @param id 页面ID
         */
        void deletePage(Integer id);
    
        /**
         * 编辑页面
         * 
         * @param page 分页
         */
        void updatePage(Page page);
    }
    
  2. com.liuyanzhao.ssm.blog.service.impl.PageServiceImpl

    package com.liuyanzhao.ssm.blog.service.impl;
    
    import com.liuyanzhao.ssm.blog.entity.Page;
    import com.liuyanzhao.ssm.blog.mapper.PageMapper;
    import com.liuyanzhao.ssm.blog.service.PageService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    
    import java.util.List;
    
    /**
     * @author 言曌
     * @date 2017/9/7
     */
    @Service
    public class PageServiceImpl implements PageService {
    
        @Autowired
        private PageMapper pageMapper;
    
        /**
         * 根据页面key获得页面
         * 
         * @param status 状态
         * @param key 别名
         * @return 页面
         */
        @Override
        public Page getPageByKey(Integer status, String key) {
            return pageMapper.getPageByKey(status, key);
        }
    
        /**
         * 根据id获取页面
         * 
         * @param id 页面ID
         * @return 页面
         */
        @Override
        public Page getPageById(Integer id) {
            return pageMapper.getPageById(id);
        }
    
        /**
         * 获得页面列表
         *
         * @param status 状态
         * @return 列表
         */
        @Override
        public List<Page> listPage(Integer status) {
            return pageMapper.listPage(status);
        }
    
    
        /**
         * 添加页面
         * 
         * @param page 页面
         */
        @Override
        public void insertPage(Page page) {
            pageMapper.insert(page);
        }
    
        /**
         * 删除页面
         * 
         * @param id 页面ID
         */
        @Override
        public void deletePage(Integer id) {
            pageMapper.deleteById(id);
        }
    
        /**
         * 编辑页面
         * 
         * @param page 分页
         */
        @Override
        public void updatePage(Page page) {
            pageMapper.update(page);
        }
    }
    
2.7.9 TagService
  1. com.liuyanzhao.ssm.blog.service.TagService

    package com.liuyanzhao.ssm.blog.service;
    
    import com.liuyanzhao.ssm.blog.entity.Tag;
    
    
    import java.util.List;
    
    /**
     *
     * @author 言曌
     * @date 2017/9/2
     */
    public interface TagService {
    
    	/**
    	 * 获得标签总数
    	 *
    	 * @return 数量
    	 */
    	Integer countTag() ;
    
    	/**
    	 * 获得标签列表
    	 *
    	 * @return 标签列表
    	 */
    	List<Tag> listTag() ;
    
    	/**
    	 * 获得标签列表
    	 *
    	 * @return 标签列表
    	 */
    	List<Tag> listTagWithCount() ;
    
    	/**
    	 * 根据id获得标签信息
    	 *
    	 * @param id 标签ID
    	 * @return 标签
    	 */
    	Tag getTagById(Integer id) ;
    
    	/**
    	 * 添加标签
    	 *
    	 * @param tag 标签
    	 * @return 标签
    	 */
    	Tag insertTag(Tag tag) ;
    
    	/**
    	 * 修改标签
    	 *
    	 * @param tag 标签
    	 */
    	void updateTag(Tag tag) ;
    
    	/**
    	 * 删除标签
    	 *
    	 * @param id 标签iD
    	 */
        void deleteTag(Integer id) ;
    
    	/**
    	 * 根据标签名获取标签
    	 *
    	 * @param name 标签名称
    	 * @return 标签
    	 */
    	Tag getTagByName(String name) ;
    
    	/**
    	 * 根据文章ID获得标签
    	 *
    	 * @param articleId 文章ID
    	 * @return 标签列表
    	 */
    	List<Tag> listTagByArticleId(Integer articleId);
    
    }
    
  2. com.liuyanzhao.ssm.blog.service.impl.TagServiceImpl

    package com.liuyanzhao.ssm.blog.service.impl;
    
    import com.liuyanzhao.ssm.blog.mapper.ArticleTagRefMapper;
    import com.liuyanzhao.ssm.blog.mapper.TagMapper;
    import com.liuyanzhao.ssm.blog.entity.Tag;
    import com.liuyanzhao.ssm.blog.service.TagService;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    import org.springframework.transaction.interceptor.TransactionAspectSupport;
    
    import java.util.List;
    
    /**
     * @author 言曌
     * @date 2017/9/2
     */
    @Service
    @Slf4j
    public class TagServiceImpl implements TagService {
    
        @Autowired
        private TagMapper tagMapper;
    
        @Autowired
        private ArticleTagRefMapper articleTagRefMapper;
    
        /**
    	 * 获得标签总数
    	 *
    	 * @return 数量
    	 */
        @Override
        public Integer countTag() {
            return tagMapper.countTag();
        }
    
        /**
    	 * 获得标签列表
    	 *
    	 * @return 标签列表
    	 */
        @Override
        public List<Tag> listTag() {
            List<Tag> tagList = null;
            try {
                tagList = tagMapper.listTag();
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获得所有标签失败, cause:{}", e);
            }
            return tagList;
        }
    
        /**
    	 * 获得标签列表
    	 *
    	 * @return 标签列表
    	 */
        @Override
        public List<Tag> listTagWithCount() {
            List<Tag> tagList = null;
            try {
                tagList = tagMapper.listTag();
                for (int i = 0; i < tagList.size(); i++) {
                    Integer count = articleTagRefMapper.countArticleByTagId(tagList.get(i).getTagId());
                    tagList.get(i).setArticleCount(count);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.error("获得所有标签失败, cause:{}", e);
            }
            return tagList;
        }
    
        /**
    	 * 根据id获得标签信息
    	 *
    	 * @param id 标签ID
    	 * @return 标签
    	 */
        @Override
        public Tag getTagById(Integer id) {
            Tag tag = null;
            try {
                tag = tagMapper.getTagById(id);
            } catch (Exception e) {            e.printStackTrace();
                log.error("根据ID获得标签失败, id:{}, cause:{}", id, e);
            }
            return tag;
        }
    
        /**
    	 * 添加标签
    	 *
    	 * @param tag 标签
    	 * @return 标签
    	 */
        @Override
        public Tag insertTag(Tag tag) {
            try {
                tagMapper.insert(tag);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("添加标签失败, tag:{}, cause:{}", tag, e);
            }
            return tag;
        }
    
        /**
    	 * 修改标签
    	 *
    	 * @param tag 标签
    	 */
        @Override
        public void updateTag(Tag tag) {
            try {
                tagMapper.update(tag);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("更新标签失败, tag:{}, cause:{}", tag, e);
            }
        }
    
        /**
    	 * 删除标签
    	 *
    	 * @param id 标签iD
    	 */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void deleteTag(Integer id) {
            try {
                tagMapper.deleteById(id);
                articleTagRefMapper.deleteByTagId(id);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("删除标签失败, id:{}, cause:{}", id, e);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            }
    
        }
    
        /**
    	 * 根据标签名获取标签
    	 *
    	 * @param name 标签名称
    	 * @return 标签
    	 */
        @Override
        public Tag getTagByName(String name) {
            Tag tag = null;
            try {
                tag = tagMapper.getTagByName(name);
            } catch (Exception e) {            e.printStackTrace();
                log.error("根据名称获得标签, name:{}, cause:{}", name, e);
            }
            return tag;
        }
    
        /**
    	 * 根据文章ID获得标签
    	 *
    	 * @param articleId 文章ID
    	 * @return 标签列表
    	 */
        @Override
        public List<Tag> listTagByArticleId(Integer articleId) {
            List<Tag> tagList = null;
            try {
                tagList = articleTagRefMapper.listTagByArticleId(articleId);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("根据文章ID获得标签失败,articleId:{}, cause:{}", articleId, e);
            }
            return tagList;
        }
    
    }
    
2.7.10 UserService
  1. com.liuyanzhao.ssm.blog.service.UserService

    package com.liuyanzhao.ssm.blog.service;
    
    import com.liuyanzhao.ssm.blog.entity.User;
    
    import java.util.List;
    
    /**
     * @author 言曌
     * @date 2017/8/24
     */
    
    public interface UserService {
        /**
         * 获得用户列表
         *
         * @return 用户列表
         */
        List<User> listUser();
    
        /**
         * 根据id查询用户信息
         *
         * @param id 用户ID
         * @return 用户
         */
        User getUserById(Integer id);
    
        /**
         * 修改用户信息
         *
         * @param user 用户
         */
        void updateUser(User user);
    
        /**
         * 删除用户
         *
         * @param id 用户ID
         */
        void deleteUser(Integer id);
    
        /**
         * 添加用户
         *
         * @param user 用户
         * @return 用户
         */
        User insertUser(User user);
    
        /**
         * 根据用户名和邮箱查询用户
         *
         * @param str 用户名或Email
         * @return 用户
         */
        User getUserByNameOrEmail(String str);
    
        /**
         * 根据用户名查询用户
         *
         * @param name 用户名
         * @return 用户
         */
        User getUserByName(String name);
    
        /**
         * 根据邮箱查询用户
         *
         * @param email Email
         * @return 用户
         */
        User getUserByEmail(String email);
    }
    
  2. com.liuyanzhao.ssm.blog.service.impl.UserServiceImpl

    package com.liuyanzhao.ssm.blog.service.impl;
    
    import com.liuyanzhao.ssm.blog.mapper.ArticleMapper;
    import com.liuyanzhao.ssm.blog.mapper.CommentMapper;
    import com.liuyanzhao.ssm.blog.mapper.UserMapper;
    import com.liuyanzhao.ssm.blog.entity.User;
    import com.liuyanzhao.ssm.blog.service.ArticleService;
    import com.liuyanzhao.ssm.blog.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    
    import java.util.Date;
    import java.util.List;
    
    /**
     * 用户管理
     *
     * @author 言曌
     * @date 2017/8/24
     */
    @Service
    public class UserServiceImpl implements UserService {
    
        @Autowired
        private UserMapper userMapper;
    
        @Autowired
        private ArticleMapper articleMapper;
    
        @Autowired
        private ArticleService articleService;
        @Autowired
        private CommentMapper commentMapper;
    
        /**
         * 获得用户列表
         *
         * @return 用户列表
         */
        @Override
        public List<User> listUser() {
            List<User> userList = userMapper.listUser();
            for (int i = 0; i < userList.size(); i++) {
                Integer articleCount = articleMapper.countArticleByUser(userList.get(i).getUserId());
                userList.get(i).setArticleCount(articleCount);
            }
            return userList;
        }
    
        /**
         * 根据id查询用户信息
         *
         * @param id 用户ID
         * @return 用户
         */
        @Override
        public User getUserById(Integer id) {
            return userMapper.getUserById(id);
        }
    
        /**
         * 修改用户信息
         *
         * @param user 用户
         */
        @Override
        public void updateUser(User user) {
            userMapper.update(user);
        }
    
        /**
         * 删除用户
         *
         * @param id 用户ID
         */
        @Override
        @Transactional(rollbackFor = Exception.class)
        public void deleteUser(Integer id) {
            // 删除用户
            userMapper.deleteById(id);
            // 删除评论
            commentMapper.deleteByUserId(id);
            // 删除文章
            List<Integer> articleIds = articleMapper.listArticleIdsByUserId(id);
            if (articleIds != null && articleIds.size() > 0) {
                for (Integer articleId : articleIds) {
                    articleService.deleteArticle(articleId);
                }
            }
        }
    
        /**
         * 添加用户
         *
         * @param user 用户
         * @return 用户
         */
        @Override
        public User insertUser(User user) {
            user.setUserRegisterTime(new Date());
            userMapper.insert(user);
            return user;
        }
    
        /**
         * 根据用户名和邮箱查询用户
         *
         * @param str 用户名或Email
         * @return 用户
         */
        @Override
        public User getUserByNameOrEmail(String str) {
            return userMapper.getUserByNameOrEmail(str);
        }
    
        /**
         * 根据用户名查询用户
         *
         * @param name 用户名
         * @return 用户
         */
        @Override
        public User getUserByName(String name) {
            return userMapper.getUserByName(name);
        }
    
        /**
         * 根据邮箱查询用户
         *
         * @param email Email
         * @return 用户
         */
        @Override
        public User getUserByEmail(String email) {
            return userMapper.getUserByEmail(email);
        }
    
    }
    
2.8 controller表示层

├─controller
│ ├─admin
│ │ AdminController.java
│ │ BackArticleController.java
│ │ BackCategoryController.java
│ │ BackCommentController.java
│ │ BackLinkController.java
│ │ BackMenuController.java
│ │ BackNoticeController.java
│ │ BackOptionsController.java
│ │ BackPageController.java
│ │ BackTagController.java
│ │ BackUserController.java
│ │ UploadFileController.java
│ │
│ └─home
│ ArticleController.java
│ CategoryController.java
│ CommentController.java
│ IndexController.java
│ LinkController.java
│ NoticeController.java
│ PageController.java
│ TagController.java

后台功能
AdminController
  • 后台首页

    • /admin
    • 用户查询自己的文章, 管理员查询所有的
    • 文章列表 5条
    • 评论列表 5条
    • Admin/index
  • 登录页面显示

    • /login
    • Admin/login
  • 注册页面显示

    • /register
    • Admin/register
  • 登录验证

    • /loginVerify
    • @ResponseBody
    • 登录信息
      • 用户名和密码
      • 用户状态
    • 登录检测
      • 用户名无效!
      • 密码错误!
      • 账号已禁用!
    • 成功可以选择cookie有效期
    • 更新用户最后一次登录时间和IP
    • String
  • 注册验证

    • /registerSubmit
    • 注册信息
      • 用户名
      • 昵称
      • email
      • 密码
    • 注册检测
      • 用户名已存在
      • 电子邮箱已存在
    • 新增用户
    • @ResponseBody
  • 退出登录

    • /admin/logout
    • 删除用户会话信息,将会话设置为invalidate
    • redirect:/login
  • 基本信息页面显示

    • /admin/profile
    • 获取用户信息存入modelAndView
    • modelAndView: Admin/User/profile
  • 编辑个人信息页面显示

    • /admin/profile/edit
    • 获取用户信息存入modelAndView
    • modelAndView: Admin/User/editProfile
  • 编辑用户提交

    • /admin/profile/save
    • 更新用户信息
    • redirect:/admin/profile
BackArticleController

/admin/article

  • 后台文章列表显示
    • “”
    • 分页显示
    • 用户查询自己的文章, 管理员查询所有的
    • Admin/Article/index
  • 后台添加文章页面显示
    • /insert
    • 获取分类列表和标签列表
    • Admin/Article/insert
  • 后台添加文章提交操作
    • /insertSubmit
    • 配置文章信息后插入数据库
      • 用户ID
      • 标题
      • 文章摘要
        • 字符串长度小于150个
      • 缩略图
      • 内容
      • 状态
      • 分类列表
      • 标签列表
    • redirect:/admin/article
  • 删除文章
    • /delete/{id}
    • @param id 文章ID
    • 获取文章
    • 如果不是管理员,访问其他用户的数据,则跳转403
    • 删除文章信息
    • void
  • 编辑文章页面显示
    • /edit/{id}
    • @param id
    • 获取文章信息,若不存在则跳转404
    • 如果不是管理员,访问其他用户的数据,则跳转403
    • 上传文章信息、全部分类信息、全部标签信息
    • Admin/Article/edit
  • 编辑文章提交
    • /editSubmit
    • 获取文章信息,若不存在跳转404
    • 如果不是管理员,访问其他用户的数据,则跳转403
    • 更新文章信息后插入数据库
      • 用户ID
      • 标题
      • 文章摘要
        • 字符串长度小于150个
      • 缩略图
      • 内容
      • 状态
      • 分类列表
      • 标签列表
    • redirect:/admin/article
  • 后台添加文章草稿提交操作
    • /insertDraftSubmit

    • 配置文章信息后插入数据库

      • 用户ID
      • 标题
      • 文章摘要
        • 字符串长度小于150个
      • 缩略图
      • 内容
      • 状态
      • 分类列表
      • 标签列表
    • redirect:/admin

BackCategoryController

/admin/category

  • 后台分类列表显示
    • “”
    • 获取所有分类并计数
    • modelandview:Admin/Category/index
  • 后台添加分类提交
    • /insertSubmit
    • 添加分类
    • redirect:/admin/category
  • 删除分类
    • /delete/{id}
    • @param id
    • 获取该分类具有的文章数,禁止删除有文章的分类
    • 若分类中文章数为0,则删除该分类
    • redirect:/admin/category
  • 编辑分类页面显示
    • /edit/{id}
    • @param id
    • 获取分类
    • 获取分类列表并计数
    • modelAndView:Admin/Category/edit
  • 编辑分类提交
    • /editSubmit
    • @param category 分类
    • 更新分类信息
    • redirect:/admin/category
BackCommentController

/admin/comment

  • 评论页面-我发送的评论
    • “”
    • @param pageIndex 页码
    • @param pageSize 页大小
    • 用户查询自己的文章, 管理员查询所有的
    • 分页处理
    • Admin/Comment/index
  • 评论页面-我收到的评论
    • /receive
    • @param pageIndex 页码
    • @param pageSize 页大小
    • 分页处理
    • Admin/Comment/index
  • 添加评论
    • /insert
    • @ResponseBody
    • 获取用户、文章
    • 添加评论信息并插入数据库
      • 用户ID
      • IP
      • 创建时间
    • 更新评论数
    • void
  • 删除评论
    • /delete/{id}
    • @param id 批量ID
    • 如果不是管理员,访问其他用户的数据,没有权限删除
    • 删除评论及其子评论
    • 更新评论数
    • void
  • 编辑评论页面显示
    • /edit/{id}
    • @param id
    • 没有权限操作,只有管理员可以操作,没有权限则跳转403
    • 获取评论
    • Admin/Comment/edit
  • 编辑评论提交
    • /editSubmit
    • @param comment
    • 没有权限操作,只有管理员可以操作,没有权限则跳转403
    • 更新评论信息
    • redirect:/admin/comment
  • 回复评论页面显示
    • /reply/{id}
    • @param id
    • 获取评论
    • Admin/Comment/reply
  • 回复评论提交
    • /replySubmit
    • @param request
    • @param comment
    • 获取评论,若不存在则跳转404
    • 设置评论信息,并插入数据库
      • 内容
      • 评论人昵称
      • 评论人email
      • 评论人主页url
      • 创建时间
      • IP
      • 评论人角色(本人、游客)
    • 更新文章评论数
    • redirect:/admin/comment
BackLinkController

/admin/link

  • 后台链接列表显示
    • “”
    • 获取全部链接
    • modelandview:Admin/Link/index
  • 后台添加链接页面显示
    • /insert
    • 获取全部链接
    • modelandview:Admin/Link/insert
  • 后台添加链接页面提交
    • /insertSubmit
    • @param link 链接
    • 增加链接信息,并插入数据库
      • 创建时间
      • 更新时间
      • 链接状态
    • redirect:/admin/link/insert
  • 删除链接
    • /delete/{id}
    • @param id 链接ID
    • 删除链接
    • redirect:/admin/link
  • 编辑链接页面显示
    • /edit/{id}
    • @param id
    • 获取该链接
    • 获取全部链接
    • modelAndView:Admin/Link/edit
  • 编辑链接提交
    • /editSubmit
    • @param link 链接
    • 添加链接信息
      • 更新时间
    • redirect:/admin/link
BackMenuController

/admin/menu

  • 后台菜单列表显示
    • “”
    • 获取全部菜单信息
    • Admin/Menu/index
  • 添加菜单内容提交
    • /insertSubmit
    • @param menu
    • 若没有设置菜单等级,则默认为顶部菜单
    • 菜单信息插入数据库
    • redirect:/admin/menu
  • 删除菜单内容
    • /delete/{id}
    • @param id
    • 删除菜单
    • redirect:/admin/menu
  • 编辑菜单内容显示
    • /edit/{id}
    • @param id
    • 获取该菜单
    • 获取全部菜单列表
    • modelAndView:Admin/Menu/edit
  • 编辑菜单内容提交
    • /editSubmit
    • @param menu
    • 更新菜单信息
    • redirect:/admin/menu
BackNoticeController

/admin/notice

  • 后台公告列表显示
    • “”
    • 获取全部公告信息
    • Admin/Notice/index
  • 添加公告显示
    • /insert
    • Admin/Notice/insert
  • 添加公告提交
    • /insertSubmit
    • @param notice
    • 添加公告信息,并插入数据库
      • 创建时间
      • 更新时间
      • 公告该状态
      • 公告排序
    • redirect:/admin/notice
  • 删除公告
    • /delete/{id}
    • @param id
    • 删除公告
    • redirect:/admin/notice
BackOptionsController

/admin/options

  • 基本信息显示
    • “”
    • 获取基本信息
    • modelAndView:Admin/Options/index
  • 编辑基本信息显示
    • /edit
    • 获取基本信息
    • modelAndView:modelAndView
  • 编辑基本信息提交
    • /editSubmit
    • @param options
    • 如果记录不存在,那就新建,否则更新
    • redirect:/admin/options
BackPageController

/admin/page

  • 后台页面列表显示
    • “”
    • 获取所有页面列表
    • modelAndView:Admin/Page/index
  • 后台添加页面页面显示
    • /insert
    • modelAndView:Admin/Page/insert
  • 后台添加页面提交操作
    • /insertSubmit
    • @param page
    • 判断别名(key)是否存在
    • 若不存在,添加信息
      • 创建时间
      • 更新时间
      • 页面状态设置为正常
    • 插入数据库
    • redirect:/admin/page
  • 删除页面
    • /delete/{id}
    • @param id
    • 调用service删除
    • redirect:/admin/page
  • 编辑页面页面显示
    • /edit/{id}
    • @param id
    • 获取页面信息
    • modelAndView:Admin/Page/edit
  • 编辑页面提交
    • /editSubmit
    • @param page
    • 判断别名是否存在且不是这篇文章
    • 若是同一篇,则设置更新时间,并更新数据库
    • redirect:/admin/page
BackTagController

/admin/tag

  • 后台标签列表显示
    • “”
    • 获取所有标签并计数
    • modelandview:Admin/Tag/index
  • 后台添加标签
    • /insertSubmit
    • @param tag
    • 标签插入数据库
    • redirect:/admin/tag
  • 删除标签
    • /delete/{id}
    • @param id 标签ID
    • 查询该标签关联的文章数,不允许删除仍然有关联的文章
    • 若没有,则删除标签
    • redirect:/admin/tag
  • 编辑标签页面显示
    • /edit/{id}
    • @param id
    • 获取该标签
    • 获取所有标签并计数
    • modelAndView:Admin/Tag/edit
  • 编辑标签提交
    • /editSubmit
    • @param tag
    • 更新标签信息
    • redirect:/admin/tag
BackUserController

管理员视角

/admin/user

  • 后台用户列表显示
    • “”
    • 获取用户信息列表
    • modelandview:Admin/User/index
  • 后台添加用户页面显示
    • /insert
    • modelAndView:Admin/User/insert
  • 检查用户名是否存在
    • /checkUserName
    • @ResponseBody
    • @param request
    • 根据用户名获取用户信息,并用获取用户ID与输入用户ID对比,若不相等,则返回用户名已存在!
    • String
  • 检查Email是否存在
    • /checkUserEmail
    • @ResponseBody
    • @param request
    • 根据email获取用户信息,并用获取用户ID与输入用户ID对比,若不相等,则返回电子邮箱已存在!
    • String
  • 后台添加用户页面提交
    • /insertSubmit
    • @param user
    • 根据用户名获取用户信息
    • 根据用户email获取用户信息
    • 若两个都为空,则添加信息,并插入数据库
      • 注册时间
      • 用户状态
      • 用户角色为一般用户
    • redirect:/admin/user
  • 删除用户
    • /delete/{id}
    • @param id
    • 删除用户
    • redirect:/admin/user
  • 编辑用户页面显示
    • /edit/{id}
    • @param id
    • 获取用户信息
    • modelAndView:Admin/User/edit
  • 编辑用户提交
    • /editSubmit
    • @param user
    • 更新用户信息
    • redirect:/admin/user
UploadFileController

/admin/upload

@Slf4j

@RestController

  • 文件保存目录,物理路径

    • public final String rootPath = "D:\\uploads";
    • public final String allowSuffix = ".bmp.jpg.jpeg.png.gif.pdf.doc.zip.rar.gz";
  • 上传文件

    • /img

    • @param file

      public JsonResult uploadFile(@RequestParam("file") MultipartFile file) {
      
          //1.文件后缀过滤,只允许部分后缀
          //文件的完整名称,如spring.jpeg
          String filename = file.getOriginalFilename();
          //文件名,如spring
          String name = filename.substring(0, filename.indexOf("."));
          //文件后缀,如.jpeg
          String suffix = filename.substring(filename.lastIndexOf("."));
      
          if (allowSuffix.indexOf(suffix) == -1) {
              return new JsonResult().fail("不允许上传该后缀的文件!");
          }
      
      
          //2.创建文件目录
          //创建年月文件夹
          Calendar date = Calendar.getInstance();
          File dateDirs = new File(date.get(Calendar.YEAR)
                  + File.separator + (date.get(Calendar.MONTH) + 1));
      
          //目标文件
          File descFile = new File(rootPath + File.separator + dateDirs + File.separator + filename);
          int i = 1;
          //若文件存在重命名
          String newFilename = filename;
          while (descFile.exists()) {
              newFilename = name + "(" + i + ")" + suffix;
              String parentPath = descFile.getParent();
              descFile = new File(parentPath + File.separator + newFilename);
              i++;
          }
          //判断目标文件所在的目录是否存在
          if (!descFile.getParentFile().exists()) {
              //如果目标文件所在的目录不存在,则创建父目录
              descFile.getParentFile().mkdirs();
          }
      
          //3.存储文件
          //将内存中的数据写入磁盘
          try {
              file.transferTo(descFile);
          } catch (Exception e) {
              e.printStackTrace();
              log.error("上传失败,cause:{}", e);
          }
          //完整的url
          String fileUrl = "/uploads/" + dateDirs + "/" + newFilename;
      
          //4.返回URL
          UploadFileVO uploadFileVO = new UploadFileVO();
          uploadFileVO.setTitle(filename);
          uploadFileVO.setSrc(fileUrl);
          return new JsonResult().ok(uploadFileVO);
      }
      
admin目录下(即后台Controller)
2.8.1 AdminController
  • com.liuyanzhao.ssm.blog.controller.admin.AdminController

    package com.liuyanzhao.ssm.blog.controller.admin;
    
    import com.liuyanzhao.ssm.blog.dto.JsonResult;
    import com.liuyanzhao.ssm.blog.entity.Article;
    import com.liuyanzhao.ssm.blog.entity.Comment;
    import com.liuyanzhao.ssm.blog.entity.User;
    import com.liuyanzhao.ssm.blog.enums.UserRole;
    import com.liuyanzhao.ssm.blog.service.ArticleService;
    import com.liuyanzhao.ssm.blog.service.CommentService;
    import com.liuyanzhao.ssm.blog.service.UserService;
    import org.json.JSONObject;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    import static com.liuyanzhao.ssm.blog.util.MyUtils.getIpAddr;
    
    /**
     * @author liuyanzhao
     */
    @Controller
    public class AdminController {
        @Autowired
        private UserService userService;
    
        @Autowired
        private ArticleService articleService;
    
        @Autowired
        private CommentService commentService;
    
        /**
         * 后台首页
         *
         * @return
         */
        @RequestMapping("/admin")
        public String index(Model model, HttpSession session) {
            User user = (User) session.getAttribute("user");
            Integer userId = null;
            if (!UserRole.ADMIN.getValue().equals(user.getUserRole())) {
                // 用户查询自己的文章, 管理员查询所有的
                userId = user.getUserId();
            }
            //文章列表
            List<Article> articleList = articleService.listRecentArticle(userId, 5);
            model.addAttribute("articleList", articleList);
    
            //评论列表
            List<Comment> commentList = commentService.listRecentComment(userId, 5);
            model.addAttribute("commentList", commentList);
            return "Admin/index";
        }
    
        /**
         * 登录页面显示
         *
         * @return
         */
        @RequestMapping("/login")
        public String
        loginPage() {
            return "Admin/login";
        }
    
    
        /**
         * 登录页面显示
         *
         * @return
         */
        @RequestMapping("/register")
        public String registerPage() {
            return "Admin/register";
        }
    
        /**
         * 登录验证
         *
         * @param request
         * @param response
         * @return
         */
        @RequestMapping(value = "/loginVerify", method = RequestMethod.POST, produces = {"text/plain;charset=UTF-8"})
        @ResponseBody
        public String loginVerify(HttpServletRequest request, HttpServletResponse response) {
            Map<String, Object> map = new HashMap<String, Object>();
    
            String username = request.getParameter("username");
            String password = request.getParameter("password");
            String rememberme = request.getParameter("rememberme");
            User user = userService.getUserByNameOrEmail(username);
            if (user == null) {
                map.put("code", 0);
                map.put("msg", "用户名无效!");
            } else if (!user.getUserPass().equals(password)) {
                map.put("code", 0);
                map.put("msg", "密码错误!");
            } else if (user.getUserStatus() == 0) {
                map.put("code", 0);
                map.put("msg", "账号已禁用!");
            } else {
                //登录成功
                map.put("code", 1);
                map.put("msg", "");
                //添加session
                request.getSession().setAttribute("user", user);
                //添加cookie
                if (rememberme != null) {
                    //创建两个Cookie对象
                    Cookie nameCookie = new Cookie("username", username);
                    //设置Cookie的有效期为3天
                    nameCookie.setMaxAge(60 * 60 * 24 * 3);
                    Cookie pwdCookie = new Cookie("password", password);
                    pwdCookie.setMaxAge(60 * 60 * 24 * 3);
                    response.addCookie(nameCookie);
                    response.addCookie(pwdCookie);
                }
                user.setUserLastLoginTime(new Date());
                user.setUserLastLoginIp(getIpAddr(request));
                userService.updateUser(user);
    
            }
            String result = new JSONObject(map).toString();
            return result;
        }
    
        /**
         * 登录验证
         *
         * @param request
         * @return
         */
        @RequestMapping(value = "/registerSubmit", method = RequestMethod.POST)
        @ResponseBody
        public JsonResult registerSubmit(HttpServletRequest request) {
            String username = request.getParameter("username");
            String nickname = request.getParameter("nickname");
            String email = request.getParameter("email");
            String password = request.getParameter("password");
            User checkUserName = userService.getUserByName(username);
            if (checkUserName != null) {
                return new JsonResult().fail("用户名已存在");
            }
            User checkEmail = userService.getUserByEmail(username);
            if (checkEmail != null) {
                return new JsonResult().fail("电子邮箱已存在");
            }
    
            // 添加用户
            User user = new User();
            user.setUserAvatar("/img/avatar/avatar.png");
            user.setUserName(username);
            user.setUserNickname(nickname);
            user.setUserPass(password);
            user.setUserEmail(email);
            user.setUserStatus(1);
            user.setArticleCount(0);
            user.setUserRole(UserRole.USER.getValue());
            try {
                userService.insertUser(user);
            } catch (Exception e) {
                e.printStackTrace();
                return new JsonResult().fail("系统异常");
            }
            return new JsonResult().ok("注册成功");
        }
    
        /**
         * 退出登录
         *
         * @param session
         * @return
         */
        @RequestMapping(value = "/admin/logout")
        public String logout(HttpSession session) {
            session.removeAttribute("user");
            session.invalidate();
            return "redirect:/login";
        }
    
    
        /**
         * 基本信息页面显示
         *
         * @return
         */
        @RequestMapping(value = "/admin/profile")
        public ModelAndView userProfileView(HttpSession session) {
    
            ModelAndView modelAndView = new ModelAndView();
            User sessionUser = (User) session.getAttribute("user");
            User user = userService.getUserById(sessionUser.getUserId());
            modelAndView.addObject("user", user);
    
            modelAndView.setViewName("Admin/User/profile");
            return modelAndView;
        }
    
        /**
         * 编辑个人信息页面显示
         *
         * @param session
         * @return
         */
        @RequestMapping(value = "/admin/profile/edit")
        public ModelAndView editUserView(HttpSession session) {
            ModelAndView modelAndView = new ModelAndView();
            User loginUser = (User) session.getAttribute("user");
            User user = userService.getUserById(loginUser.getUserId());
            modelAndView.addObject("user", user);
    
            modelAndView.setViewName("Admin/User/editProfile");
            return modelAndView;
        }
    
    
        /**
         * 编辑用户提交
         *
         * @param user
         * @return
         */
        @RequestMapping(value = "/admin/profile/save", method = RequestMethod.POST)
        public String saveProfile(User user, HttpSession session) {
            User dbUser = (User) session.getAttribute("user");
    
            user.setUserId(dbUser.getUserId());
            userService.updateUser(user);
            return "redirect:/admin/profile";
        }
    
    
    }
    
2.8.2 BackArticleController
  • com.liuyanzhao.ssm.blog.controller.admin.BackArticleController

    package com.liuyanzhao.ssm.blog.controller.admin;
    
    import cn.hutool.http.HtmlUtil;
    import com.github.pagehelper.PageInfo;
    import com.liuyanzhao.ssm.blog.dto.ArticleParam;
    import com.liuyanzhao.ssm.blog.dto.JsonResult;
    import com.liuyanzhao.ssm.blog.entity.Article;
    import com.liuyanzhao.ssm.blog.enums.UserRole;
    import com.liuyanzhao.ssm.blog.service.ArticleService;
    import com.liuyanzhao.ssm.blog.service.CategoryService;
    import com.liuyanzhao.ssm.blog.service.TagService;
    
    import com.liuyanzhao.ssm.blog.entity.Category;
    import com.liuyanzhao.ssm.blog.entity.Tag;
    import com.liuyanzhao.ssm.blog.entity.User;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpSession;
    import java.util.ArrayList;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Objects;
    
    
    /**
     * @author liuyanzhao
     */
    @Controller
    @RequestMapping("/admin/article")
    public class BackArticleController {
        @Autowired
        private ArticleService articleService;
    
        @Autowired
        private TagService tagService;
    
        @Autowired
        private CategoryService categoryService;
    
        /**
         * 后台文章列表显示
         *
         * @return modelAndView
         */
        @RequestMapping(value = "")
        public String index(@RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                      @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                      @RequestParam(required = false) String status, 
                      Model model,
                      HttpSession session) {
            HashMap<String, Object> criteria = new HashMap<>(1);
            if (status == null) {
                model.addAttribute("pageUrlPrefix", "/admin/article?pageIndex");
            } else {
                criteria.put("status", status);
                model.addAttribute("pageUrlPrefix", "/admin/article?status=" + status + "&pageIndex");
            }
    
            User user = (User) session.getAttribute("user");
            if (!UserRole.ADMIN.getValue().equals(user.getUserRole())) {
                // 用户查询自己的文章, 管理员查询所有的
                criteria.put("userId", user.getUserId());
            }
            PageInfo<Article> articlePageInfo = articleService.pageArticle(pageIndex, pageSize, criteria);
            model.addAttribute("pageInfo", articlePageInfo);
            return "Admin/Article/index";
        }
    
    
        /**
         * 后台添加文章页面显示
         *
         * @return
         */
        @RequestMapping(value = "/insert")
        public String insertArticleView(Model model) {
            List<Category> categoryList = categoryService.listCategory();
            List<Tag> tagList = tagService.listTag();
            model.addAttribute("categoryList", categoryList);
            model.addAttribute("tagList", tagList);
            return "Admin/Article/insert";
        }
    
        /**
         * 后台添加文章提交操作
         *
         * @param articleParam
         * @return
         */
        @RequestMapping(value = "/insertSubmit", method = RequestMethod.POST)
        public String insertArticleSubmit(HttpSession session, ArticleParam articleParam) {
            Article article = new Article();
            //用户ID
            User user = (User) session.getAttribute("user");
            if (user != null) {
                article.setArticleUserId(user.getUserId());
            }
            article.setArticleTitle(articleParam.getArticleTitle());
            //文章摘要
            int summaryLength = 150;
            String summaryText = HtmlUtil.cleanHtmlTag(articleParam.getArticleContent());
            if (summaryText.length() > summaryLength) {
                String summary = summaryText.substring(0, summaryLength);
                article.setArticleSummary(summary);
            } else {
                article.setArticleSummary(summaryText);
            }
            article.setArticleThumbnail(articleParam.getArticleThumbnail());
            article.setArticleContent(articleParam.getArticleContent());
            article.setArticleStatus(articleParam.getArticleStatus());
            //填充分类
            List<Category> categoryList = new ArrayList<>();
            if (articleParam.getArticleChildCategoryId() != null) {
                categoryList.add(new Category(articleParam.getArticleParentCategoryId()));
            }
            if (articleParam.getArticleChildCategoryId() != null) {
                categoryList.add(new Category(articleParam.getArticleChildCategoryId()));
            }
            article.setCategoryList(categoryList);
            //填充标签
            List<Tag> tagList = new ArrayList<>();
            if (articleParam.getArticleTagIds() != null) {
                for (int i = 0; i < articleParam.getArticleTagIds().size(); i++) {
                    Tag tag = new Tag(articleParam.getArticleTagIds().get(i));
                    tagList.add(tag);
                }
            }
            article.setTagList(tagList);
    
            articleService.insertArticle(article);
            return "redirect:/admin/article";
        }
    
    
        /**
         * 删除文章
         *
         * @param id 文章ID
         */
        @RequestMapping(value = "/delete/{id}", method = RequestMethod.POST)
        public void deleteArticle(@PathVariable("id") Integer id, HttpSession session) {
            Article dbArticle = articleService.getArticleByStatusAndId(null, id);
            if (dbArticle == null) {
                return;
            }
            User user = (User) session.getAttribute("user");
            // 如果不是管理员,访问其他用户的数据,则跳转403
            if (!Objects.equals(dbArticle.getArticleUserId(), user.getUserId()) && !Objects.equals(user.getUserRole(), UserRole.ADMIN.getValue())) {
                return;
            }
            articleService.deleteArticle(id);
        }
    
    
        /**
         * 编辑文章页面显示
         *
         * @param id
         * @return
         */
        @RequestMapping(value = "/edit/{id}")
        public String editArticleView(@PathVariable("id") Integer id, Model model, HttpSession session) {
    
            Article article = articleService.getArticleByStatusAndId(null, id);
            if (article == null) {
                return "redirect:/404";
            }
            User user = (User) session.getAttribute("user");
            // 如果不是管理员,访问其他用户的数据,则跳转403
            if (!Objects.equals(article.getArticleUserId(), user.getUserId()) && !Objects.equals(user.getUserRole(), UserRole.ADMIN.getValue())) {
                return "redirect:/403";
            }
    
            model.addAttribute("article", article);
    
            List<Category> categoryList = categoryService.listCategory();
            model.addAttribute("categoryList", categoryList);
    
            List<Tag> tagList = tagService.listTag();
            model.addAttribute("tagList", tagList);
    
            return "Admin/Article/edit";
        }
    
    
        /**
         * 编辑文章提交
         *
         * @param articleParam
         * @return
         */
        @RequestMapping(value = "/editSubmit", method = RequestMethod.POST)
        public String editArticleSubmit(ArticleParam articleParam, HttpSession session) {
            Article dbArticle = articleService.getArticleByStatusAndId(null, articleParam.getArticleId());
            if (dbArticle == null) {
                return "redirect:/404";
            }
            User user = (User) session.getAttribute("user");
            // 如果不是管理员,访问其他用户的数据,则跳转403
            if (!Objects.equals(dbArticle.getArticleUserId(), user.getUserId()) && !Objects.equals(user.getUserRole(), UserRole.ADMIN.getValue())) {
                return "redirect:/403";
            }
            Article article = new Article();
            article.setArticleThumbnail(articleParam.getArticleThumbnail());
            article.setArticleId(articleParam.getArticleId());
            article.setArticleTitle(articleParam.getArticleTitle());
            article.setArticleContent(articleParam.getArticleContent());
            article.setArticleStatus(articleParam.getArticleStatus());
            //文章摘要
            int summaryLength = 150;
            String summaryText = HtmlUtil.cleanHtmlTag(article.getArticleContent());
            if (summaryText.length() > summaryLength) {
                String summary = summaryText.substring(0, summaryLength);
                article.setArticleSummary(summary);
            } else {
                article.setArticleSummary(summaryText);
            }
            //填充分类
            List<Category> categoryList = new ArrayList<>();
            if (articleParam.getArticleChildCategoryId() != null) {
                categoryList.add(new Category(articleParam.getArticleParentCategoryId()));
            }
            if (articleParam.getArticleChildCategoryId() != null) {
                categoryList.add(new Category(articleParam.getArticleChildCategoryId()));
            }
            article.setCategoryList(categoryList);
            //填充标签
            List<Tag> tagList = new ArrayList<>();
            if (articleParam.getArticleTagIds() != null) {
                for (int i = 0; i < articleParam.getArticleTagIds().size(); i++) {
                    Tag tag = new Tag(articleParam.getArticleTagIds().get(i));
                    tagList.add(tag);
                }
            }
            article.setTagList(tagList);
            articleService.updateArticleDetail(article);
            return "redirect:/admin/article";
        }
    
        /**
         * 后台添加文章提交操作
         *
         * @param articleParam
         * @return
         */
        @RequestMapping(value = "/insertDraftSubmit", method = RequestMethod.POST)
        public String insertDraftSubmit(HttpSession session, ArticleParam articleParam) {
            Article article = new Article();
            //用户ID
            User user = (User) session.getAttribute("user");
            if (user != null) {
                article.setArticleUserId(user.getUserId());
            }
            article.setArticleTitle(articleParam.getArticleTitle());
            //文章摘要
            int summaryLength = 150;
            String summaryText = HtmlUtil.cleanHtmlTag(articleParam.getArticleContent());
            if (summaryText.length() > summaryLength) {
                String summary = summaryText.substring(0, summaryLength);
                article.setArticleSummary(summary);
            } else {
                article.setArticleSummary(summaryText);
            }
            article.setArticleThumbnail(articleParam.getArticleThumbnail());
            article.setArticleContent(articleParam.getArticleContent());
            article.setArticleStatus(articleParam.getArticleStatus());
            //填充分类
            List<Category> categoryList = new ArrayList<>();
            if (articleParam.getArticleChildCategoryId() != null) {
                categoryList.add(new Category(articleParam.getArticleParentCategoryId()));
            }
            if (articleParam.getArticleChildCategoryId() != null) {
                categoryList.add(new Category(articleParam.getArticleChildCategoryId()));
            }
            article.setCategoryList(categoryList);
            //填充标签
            List<Tag> tagList = new ArrayList<>();
            if (articleParam.getArticleTagIds() != null) {
                for (int i = 0; i < articleParam.getArticleTagIds().size(); i++) {
                    Tag tag = new Tag(articleParam.getArticleTagIds().get(i));
                    tagList.add(tag);
                }
            }
            article.setTagList(tagList);
    
            articleService.insertArticle(article);
            return "redirect:/admin";
        }
    
    }
    
2.8.3 BackCategoryController
  • com.liuyanzhao.ssm.blog.controller.admin.BackCategoryController

    package com.liuyanzhao.ssm.blog.controller.admin;
    
    
    import com.liuyanzhao.ssm.blog.entity.Category;
    
    import com.liuyanzhao.ssm.blog.service.ArticleService;
    import com.liuyanzhao.ssm.blog.service.CategoryService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.ModelAndView;
    
    import java.util.List;
    
    
    /**
     * @author liuyanzhao
     */
    @Controller
    @RequestMapping("/admin/category")
    public class BackCategoryController {
    
        @Autowired
        private ArticleService articleService;
    
    
        @Autowired
        private CategoryService categoryService;
    
        /**
         * 后台分类列表显示
         *
         * @return
         */
        @RequestMapping(value = "")
        public ModelAndView categoryList()  {
            ModelAndView modelandview = new ModelAndView();
            List<Category> categoryList = categoryService.listCategoryWithCount();
            modelandview.addObject("categoryList",categoryList);
            modelandview.setViewName("Admin/Category/index");
            return modelandview;
    
        }
    
    
        /**
         * 后台添加分类提交
         *
         * @param category
         * @return
         */
        @RequestMapping(value = "/insertSubmit",method = RequestMethod.POST)
        public String insertCategorySubmit(Category category)  {
            categoryService.insertCategory(category);
            return "redirect:/admin/category";
        }
    
        /**
         * 删除分类
         *
         * @param id
         * @return
         */
        @RequestMapping(value = "/delete/{id}")
        public String deleteCategory(@PathVariable("id") Integer id)  {
            //禁止删除有文章的分类
            int count = articleService.countArticleByCategoryId(id);
    
            if (count == 0) {
                categoryService.deleteCategory(id);
            }
            return "redirect:/admin/category";
        }
    
        /**
         * 编辑分类页面显示
         *
         * @param id
         * @return
         */
        @RequestMapping(value = "/edit/{id}")
        public ModelAndView editCategoryView(@PathVariable("id") Integer id)  {
            ModelAndView modelAndView = new ModelAndView();
    
            Category category =  categoryService.getCategoryById(id);
            modelAndView.addObject("category",category);
    
            List<Category> categoryList = categoryService.listCategoryWithCount();
            modelAndView.addObject("categoryList",categoryList);
    
            modelAndView.setViewName("Admin/Category/edit");
            return modelAndView;
        }
    
        /**
         * 编辑分类提交
         *
         * @param category 分类
         * @return 重定向
         */
        @RequestMapping(value = "/editSubmit",method = RequestMethod.POST)
        public String editCategorySubmit(Category category)  {
            categoryService.updateCategory(category);
            return "redirect:/admin/category";
        }
    }
    
2.8.4 BackCommentController
  • com.liuyanzhao.ssm.blog.controller.admin.BackCommentController

    package com.liuyanzhao.ssm.blog.controller.admin;
    
    
    import cn.hutool.http.HtmlUtil;
    import com.github.pagehelper.PageInfo;
    import com.liuyanzhao.ssm.blog.dto.JsonResult;
    import com.liuyanzhao.ssm.blog.entity.Article;
    import com.liuyanzhao.ssm.blog.entity.Comment;
    import com.liuyanzhao.ssm.blog.entity.User;
    import com.liuyanzhao.ssm.blog.enums.ArticleStatus;
    import com.liuyanzhao.ssm.blog.enums.Role;
    import com.liuyanzhao.ssm.blog.enums.UserRole;
    import com.liuyanzhao.ssm.blog.util.MyUtils;
    import com.liuyanzhao.ssm.blog.service.ArticleService;
    import com.liuyanzhao.ssm.blog.service.CommentService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    import java.util.*;
    
    
    /**
     * @author liuyanzhao
     */
    @Controller
    @RequestMapping("/admin/comment")
    public class BackCommentController {
    
        @Autowired
        private CommentService commentService;
    
        @Autowired
        private ArticleService articleService;
    
        /**
         * 评论页面
         * 我发送的评论
         *
         * @param pageIndex 页码
         * @param pageSize  页大小
         * @return modelAndView
         */
        @RequestMapping(value = "")
        public String commentList(@RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                          @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                          HttpSession session,
                          Model model) {
            User user = (User) session.getAttribute("user");
            HashMap<String, Object> criteria = new HashMap<>();
            if (!UserRole.ADMIN.getValue().equals(user.getUserRole())) {
                // 用户查询自己的文章, 管理员查询所有的
                criteria.put("userId", user.getUserId());
            }
            PageInfo<Comment> commentPageInfo = commentService.listCommentByPage(pageIndex, pageSize, criteria);
            model.addAttribute("pageInfo", commentPageInfo);
            model.addAttribute("pageUrlPrefix", "/admin/comment?pageIndex");
            return "Admin/Comment/index";
        }
    
    
        /**
         * 评论页面
         * 我收到的评论
         *
         * @param pageIndex 页码
         * @param pageSize  页大小
         * @return modelAndView
         */
        @RequestMapping(value = "/receive")
        public String myReceiveComment(@RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                             @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                             HttpSession session,
                             Model model) {
            User user = (User) session.getAttribute("user");
            PageInfo<Comment> commentPageInfo = commentService.listReceiveCommentByPage(pageIndex, pageSize, user.getUserId());
            model.addAttribute("pageInfo", commentPageInfo);
            model.addAttribute("pageUrlPrefix", "/admin/comment?pageIndex");
            return "Admin/Comment/index";
        }
    
    
        /**
         * 添加评论
         *
         * @param request
         * @param comment
         */
        @RequestMapping(value = "/insert", method = {RequestMethod.POST}, produces = {"text/plain;charset=UTF-8"})
        @ResponseBody
        public void insertComment(HttpServletRequest request, Comment comment, HttpSession session) {
            User user = (User) session.getAttribute("user");
            Article article = articleService.getArticleByStatusAndId(null, comment.getCommentArticleId());
            if (article == null) {
                return;
            }
    
            //添加评论
            comment.setCommentUserId(user.getUserId());
            comment.setCommentIp(MyUtils.getIpAddr(request));
            comment.setCommentCreateTime(new Date());
            commentService.insertComment(comment);
            //更新文章的评论数
            articleService.updateCommentCount(article.getArticleId());
        }
    
        /**
         * 删除评论
         *
         * @param id 批量ID
         */
        @RequestMapping(value = "/delete/{id}")
        public void deleteComment(@PathVariable("id") Integer id, HttpSession session) {
            Comment comment = commentService.getCommentById(id);
            User user = (User) session.getAttribute("user");
            // 如果不是管理员,访问其他用户的数据,没有权限
            if (!Objects.equals(user.getUserRole(), UserRole.ADMIN.getValue()) && !Objects.equals(comment.getCommentUserId(), user.getUserId())) {
                return;
            }
            //删除评论
            commentService.deleteComment(id);
            //删除其子评论
            List<Comment> childCommentList = commentService.listChildComment(id);
            for (int i = 0; i < childCommentList.size(); i++) {
                commentService.deleteComment(childCommentList.get(i).getCommentId());
            }
            //更新文章的评论数
            Article article = articleService.getArticleByStatusAndId(null, comment.getCommentArticleId());
            articleService.updateCommentCount(article.getArticleId());
        }
    
        /**
         * 编辑评论页面显示
         *
         * @param id
         * @return
         */
        @RequestMapping(value = "/edit/{id}")
        public String editCommentView(@PathVariable("id") Integer id, Model model, HttpSession session) {
            // 没有权限操作,只有管理员可以操作
            User user = (User) session.getAttribute("user");
            if (!Objects.equals(user.getUserRole(), UserRole.ADMIN.getValue())) {
                return "redirect:/403";
            }
            Comment comment = commentService.getCommentById(id);
            model.addAttribute("comment", comment);
            return "Admin/Comment/edit";
        }
    
    
        /**
         * 编辑评论提交
         *
         * @param comment
         * @return
         */
        @RequestMapping(value = "/editSubmit", method = RequestMethod.POST)
        public String editCommentSubmit(Comment comment, HttpSession session) {
            User user = (User) session.getAttribute("user");
            // 没有权限操作,只有管理员可以操作
            if (!Objects.equals(user.getUserRole(), UserRole.ADMIN.getValue())) {
                return "redirect:/403";
            }
            commentService.updateComment(comment);
            return "redirect:/admin/comment";
        }
    
    
        /**
         * 回复评论页面显示
         *
         * @param id
         * @return
         */
        @RequestMapping(value = "/reply/{id}")
        public String replyCommentView(@PathVariable("id") Integer id, Model model) {
            Comment comment = commentService.getCommentById(id);
            model.addAttribute("comment", comment);
            return "Admin/Comment/reply";
        }
    
        /**
         * 回复评论提交
         *
         * @param request
         * @param comment
         * @return
         */
        @RequestMapping(value = "/replySubmit", method = RequestMethod.POST)
        public String replyCommentSubmit(HttpServletRequest request, 
                                Comment comment, 
                                HttpSession session) {
            //文章评论数+1
            Article article = articleService.getArticleByStatusAndId(ArticleStatus.PUBLISH.getValue(), comment.getCommentArticleId());
            if (article == null) {
                return "redirect:/404";
            }
            User user = (User) session.getAttribute("user");
            comment.setCommentContent(HtmlUtil.escape(comment.getCommentContent()));
            comment.setCommentAuthorName(user.getUserNickname());
            comment.setCommentAuthorEmail(user.getUserEmail());
            comment.setCommentAuthorUrl(user.getUserUrl());
            article.setArticleCommentCount(article.getArticleCommentCount() + 1);
            articleService.updateArticle(article);
            //添加评论
            comment.setCommentCreateTime(new Date());
            comment.setCommentIp(MyUtils.getIpAddr(request));
            if (Objects.equals(user.getUserId(), article.getArticleUserId())) {
                comment.setCommentRole(Role.OWNER.getValue());
            } else {
                comment.setCommentRole(Role.VISITOR.getValue());
            }
            commentService.insertComment(comment);
            return "redirect:/admin/comment";
        }
    
    }
    
2.8.5 BackLinkController
  • com.liuyanzhao.ssm.blog.controller.admin.BackLinkController

    package com.liuyanzhao.ssm.blog.controller.admin;
    
    
    import com.liuyanzhao.ssm.blog.entity.Link;
    import com.liuyanzhao.ssm.blog.service.LinkService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.ModelAndView;
    
    import java.util.Date;
    import java.util.List;
    
    
    /**
     * @author liuyanzhao
     */
    @Controller
    @RequestMapping("/admin/link")
    public class BackLinkController {
    
        @Autowired
        private LinkService linkService;
    
        /**
         * 后台链接列表显示
         *
         * @return modelAndView
         */
        @RequestMapping(value = "")
        public ModelAndView linkList()  {
            ModelAndView modelandview = new ModelAndView();
    
            List<Link> linkList = linkService.listLink(null);
            modelandview.addObject("linkList",linkList);
    
            modelandview.setViewName("Admin/Link/index");
            return modelandview;
    
        }
    
        /**
         * 后台添加链接页面显示
         *
         * @return modelAndView
         */
        @RequestMapping(value = "/insert")
        public ModelAndView insertLinkView()  {
            ModelAndView modelAndView = new ModelAndView();
    
            List<Link> linkList = linkService.listLink(null);
            modelAndView.addObject("linkList",linkList);
    
            modelAndView.setViewName("Admin/Link/insert");
            return modelAndView;
        }
    
        /**
         * 后台添加链接页面提交
         *
         * @param link 链接
         * @return 响应
         */
        @RequestMapping(value = "/insertSubmit",method = RequestMethod.POST)
        public String insertLinkSubmit(Link link)  {
            link.setLinkCreateTime(new Date());
            link.setLinkUpdateTime(new Date());
            link.setLinkStatus(1);
            linkService.insertLink(link);
            return "redirect:/admin/link/insert";
        }
    
        /**
         * 删除链接
         *
         * @param id 链接ID
         * @return 响应
         */
        @RequestMapping(value = "/delete/{id}")
        public String deleteLink(@PathVariable("id") Integer id)  {
    
            linkService.deleteLink(id);
            return "redirect:/admin/link";
        }
    
        /**
         * 编辑链接页面显示
         *
         * @param id
         * @return modelAndVIew
         */
        @RequestMapping(value = "/edit/{id}")
        public ModelAndView editLinkView(@PathVariable("id") Integer id)  {
            ModelAndView modelAndView = new ModelAndView();
    
            Link linkCustom =  linkService.getLinkById(id);
            modelAndView.addObject("linkCustom",linkCustom);
    
            List<Link> linkList = linkService.listLink(null);
            modelAndView.addObject("linkList",linkList);
    
            modelAndView.setViewName("Admin/Link/edit");
            return modelAndView;
        }
    
    
        /**
         * 编辑链接提交
         *
         * @param link 链接
         * @return 响应
         */
        @RequestMapping(value = "/editSubmit",method = RequestMethod.POST)
        public String editLinkSubmit(Link link)  {
            link.setLinkUpdateTime(new Date());
            linkService.updateLink(link);
            return "redirect:/admin/link";
        }
    }
    
2.8.6 BackMenuController
  • com.liuyanzhao.ssm.blog.controller.admin.BackMenuController

    package com.liuyanzhao.ssm.blog.controller.admin;
    
    import com.liuyanzhao.ssm.blog.entity.Menu;
    import com.liuyanzhao.ssm.blog.enums.MenuLevel;
    import com.liuyanzhao.ssm.blog.service.MenuService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.ModelAndView;
    
    import java.util.List;
    
    /**
     * @author liuyanzhao
     */
    @Controller
    @RequestMapping("/admin/menu")
    public class BackMenuController {
    
        @Autowired
        private MenuService menuService;
    
        /**
         * 后台菜单列表显示
         *
         * @return
         */
        @RequestMapping(value = "")
        public String menuList(Model model)  {
            List<Menu> menuList = menuService.listMenu();
            model.addAttribute("menuList",menuList);
            return "Admin/Menu/index";
        }
    
        /**
         * 添加菜单内容提交
         *
         * @param menu
         * @return
         */
        @RequestMapping(value = "/insertSubmit",method = RequestMethod.POST)
        public String insertMenuSubmit(Menu menu)  {
            if(menu.getMenuOrder() == null) {
                menu.setMenuOrder(MenuLevel.TOP_MENU.getValue());
            }
            menuService.insertMenu(menu);
            return "redirect:/admin/menu";
        }
    
        /**
         * 删除菜单内容
         *
         * @param id
         * @return
         */
        @RequestMapping(value = "/delete/{id}")
        public String deleteMenu(@PathVariable("id") Integer id)  {
            menuService.deleteMenu(id);
            return "redirect:/admin/menu";
        }
    
        /**
         * 编辑菜单内容显示
         *
         * @param id
         * @return
         */
        @RequestMapping(value = "/edit/{id}")
        public ModelAndView editMenuView(@PathVariable("id") Integer id)  {
            ModelAndView modelAndView = new ModelAndView();
    
            Menu menu =  menuService.getMenuById(id);
            modelAndView.addObject("menu",menu);
    
            List<Menu> menuList = menuService.listMenu();
            modelAndView.addObject("menuList",menuList);
    
            modelAndView.setViewName("Admin/Menu/edit");
            return modelAndView;
        }
    
    
        /**
         * 编辑菜单内容提交
         *
         * @param menu
         * @return
         */
        @RequestMapping(value = "/editSubmit",method = RequestMethod.POST)
        public String editMenuSubmit(Menu menu)  {
            menuService.updateMenu(menu);
            return "redirect:/admin/menu";
        }
    
    }
    
2.8.7 BackNoticeController
  • com.liuyanzhao.ssm.blog.controller.admin.BackNoticeController

    package com.liuyanzhao.ssm.blog.controller.admin;
    
    
    import com.liuyanzhao.ssm.blog.entity.Notice;
    import com.liuyanzhao.ssm.blog.enums.NoticeStatus;
    import com.liuyanzhao.ssm.blog.service.NoticeService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    
    import java.util.Date;
    import java.util.List;
    
    
    @Controller
    @RequestMapping("/admin/notice")
    public class BackNoticeController {
    
        @Autowired
        private NoticeService noticeService;
    
        /**
         * 后台公告列表显示
         *
         * @return
         */
        @RequestMapping(value = "")
        public String index(Model model) {
            List<Notice> noticeList = noticeService.listNotice(null);
            model.addAttribute("noticeList", noticeList);
            return "Admin/Notice/index";
    
        }
    
        /**
         * 添加公告显示
         *
         * @return
         */
        @RequestMapping(value = "/insert")
        public String insertNoticeView() {
            return "Admin/Notice/insert";
        }
    
        /**
         * 添加公告提交
         *
         * @param notice
         * @return
         */
        @RequestMapping(value = "/insertSubmit", method = RequestMethod.POST)
        public String insertNoticeSubmit(Notice notice) {
            notice.setNoticeCreateTime(new Date());
            notice.setNoticeUpdateTime(new Date());
            notice.setNoticeStatus(NoticeStatus.NORMAL.getValue());
            notice.setNoticeOrder(1);
            noticeService.insertNotice(notice);
            return "redirect:/admin/notice";
        }
    
        /**
         * 删除公告
         *
         * @param id
         * @return
         */
        @RequestMapping(value = "/delete/{id}")
        public String deleteNotice(@PathVariable("id") Integer id) {
            noticeService.deleteNotice(id);
    
            return "redirect:/admin/notice";
        }
    
        /**
         * 编辑公告页面显示
         *
         * @param id
         * @return
         */
        @RequestMapping(value = "/edit/{id}")
        public String editNoticeView(@PathVariable("id") Integer id, Model model) {
            Notice notice = noticeService.getNoticeById(id);
            model.addAttribute("notice", notice);
            return "Admin/Notice/edit";
        }
    
    
        /**
         * 编辑公告页面显示
         *
         * @param notice
         * @return
         */
        @RequestMapping(value = "/editSubmit", method = RequestMethod.POST)
        public String editNoticeSubmit(Notice notice) {
            notice.setNoticeUpdateTime(new Date());
            noticeService.updateNotice(notice);
            return "redirect:/admin/notice";
        }
        
    }
    
2.8.8 BackOptionsController
  • com.liuyanzhao.ssm.blog.controller.admin.BackOptionsController

    package com.liuyanzhao.ssm.blog.controller.admin;
    
    import com.liuyanzhao.ssm.blog.entity.Options;
    import com.liuyanzhao.ssm.blog.service.OptionsService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.ModelAndView;
    
    
    /**
     * @author liuyanzhao
     */
    @Controller
    @RequestMapping("/admin/options")
    public class BackOptionsController {
    
        @Autowired
        private OptionsService optionsService;
    
    
        /**
         * 基本信息显示
         *
         * @return
         */
        @RequestMapping(value = "")
        public ModelAndView index()  {
            ModelAndView modelAndView = new ModelAndView();
            Options option = optionsService.getOptions();
            modelAndView.addObject("option",option);
    
            modelAndView.setViewName("Admin/Options/index");
            return modelAndView;
        }
    
        /**
         * 编辑基本信息显示
         *
         * @return
         */
        @RequestMapping(value = "/edit")
        public ModelAndView editOptionView()  {
            ModelAndView modelAndView = new ModelAndView();
            Options option = optionsService.getOptions();
            modelAndView.addObject("option",option);
    
            modelAndView.setViewName("Admin/Options/edit");
            return modelAndView;
        }
    
        /**
         * 编辑基本信息提交
         *
         * @param options
         * @return
         */
        @RequestMapping(value = "/editSubmit",method = RequestMethod.POST)
        public String editOptionSubmit(Options options)  {
            //如果记录不存在,那就新建
            Options optionsCustom = optionsService.getOptions();
            if(optionsCustom.getOptionId()==null) {
                optionsService.insertOptions(options);
            } else {
                optionsService.updateOptions(options);
            }
            return "redirect:/admin/options";
        }
    
    }
    
2.8.9 BackPageController
  • com.liuyanzhao.ssm.blog.controller.admin.BackPageController

    package com.liuyanzhao.ssm.blog.controller.admin;
    
    import com.liuyanzhao.ssm.blog.entity.Page;
    import com.liuyanzhao.ssm.blog.enums.PageStatus;
    import com.liuyanzhao.ssm.blog.service.PageService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.ModelAndView;
    
    import java.util.Date;
    import java.util.List;
    import java.util.Objects;
    
    
    /**
     * @author liuyanzhao
     */
    @Controller
    @RequestMapping("/admin/page")
    public class BackPageController {
    
        @Autowired
        private PageService pageService;
    
        /**
         * 后台页面列表显示
         *
         * @return
         */
        @RequestMapping(value = "")
        public ModelAndView index() {
            ModelAndView modelAndView = new ModelAndView();
            List<Page> pageList = pageService.listPage(null);
            modelAndView.addObject("pageList", pageList);
            modelAndView.setViewName("Admin/Page/index");
            return modelAndView;
        }
    
    
        /**
         * 后台添加页面页面显示
         *
         * @return
         */
        @RequestMapping(value = "/insert")
        public ModelAndView insertPageView() {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("Admin/Page/insert");
            return modelAndView;
        }
    
        /**
         * 后台添加页面提交操作
         *
         * @param page
         * @return
         */
        @RequestMapping(value = "/insertSubmit", method = RequestMethod.POST)
        public String insertPageSubmit(Page page) {
    
            //判断别名是否存在
            Page checkPage = pageService.getPageByKey(null, page.getPageKey());
            if (checkPage == null) {
                page.setPageCreateTime(new Date());
                page.setPageUpdateTime(new Date());
                page.setPageStatus(PageStatus.NORMAL.getValue());
                pageService.insertPage(page);
            }
            return "redirect:/admin/page";
        }
    
        /**
         * 删除页面
         *
         * @param id
         * @return
         */
        @RequestMapping(value = "/delete/{id}")
        public String deletePage(@PathVariable("id") Integer id) {
            //调用service批量删除
            pageService.deletePage(id);
            return "redirect:/admin/page";
        }
    
    
        /**
         * 编辑页面页面显示
         *
         * @param id
         * @return
         */
        @RequestMapping(value = "/edit/{id}")
        public ModelAndView editPageView(@PathVariable("id") Integer id) {
            ModelAndView modelAndView = new ModelAndView();
    
            Page page = pageService.getPageById(id);
            modelAndView.addObject("page", page);
    
            modelAndView.setViewName("Admin/Page/edit");
            return modelAndView;
        }
    
    
        /**
         * 编辑页面提交
         *
         * @param page
         * @return
         */
        @RequestMapping(value = "/editSubmit", method = RequestMethod.POST)
        public String editPageSubmit(Page page) {
            Page checkPage = pageService.getPageByKey(null, page.getPageKey());
            //判断别名是否存在且不是这篇文章
            if (Objects.equals(checkPage.getPageId(), page.getPageId())) {
                page.setPageUpdateTime(new Date());
                pageService.updatePage(page);
            }
            return "redirect:/admin/page";
        }
    
    }
    
2.8.10 BackTagController
  • com.liuyanzhao.ssm.blog.controller.admin.BackTagController

    package com.liuyanzhao.ssm.blog.controller.admin;
    
    
    import com.liuyanzhao.ssm.blog.entity.Tag;
    import com.liuyanzhao.ssm.blog.service.ArticleService;
    import com.liuyanzhao.ssm.blog.service.TagService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.servlet.ModelAndView;
    
    import java.util.List;
    
    
    /**
     * @author liuyanzhao
     */
    @Controller
    @RequestMapping("/admin/tag")
    public class BackTagController {
    
        @Autowired
        private ArticleService articleService;
    
        @Autowired
        private TagService tagService;
    
        /**
         * 后台标签列表显示
         * @return
         */
        @RequestMapping(value = "")
        public ModelAndView index()  {
            ModelAndView modelandview = new ModelAndView();
            List<Tag> tagList = tagService.listTagWithCount();
            modelandview.addObject("tagList",tagList);
    
            modelandview.setViewName("Admin/Tag/index");
            return modelandview;
    
        }
    
    
        /**
         * 后台添加分类页面显示
         *
         * @param tag
         * @return
         */
        @RequestMapping(value = "/insertSubmit",method = RequestMethod.POST)
        public String insertTagSubmit(Tag tag)  {
            tagService.insertTag(tag);
            return "redirect:/admin/tag";
        }
    
        /**
         * 删除标签
         *
         * @param id 标签ID
         * @return
         */
        @RequestMapping(value = "/delete/{id}")
        public String deleteTag(@PathVariable("id") Integer id)  {
            Integer count = articleService.countArticleByTagId(id);
            if (count == 0) {
                tagService.deleteTag(id);
            }
            return "redirect:/admin/tag";
        }
    
        /**
         * 编辑标签页面显示
         *
         * @param id
         * @return
         */
        @RequestMapping(value = "/edit/{id}")
        public ModelAndView editTagView(@PathVariable("id") Integer id)  {
            ModelAndView modelAndView = new ModelAndView();
    
            Tag tag =  tagService.getTagById(id);
            modelAndView.addObject("tag",tag);
    
            List<Tag> tagList = tagService.listTagWithCount();
            modelAndView.addObject("tagList",tagList);
    
            modelAndView.setViewName("Admin/Tag/edit");
            return modelAndView;
        }
    
    
        /**
         * 编辑标签提交
         *
         * @param tag
         * @return
         */
        @RequestMapping(value = "/editSubmit",method = RequestMethod.POST)
        public String editTagSubmit(Tag tag)  {
            tagService.updateTag(tag);
            return "redirect:/admin/tag";
        }
    }
    
2.8.11 BackUserController
  • com.liuyanzhao.ssm.blog.controller.admin.BackUserController

    package com.liuyanzhao.ssm.blog.controller.admin;
    
    
    import com.liuyanzhao.ssm.blog.entity.User;
    import com.liuyanzhao.ssm.blog.enums.UserRole;
    import com.liuyanzhao.ssm.blog.service.UserService;
    import org.json.JSONObject;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.List;
    import java.util.Map;
    
    
    /**
     * @author liuyanzhao
     */
    @Controller
    @RequestMapping("/admin/user")
    public class BackUserController {
    
        @Autowired
        private UserService userService;
    
        /**
         * 后台用户列表显示
         *
         * @return
         */
        @RequestMapping(value = "")
        public ModelAndView userList() {
            ModelAndView modelandview = new ModelAndView();
    
            List<User> userList = userService.listUser();
            modelandview.addObject("userList", userList);
    
            modelandview.setViewName("Admin/User/index");
            return modelandview;
    
        }
    
        /**
         * 后台添加用户页面显示
         *
         * @return
         */
        @RequestMapping(value = "/insert")
        public ModelAndView insertUserView() {
            ModelAndView modelAndView = new ModelAndView();
            modelAndView.setViewName("Admin/User/insert");
            return modelAndView;
        }
    
        /**
         * 检查用户名是否存在
         *
         * @param request
         * @return
         */
        @RequestMapping(value = "/checkUserName", method = RequestMethod.POST, produces = {"text/plain;charset=UTF-8"})
        @ResponseBody
        public String checkUserName(HttpServletRequest request) {
            Map<String, Object> map = new HashMap<String, Object>();
            String username = request.getParameter("username");
            User user = userService.getUserByName(username);
            int id = Integer.valueOf(request.getParameter("id"));
            //用户名已存在,但不是当前用户(编辑用户的时候,不提示)
            if (user != null) {
                if (user.getUserId() != id) {
                    map.put("code", 1);
                    map.put("msg", "用户名已存在!");
                }
            } else {
                map.put("code", 0);
                map.put("msg", "");
            }
            String result = new JSONObject(map).toString();
            return result;
        }
    
        /**
         * 检查Email是否存在
         *
         * @param request
         * @return
         */
        @RequestMapping(value = "/checkUserEmail", method = RequestMethod.POST, produces = {"text/plain;charset=UTF-8"})
        @ResponseBody
        public String checkUserEmail(HttpServletRequest request) {
            Map<String, Object> map = new HashMap<String, Object>();
            String email = request.getParameter("email");
            User user = userService.getUserByEmail(email);
            int id = Integer.valueOf(request.getParameter("id"));
            //用户名已存在,但不是当前用户(编辑用户的时候,不提示)
            if (user != null) {
                if (user.getUserId() != id) {
                    map.put("code", 1);
                    map.put("msg", "电子邮箱已存在!");
                }
            } else {
                map.put("code", 0);
                map.put("msg", "");
            }
            String result = new JSONObject(map).toString();
            return result;
        }
    
    
        /**
         * 后台添加用户页面提交
         *
         * @param user
         * @return
         */
        @RequestMapping(value = "/insertSubmit", method = RequestMethod.POST)
        public String insertUserSubmit(User user) {
            User user2 = userService.getUserByName(user.getUserName());
            User user3 = userService.getUserByEmail(user.getUserEmail());
            if (user2 == null && user3 == null) {
                user.setUserRegisterTime(new Date());
                user.setUserStatus(1);
                user.setUserRole(UserRole.USER.getValue());
                userService.insertUser(user);
            }
            return "redirect:/admin/user";
        }
    
        /**
         * 删除用户
         *
         * @param id
         * @return
         */
        @RequestMapping(value = "/delete/{id}")
        public String deleteUser(@PathVariable("id") Integer id) {
            userService.deleteUser(id);
            return "redirect:/admin/user";
        }
    
        /**
         * 编辑用户页面显示
         *
         * @param id
         * @return
         */
        @RequestMapping(value = "/edit/{id}")
        public ModelAndView editUserView(@PathVariable("id") Integer id) {
            ModelAndView modelAndView = new ModelAndView();
    
            User user = userService.getUserById(id);
            modelAndView.addObject("user", user);
    
            modelAndView.setViewName("Admin/User/edit");
            return modelAndView;
        }
    
    
        /**
         * 编辑用户提交
         *
         * @param user
         * @return
         */
        @RequestMapping(value = "/editSubmit", method = RequestMethod.POST)
        public String editUserSubmit(User user) {
            userService.updateUser(user);
            return "redirect:/admin/user";
        }
    
    }
    
2.8.12 UploadFileController
  • com.liuyanzhao.ssm.blog.controller.admin.UploadFileController

    package com.liuyanzhao.ssm.blog.controller.admin;
    
    import com.liuyanzhao.ssm.blog.dto.JsonResult;
    import com.liuyanzhao.ssm.blog.dto.UploadFileVO;
    import lombok.extern.slf4j.Slf4j;
    import org.springframework.web.bind.annotation.*;
    import org.springframework.web.multipart.MultipartFile;
    
    
    import java.io.File;
    import java.io.IOException;
    import java.util.Calendar;
    
    /**
     * @author liuyanzhao
     */
    @Slf4j
    @RestController
    @RequestMapping("/admin/upload")
    public class UploadFileController {
    
        /**
         * 文件保存目录,物理路径
         */
    //    public final String rootPath = "/Users/liuyanzhao/Documents/uploads";
        public final String rootPath = "D:\\uploads";
    
        public final String allowSuffix = ".bmp.jpg.jpeg.png.gif.pdf.doc.zip.rar.gz";
    
        /**
         * 上传文件
         *
         * @param file
         * @return
         * @throws IOException
         */
        @RequestMapping(value = "/img", method = RequestMethod.POST)
        public JsonResult uploadFile(@RequestParam("file") MultipartFile file) {
    
            //1.文件后缀过滤,只允许部分后缀
            //文件的完整名称,如spring.jpeg
            String filename = file.getOriginalFilename();
            //文件名,如spring
            String name = filename.substring(0, filename.indexOf("."));
            //文件后缀,如.jpeg
            String suffix = filename.substring(filename.lastIndexOf("."));
    
            if (allowSuffix.indexOf(suffix) == -1) {
                return new JsonResult().fail("不允许上传该后缀的文件!");
            }
    
    
            //2.创建文件目录
            //创建年月文件夹
            Calendar date = Calendar.getInstance();
            File dateDirs = new File(date.get(Calendar.YEAR)
                    + File.separator + (date.get(Calendar.MONTH) + 1));
    
            //目标文件
            File descFile = new File(rootPath + File.separator + dateDirs + File.separator + filename);
            int i = 1;
            //若文件存在重命名
            String newFilename = filename;
            while (descFile.exists()) {
                newFilename = name + "(" + i + ")" + suffix;
                String parentPath = descFile.getParent();
                descFile = new File(parentPath + File.separator + newFilename);
                i++;
            }
            //判断目标文件所在的目录是否存在
            if (!descFile.getParentFile().exists()) {
                //如果目标文件所在的目录不存在,则创建父目录
                descFile.getParentFile().mkdirs();
            }
    
            //3.存储文件
            //将内存中的数据写入磁盘
            try {
                file.transferTo(descFile);
            } catch (Exception e) {
                e.printStackTrace();
                log.error("上传失败,cause:{}", e);
            }
            //完整的url
            String fileUrl = "/uploads/" + dateDirs + "/" + newFilename;
    
            //4.返回URL
            UploadFileVO uploadFileVO = new UploadFileVO();
            uploadFileVO.setTitle(filename);
            uploadFileVO.setSrc(fileUrl);
            return new JsonResult().ok(uploadFileVO);
        }
    }
    
前台功能
ArticleController
  • 文章详情页显示
    • /article/{articleId}
    • @param articleId 文章ID
    • 获取文章信息,分类,标签,作者,评论,若不存在则跳转404
    • 获取其他信息
      • 用户信息
      • 评论列表
      • 相关分类文章 5篇
      • 猜你喜欢,即浏览数最高的文章 5篇
      • 获取下一篇文章
      • 获取上一篇文章
    • 侧边栏
      • 标签列表显示
      • 获得随机文章 8篇
      • 获得热评文章 8篇
    • Home/Page/articleDetail
  • 点赞增加
    • /article/like/{id}
    • @ResponseBody
    • @param id 文章ID
    • 获取文章,并更新点赞数
    • String
  • 文章访问量数增加
    • /article/view/{id}
    • @ResponseBody
    • @param id 文章ID
    • 获取文章,并更新访问数
    • String
CategoryController
  • 根据分类查询文章
    • /category/{cateId}

    • @param cateId 分类ID

    • @param 分页参数

    • 获取分类信息,若无则跳转404

    • 获取其他信息

      • 文章列表,分页处理
    • 侧边栏

      • 标签列表显示
      • 获得随机文章 8篇
      • 获得热评文章 8篇
    • Home/Page/articleListByCategory

CommentController
  • 添加评论
    • /comment
    • @param request
    • @param comment
    • 判断用户是否登录,若无则提示登录
    • 获取文章信息,若不存在提示文章不存在
    • 添加评论信息,并插入数据库
      • 用户信息
      • 创建时间
      • IP
      • 角色(作者/游客)
      • 评论人头像
      • 评论内容(过滤字符,防止XSS攻击)
      • 评论人昵称
      • 评论人email
      • 评论人主页url
    • 更新评论数
IndexController
  • 主页
    • “/”, “/article”
    • @param 分页参数
    • 获取发布文章列表,并进行分页处理(默认1页10篇)
    • 获取公告列表
    • 获取友情链接列表
    • 侧边栏显示
      • 所有标签
      • 最新的10条评论
    • Home/index
  • 搜索
    • /search
    • @param keywords 搜索关键字
    • @param 分页参数
    • 获取文章列表,并进行分页处理(默认1页10篇)
    • 侧边栏显示
      • 标签列表显示
      • 获得随机文章 8篇
      • 获得热评文章 8篇
      • 最新的10条评论
    • Home/Page/search
  • 未找到跳转404页面
    • /404
    • @param message
    • Home/Error/404
  • 跳转403页面
    • /403
    • @param message
    • Home/Error/403
  • 服务器错误500页面
    • /500
    • @param message
    • Home/Error/500
LinkController
  • 链接查看
    • /applyLink
    • 侧边栏显示
      • 获得热评文章 8篇
    • Home/Page/applyLink
  • 链接提交
    • /applyLinkSubmit
    • @ResponseBody
    • @param link
    • 添加链接信息
      • 状态设置为隐藏
      • 创建时间
      • 更新时间
    • 连接信息插入数据库
    • void
NoticeController
  • 公告详情页显示
    • /notice/{noticeId}
    • @param noticeId
    • 获取公告信息
    • 侧边栏显示
      • 获得热评文章 8篇
    • Home/Page/noticeDetail
PageController
  • 页面详情页面
    • /{key}
    • @param key
    • 获取页面信息,若无则跳转404
    • 侧边栏显示
      • 获得热评文章 8篇
    • Home/Page/page
  • 文章归档页面显示
    • /articleFile
    • 获取所有文章不带内容
    • 侧边栏显示
      • 获得热评文章 8篇
    • Home/Page/articleFile
  • 站点地图显示
    • /map
    • 获取无内容的所有文章
    • 获取所有分类
    • 获取所有标签
    • 侧边栏显示
      • 获得热评文章 10篇
    • Home/Page/siteMap
  • 留言板
    • /message
    • 侧边栏显示
      • 获得热评文章 8篇
    • Home/Page/message
TagController
  • 根据标签查询文章
    • /tag/{tagId}
    • @param tagId 标签ID
    • @param 分页参数(默认1页10篇)
    • 获取标签信息,若无则跳转404
    • 获取相关文章并分页处理
    • 侧边栏
      • 标签列表显示
      • 获得随机文章 8篇
      • 获得热评文章 8篇
    • Home/Page/articleListByTag
home目录下(即前台Controller)
2.8.13 ArticleController
  • com.liuyanzhao.ssm.blog.controller.home.ArticleController

    package com.liuyanzhao.ssm.blog.controller.home;
    
    
    import com.alibaba.fastjson.JSON;
    
    import com.liuyanzhao.ssm.blog.enums.ArticleStatus;
    
    import com.liuyanzhao.ssm.blog.entity.Article;
    import com.liuyanzhao.ssm.blog.entity.Comment;
    import com.liuyanzhao.ssm.blog.entity.Tag;
    import com.liuyanzhao.ssm.blog.entity.User;
    import com.liuyanzhao.ssm.blog.service.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.List;
    
    /**
     * 文章的controller
     *
     * @author 言曌
     * @date 2017/8/24
     */
    @Controller
    public class ArticleController {
    
        @Autowired
        private ArticleService articleService;
    
        @Autowired
        private CommentService commentService;
    
        @Autowired
        private UserService userService;
    
        @Autowired
        private TagService tagService;
    
        @Autowired
        private CategoryService categoryService;
    
        /**
         * 文章详情页显示
         *
         * @param articleId 文章ID
         * @return modelAndView
         */
        @RequestMapping(value = "/article/{articleId}")
        public String getArticleDetailPage(@PathVariable("articleId") Integer articleId, Model model) {
    
            //文章信息,分类,标签,作者,评论
            Article article = articleService.getArticleByStatusAndId(ArticleStatus.PUBLISH.getValue(), articleId);
            if (article == null) {
                return "Home/Error/404";
            }
    
            //用户信息
            User user = userService.getUserById(article.getArticleUserId());
            article.setUser(user);
    
            //文章信息
            model.addAttribute("article", article);
    
            //评论列表
            List<Comment> commentList = commentService.listCommentByArticleId(articleId);
            model.addAttribute("commentList", commentList);
    
            //相关文章
            List<Integer> categoryIds = articleService.listCategoryIdByArticleId(articleId);
            List<Article> similarArticleList = articleService.listArticleByCategoryIds(categoryIds, 5);
            model.addAttribute("similarArticleList", similarArticleList);
    
            //猜你喜欢
            List<Article> mostViewArticleList = articleService.listArticleByViewCount(5);
            model.addAttribute("mostViewArticleList", mostViewArticleList);
    
            //获取下一篇文章
            Article afterArticle = articleService.getAfterArticle(articleId);
            model.addAttribute("afterArticle", afterArticle);
    
            //获取上一篇文章
            Article preArticle = articleService.getPreArticle(articleId);
            model.addAttribute("preArticle", preArticle);
    
            //侧边栏
            //标签列表显示
            List<Tag> allTagList = tagService.listTag();
            model.addAttribute("allTagList", allTagList);
            //获得随机文章
            List<Article> randomArticleList = articleService.listRandomArticle(8);
            model.addAttribute("randomArticleList", randomArticleList);
            //获得热评文章
            List<Article> mostCommentArticleList = articleService.listArticleByCommentCount(8);
            model.addAttribute("mostCommentArticleList", mostCommentArticleList);
    
            return "Home/Page/articleDetail";
        }
    
        /**
         * 点赞增加
         *
         * @param id 文章ID
         * @return 点赞量数量
         */
        @RequestMapping(value = "/article/like/{id}", method = {RequestMethod.POST}, produces = {"text/plain;charset=UTF-8"})
        @ResponseBody
        public String increaseLikeCount(@PathVariable("id") Integer id) {
            Article article = articleService.getArticleByStatusAndId(ArticleStatus.PUBLISH.getValue(), id);
            Integer articleCount = article.getArticleLikeCount() + 1;
            article.setArticleLikeCount(articleCount);
            articleService.updateArticle(article);
            return JSON.toJSONString(articleCount);
        }
    
        /**
         * 文章访问量数增加
         *
         * @param id 文章ID
         * @return 访问量数量
         */
        @RequestMapping(value = "/article/view/{id}", method = {RequestMethod.POST}, produces = {"text/plain;charset=UTF-8"})
        @ResponseBody
        public String increaseViewCount(@PathVariable("id") Integer id) {
            Article article = articleService.getArticleByStatusAndId(ArticleStatus.PUBLISH.getValue(), id);
            Integer articleCount = article.getArticleViewCount() + 1;
            article.setArticleViewCount(articleCount);
            articleService.updateArticle(article);
            return JSON.toJSONString(articleCount);
        }
    
    }
    
2.8.14 CategoryController
  • com.liuyanzhao.ssm.blog.controller.home.CategoryController

    package com.liuyanzhao.ssm.blog.controller.home;
    
    
    import com.github.pagehelper.PageInfo;
    
    import com.liuyanzhao.ssm.blog.enums.ArticleStatus;
    
    
    import com.liuyanzhao.ssm.blog.entity.Article;
    import com.liuyanzhao.ssm.blog.entity.Category;
    import com.liuyanzhao.ssm.blog.entity.Tag;
    import com.liuyanzhao.ssm.blog.service.ArticleService;
    import com.liuyanzhao.ssm.blog.service.CategoryService;
    import com.liuyanzhao.ssm.blog.service.TagService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.HashMap;
    import java.util.List;
    
    
    /**
     * 文章分类目录的controller
     *
     * @author 言曌
     * @date 2017/8/24
     */
    @Controller
    public class CategoryController {
    
        @Autowired
        private CategoryService categoryService;
    
        @Autowired
        private ArticleService articleService;
    
        @Autowired
        private TagService tagService;
    
        /**
         * 根据分类查询文章
         *
         * @param cateId 分类ID
         * @return 模板
         */
        @RequestMapping("/category/{cateId}")
        public String getArticleListByCategory(@PathVariable("cateId") Integer cateId,
                                   @RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                                   @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                               Model model) {
    
            //该分类信息
            Category category = categoryService.getCategoryById(cateId);
            if (category == null) {
                return "redirect:/404";
            }
            model.addAttribute("category", category);
    
            //文章列表
            HashMap<String, Object> criteria = new HashMap<>(2);
            criteria.put("categoryId", cateId);
            criteria.put("status", ArticleStatus.PUBLISH.getValue());
            PageInfo<Article> articlePageInfo = articleService.pageArticle(pageIndex, pageSize, criteria);
            model.addAttribute("pageInfo", articlePageInfo);
    
            //侧边栏
            //标签列表显示
            List<Tag> allTagList = tagService.listTag();
            model.addAttribute("allTagList", allTagList);
            //获得随机文章
            List<Article> randomArticleList = articleService.listRandomArticle(8);
            model.addAttribute("randomArticleList", randomArticleList);
            //获得热评文章
            List<Article> mostCommentArticleList = articleService.listArticleByCommentCount(8);
            model.addAttribute("mostCommentArticleList", mostCommentArticleList);
            model.addAttribute("pageUrlPrefix", "/category/"+cateId+"?pageIndex");
            return "Home/Page/articleListByCategory";
        }
    
    }
    
2.8.15 CommentController
  • com.liuyanzhao.ssm.blog.controller.home.CommentController

    package com.liuyanzhao.ssm.blog.controller.home;
    
    import cn.hutool.http.HtmlUtil;
    import com.liuyanzhao.ssm.blog.dto.JsonResult;
    import com.liuyanzhao.ssm.blog.entity.Article;
    import com.liuyanzhao.ssm.blog.entity.Comment;
    import com.liuyanzhao.ssm.blog.entity.User;
    import com.liuyanzhao.ssm.blog.enums.ArticleStatus;
    import com.liuyanzhao.ssm.blog.enums.Role;
    import com.liuyanzhao.ssm.blog.service.ArticleService;
    import com.liuyanzhao.ssm.blog.service.CommentService;
    import com.liuyanzhao.ssm.blog.util.MyUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.RestController;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpSession;
    import java.util.Date;
    import java.util.Objects;
    
    /**
     * @author 言曌
     * @date 2017/9/10
     */
    
    @Controller
    @RestController
    public class CommentController {
        @Autowired
        private CommentService commentService;
    
        @Autowired
        private ArticleService articleService;
    
        /**
         * 添加评论
         *
         * @param request
         * @param comment
         */
        @RequestMapping(value = "/comment", method = {RequestMethod.POST})
        public JsonResult insertComment(HttpServletRequest request, 
                               Comment comment, 
                               HttpSession session) {
            User user = (User) session.getAttribute("user");
            if (user == null) {
                return new JsonResult().fail("请先登录");
            }
            Article article = articleService.getArticleByStatusAndId(ArticleStatus.PUBLISH.getValue(), comment.getCommentArticleId());
            if (article == null) {
                return new JsonResult().fail("文章不存在");
            }
    
    
            //添加评论
            comment.setCommentUserId(user.getUserId());
            comment.setCommentCreateTime(new Date());
            comment.setCommentIp(MyUtils.getIpAddr(request));
            if (Objects.equals(user.getUserId(), article.getArticleUserId())) {
                comment.setCommentRole(Role.OWNER.getValue());
            } else {
                comment.setCommentRole(Role.VISITOR.getValue());
            }
            comment.setCommentAuthorAvatar(user.getUserAvatar());
    
            //过滤字符,防止XSS攻击
            comment.setCommentContent(HtmlUtil.escape(comment.getCommentContent()));
    
            comment.setCommentAuthorName(user.getUserNickname());
            comment.setCommentAuthorEmail(user.getUserEmail());
            comment.setCommentAuthorUrl(user.getUserUrl());
            try {
                commentService.insertComment(comment);
                //更新文章的评论数
                articleService.updateCommentCount(article.getArticleId());
            } catch (Exception e) {
                e.printStackTrace();
                return new JsonResult().fail();
            }
            return new JsonResult().ok();
        }
    
    }
    
2.8.16 IndexController
  • com.liuyanzhao.ssm.blog.controller.home.IndexController

    package com.liuyanzhao.ssm.blog.controller.home;
    
    import com.github.pagehelper.PageInfo;
    import com.liuyanzhao.ssm.blog.entity.Link;
    
    import com.liuyanzhao.ssm.blog.enums.ArticleStatus;
    import com.liuyanzhao.ssm.blog.enums.LinkStatus;
    import com.liuyanzhao.ssm.blog.enums.NoticeStatus;
    
    import com.liuyanzhao.ssm.blog.entity.*;
    import com.liuyanzhao.ssm.blog.service.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.HashMap;
    import java.util.List;
    
    /**
     * 用户的controller
     *
     * @author 言曌
     * @date 2017/8/24
     */
    @Controller
    public class IndexController {
    
        @Autowired
        private ArticleService articleService;
    
        @Autowired
        private LinkService linkService;
    
        @Autowired
        private NoticeService noticeService;
    
        @Autowired
        private TagService tagService;
    
        @Autowired
        private CommentService commentService;
    
        @RequestMapping(value = {"/", "/article"})
        public String index(@RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                      @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                       Model model) {
            HashMap<String, Object> criteria = new HashMap<>(1);
            criteria.put("status", ArticleStatus.PUBLISH.getValue());
            //文章列表
            PageInfo<Article> articleList = articleService.pageArticle(pageIndex, pageSize, criteria);
            model.addAttribute("pageInfo", articleList);
    
            //公告
            List<Notice> noticeList = noticeService.listNotice(NoticeStatus.NORMAL.getValue());
            model.addAttribute("noticeList", noticeList);
            //友情链接
            List<Link> linkList = linkService.listLink(LinkStatus.NORMAL.getValue());
            model.addAttribute("linkList", linkList);
    
            //侧边栏显示
            //标签列表显示
            List<Tag> allTagList = tagService.listTag();
            model.addAttribute("allTagList", allTagList);
            //最新评论
            List<Comment> recentCommentList = commentService.listRecentComment(null, 10);
            model.addAttribute("recentCommentList", recentCommentList);
            model.addAttribute("pageUrlPrefix", "/article?pageIndex");
            return "Home/index";
        }
    
        @RequestMapping(value = "/search")
        public String search(
                @RequestParam("keywords") String keywords,
                @RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                @RequestParam(required = false, defaultValue = "10") Integer pageSize, 
            	  Model model) {
            //文章列表
            HashMap<String, Object> criteria = new HashMap<>(2);
            criteria.put("status", ArticleStatus.PUBLISH.getValue());
            criteria.put("keywords", keywords);
            PageInfo<Article> articlePageInfo = articleService.pageArticle(pageIndex, pageSize, criteria);
            model.addAttribute("pageInfo", articlePageInfo);
    
            //侧边栏显示
            //标签列表显示
            List<Tag> allTagList = tagService.listTag();
            model.addAttribute("allTagList", allTagList);
            //获得随机文章
            List<Article> randomArticleList = articleService.listRandomArticle(8);
            model.addAttribute("randomArticleList", randomArticleList);
            //获得热评文章
            List<Article> mostCommentArticleList = articleService.listArticleByCommentCount(8);
            model.addAttribute("mostCommentArticleList", mostCommentArticleList);
            //最新评论
            List<Comment> recentCommentList = commentService.listRecentComment(null, 10);
            model.addAttribute("recentCommentList", recentCommentList);
            model.addAttribute("pageUrlPrefix", "/search?keywords=" + keywords + "&pageIndex");
            return "Home/Page/search";
        }
    
        @RequestMapping("/404")
        public String NotFound(@RequestParam(required = false) String message, Model model) {
            model.addAttribute("message", message);
            return "Home/Error/404";
        }
    
    
        @RequestMapping("/403")
        public String Page403(@RequestParam(required = false) String message, Model model) {
            model.addAttribute("message", message);
            return "Home/Error/403";
        }
    
        @RequestMapping("/500")
        public String ServerError(@RequestParam(required = false) String message, Model model) {
            model.addAttribute("message", message);
            return "Home/Error/500";
        }
    
    }
    
2.8.17 LinkController
  • com.liuyanzhao.ssm.blog.controller.home.LinkController

    package com.liuyanzhao.ssm.blog.controller.home;
    
    import com.liuyanzhao.ssm.blog.entity.Article;
    import com.liuyanzhao.ssm.blog.entity.Link;
    import com.liuyanzhao.ssm.blog.enums.LinkStatus;
    import com.liuyanzhao.ssm.blog.service.ArticleService;
    import com.liuyanzhao.ssm.blog.service.LinkService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.Date;
    import java.util.List;
    
    /**
     *
     * @author 言曌
     * @date 2017/9/5
     */
    @Controller
    public class LinkController {
    	@Autowired
    	private LinkService linkService;
    
    	@Autowired
    	private ArticleService articleService;
    
    	@RequestMapping("/applyLink")
    	public String applyLinkView(Model model)  {
    		//侧边栏显示
    		//获得热评文章
    		List<Article> mostCommentArticleList = articleService.listArticleByCommentCount(8);
    		model.addAttribute("mostCommentArticleList", mostCommentArticleList);
    		return "Home/Page/applyLink";
    	}
    
    
    	@RequestMapping(value = "/applyLinkSubmit",method = {RequestMethod.POST}, produces = {"text/plain;charset=UTF-8"})
    	@ResponseBody
    	public void applyLinkSubmit(Link link)  {
    		link.setLinkStatus(LinkStatus.HIDDEN.getValue());
    		link.setLinkCreateTime(new Date());
    		link.setLinkUpdateTime(new Date());
    		linkService.insertLink(link);
    	}
    }
    
2.8.18 NoticeController
  • com.liuyanzhao.ssm.blog.controller.home.NoticeController

    package com.liuyanzhao.ssm.blog.controller.home;
    
    import com.liuyanzhao.ssm.blog.entity.Article;
    import com.liuyanzhao.ssm.blog.entity.Notice;
    import com.liuyanzhao.ssm.blog.service.ArticleService;
    import com.liuyanzhao.ssm.blog.service.NoticeService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import java.util.List;
    
    /**
     * @author liuyanzhao
     */
    @Controller
    public class NoticeController {
    
        @Autowired
        private NoticeService noticeService;
    
        @Autowired
        private ArticleService articleService;
    
        /**
         * 公告详情页显示
         *
         * @param noticeId
         * @return
         */
        @RequestMapping(value = "/notice/{noticeId}")
        public String NoticeDetailView(@PathVariable("noticeId") Integer noticeId,
                             	Model model) {
            //公告内容和信息显示
            Notice notice  = noticeService.getNoticeById(noticeId);
            model.addAttribute("notice",notice);
    
            //侧边栏显示
            //获得热评文章
            List<Article> mostCommentArticleList = articleService.listArticleByCommentCount(8);
            model.addAttribute("mostCommentArticleList", mostCommentArticleList);
            return "Home/Page/noticeDetail";
        }
    }
    
2.8.19 PageController
  • com.liuyanzhao.ssm.blog.controller.home.PageController

    package com.liuyanzhao.ssm.blog.controller.home;
    
    
    
    
    import com.liuyanzhao.ssm.blog.entity.Article;
    import com.liuyanzhao.ssm.blog.entity.Category;
    import com.liuyanzhao.ssm.blog.entity.Page;
    import com.liuyanzhao.ssm.blog.entity.Tag;
    import com.liuyanzhao.ssm.blog.service.ArticleService;
    import com.liuyanzhao.ssm.blog.service.CategoryService;
    import com.liuyanzhao.ssm.blog.service.PageService;
    import com.liuyanzhao.ssm.blog.service.TagService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.PathVariable;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import java.util.List;
    
    /**
     * @author 言曌
     * @date 2017/9/7
     */
    @Controller
    public class PageController {
    
        @Autowired
        private PageService pageService;
    
        @Autowired
        private ArticleService articleService;
    
        @Autowired
        private CategoryService categoryService;
    
    
        @Autowired
        private TagService tagService;
    
        /**
         * 页面详情页面
         *
         * @param key
         * @return
         */
        @RequestMapping(value = "/{key}")
        public String pageDetail(@PathVariable("key") String key, Model model) {
            Page page = pageService.getPageByKey(1, key);
            if (page == null) {
                return "redirect:/404";
            }
            model.addAttribute("page", page);
    
            //侧边栏显示
            //获得热评文章
            List<Article> mostCommentArticleList = articleService.listArticleByCommentCount(8);
            model.addAttribute("mostCommentArticleList", mostCommentArticleList);
            return "Home/Page/page";
    
        }
    
    
        /**
         * 文章归档页面显示
         *
         * @return
         */
        @RequestMapping(value = "/articleFile")
        public String articleFile(Model model) {
            List<Article> articleList = articleService.listAllNotWithContent();
            model.addAttribute("articleList", articleList);
            //侧边栏显示
            //获得热评文章
            List<Article> mostCommentArticleList = articleService.listArticleByCommentCount(10);
            model.addAttribute("mostCommentArticleList", mostCommentArticleList);
            return "Home/Page/articleFile";
        }
    
        /**
         * 站点地图显示
         *
         * @return
         */
        @RequestMapping(value = "/map")
        public String siteMap(Model model) {
            //文章显示
            List<Article> articleList = articleService.listAllNotWithContent();
            model.addAttribute("articleList", articleList);
            //分类显示
            List<Category> categoryList = categoryService.listCategory();
            model.addAttribute("categoryList", categoryList);
            //标签显示
            List<Tag> tagList = tagService.listTag();
            model.addAttribute("tagList", tagList);
    
            //侧边栏显示
            //获得热评文章
            List<Article> mostCommentArticleList = articleService.listArticleByCommentCount(10);
            model.addAttribute("mostCommentArticleList", mostCommentArticleList);
            return "Home/Page/siteMap";
        }
    
        /**
         * 留言板
         *
         * @return
         */
        @RequestMapping(value = "/message")
        public String message(Model model) {
    
            //侧边栏显示
            //获得热评文章
            List<Article> mostCommentArticleList = articleService.listArticleByCommentCount(8);
            model.addAttribute("mostCommentArticleList", mostCommentArticleList);
            return "Home/Page/message";
        }
    }
    
2.8.20 TagController
  • com.liuyanzhao.ssm.blog.controller.home.TagController

    package com.liuyanzhao.ssm.blog.controller.home;
    
    import com.github.pagehelper.PageInfo;
    import com.liuyanzhao.ssm.blog.entity.Article;
    import com.liuyanzhao.ssm.blog.entity.Tag;
    import com.liuyanzhao.ssm.blog.enums.ArticleStatus;
    
    
    import com.liuyanzhao.ssm.blog.service.ArticleService;
    import com.liuyanzhao.ssm.blog.service.TagService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.*;
    
    import java.util.HashMap;
    import java.util.List;
    
    /**
     * @author 言曌
     * @date 2017/9/2
     */
    @Controller
    public class TagController {
    
        @Autowired
        private TagService tagService;
    
        @Autowired
        private ArticleService articleService;
    
        /**
         * 根据标签查询文章
         *
         * @param tagId 标签ID
         * @return 模板
         */
        @RequestMapping("/tag/{tagId}")
        public String getArticleListByTag(@PathVariable("tagId") Integer tagId,
                               @RequestParam(required = false, defaultValue = "1") Integer pageIndex,
                               @RequestParam(required = false, defaultValue = "10") Integer pageSize,
                                          Model model) {
            //该标签信息
            Tag tag = tagService.getTagById(tagId);
            if (tag == null) {
                return "redirect:/404";
            }
            model.addAttribute("tag", tag);
    
            //文章列表
            HashMap<String, Object> criteria = new HashMap<>(2);
            criteria.put("tagId", tagId);
            criteria.put("status", ArticleStatus.PUBLISH.getValue());
            PageInfo<Article> articlePageInfo = articleService.pageArticle(pageIndex, pageSize, criteria);
            model.addAttribute("pageInfo", articlePageInfo);
    
            //侧边栏
            //标签列表显示
            List<Tag> allTagList = tagService.listTag();
            model.addAttribute("allTagList", allTagList);
            //获得随机文章
            List<Article> randomArticleList = articleService.listRandomArticle(8);
            model.addAttribute("randomArticleList", randomArticleList);
            //获得热评文章
            List<Article> mostCommentArticleList = articleService.listArticleByCommentCount(8);
            model.addAttribute("mostCommentArticleList", mostCommentArticleList);
            model.addAttribute("pageUrlPrefix", "/tag/"+tagId+"?pageIndex");
    
            return "Home/Page/articleListByTag";
        }
    
    }
    
2.9 interceptor拦截器

└─interceptor
AdminInterceptor.java
HomeResourceInterceptor.java
LoginInterceptor.java

2.9.1 AdminInterceptor
  1. com.liuyanzhao.ssm.blog.util.interceptor.AdminInterceptor

    package com.liuyanzhao.ssm.blog.util.interceptor;
    
    import com.liuyanzhao.ssm.blog.entity.User;
    import com.liuyanzhao.ssm.blog.enums.UserRole;
    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.Objects;
    
    
    /**
     * @author liuyanzhao
     */
    @Component
    public class AdminInterceptor extends HandlerInterceptorAdapter {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws IOException {
            // 这里可以根据session的用户来判断角色的权限,根据权限来转发不同的页面
            User user = (User) request.getSession().getAttribute("user");
            if (user == null) {
                response.sendRedirect("/login");
                return false;
            }
            if (!Objects.equals(user.getUserRole(), UserRole.ADMIN.getValue())) {
                return false;
            }
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) {
    
        }
    
        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
    
        }
    }
    
    • 检测管理员身份拦截器
      • 根据session的用户来判断角色的权限,根据权限来转发不同的页面
        1. 获取用户信息
        2. 若为空则重定向至登录界面,并拦截请求
        3. 若用户身份非admin,则拦截请求
2.9.2 HomeResourceInterceptor
  1. com.liuyanzhao.ssm.blog.util.interceptor.HomeResourceInterceptor

    package com.liuyanzhao.ssm.blog.util.interceptor;
    
    import com.liuyanzhao.ssm.blog.entity.Article;
    import com.liuyanzhao.ssm.blog.entity.Options;
    
    import com.liuyanzhao.ssm.blog.enums.ArticleStatus;
    import com.liuyanzhao.ssm.blog.enums.LinkStatus;
    
    import com.liuyanzhao.ssm.blog.entity.Category;
    import com.liuyanzhao.ssm.blog.entity.Menu;
    import com.liuyanzhao.ssm.blog.service.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.HandlerInterceptor;
    import org.springframework.web.servlet.ModelAndView;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * @author liuyanzhao
     */
    @Component
    public class HomeResourceInterceptor implements HandlerInterceptor {
        @Autowired
        private ArticleService articleService;
    
        @Autowired
        private CategoryService categoryService;
    
        @Autowired
        private TagService tagService;
    
        @Autowired
        private LinkService linkService;
    
        @Autowired
        private OptionsService optionsService;
    
        @Autowired
        private MenuService menuService;
    
        /**
         * 在请求处理之前执行,该方法主要是用于准备资源数据的,然后可以把它们当做请求属性放到WebRequest中
         */
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws IOException {
    
            // 菜单显示
            List<Menu> menuList = menuService.listMenu();
            request.setAttribute("menuList", menuList);
    
            List<Category> categoryList = categoryService.listCategory();
            request.setAttribute("allCategoryList", categoryList);
    
            //获得网站概况
            List<String> siteBasicStatistics = new ArrayList<String>();
            siteBasicStatistics.add(articleService.countArticle(ArticleStatus.PUBLISH.getValue()) + "");
            siteBasicStatistics.add(articleService.countArticleComment() + "");
            siteBasicStatistics.add(categoryService.countCategory() + "");
            siteBasicStatistics.add(tagService.countTag() + "");
            siteBasicStatistics.add(linkService.countLink(LinkStatus.NORMAL.getValue()) + "");
            siteBasicStatistics.add(articleService.countArticleView() + "");
            request.setAttribute("siteBasicStatistics", siteBasicStatistics);
            //最后更新的文章
            Article lastUpdateArticle = articleService.getLastUpdateArticle();
            request.setAttribute("lastUpdateArticle", lastUpdateArticle);
    
            //页脚显示
            //博客基本信息显示(Options)
            Options options = optionsService.getOptions();
            request.setAttribute("options", options);
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)  {
        }
    
        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)  {
    
        }
    }
    
    • 在请求处理之前执行,该方法主要是用于准备资源数据的,然后可以把它们当做请求属性放到WebRequest中

      • 获取菜单显示
      • 获取分类列表
      • 获得网站概况(文本存储)
        • 文章总数
        • 文章总评论数
        • 分类总数
        • 标签总数
        • 链接总数
        • 文章浏览总量
      • 最后更新的文章
      • 页脚显示
        • 博客基本信息显示(Options)
2.9.3 LoginInterceptor
  1. com.liuyanzhao.ssm.blog.util.interceptor.LoginInterceptor

    package com.liuyanzhao.ssm.blog.util.interceptor;
    
    import org.springframework.stereotype.Component;
    import org.springframework.web.servlet.ModelAndView;
    import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    
    /**
     * @author liuyanzhao
     */
    @Component
    public class LoginInterceptor extends HandlerInterceptorAdapter {
    
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws IOException {
            //这里可以根据session的用户来判断角色的权限,根据权限来转发不同的页面
            if(request.getSession().getAttribute("user") == null) {
                response.sendRedirect("/login");
                return false;
            }
    
            return true;
        }
    
        @Override
        public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)  {
    
        }
    
        @Override
        public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)  {
    
        }
    }
    
    • 登录拦截器
      • 根据session获取用户信息,若为空则重定向至登录界面,并拦截请求

3. 前端页面

由于此项目前端是通过LayUI+前端三件套+jQuery实现的,我不太想在去学一门比较老的前端UI,所以打算后续自己用Vue实现,因此本小节仅展示部分前端功能和UI界面,辅助后续Vue前端程序构建。

登录界面
  • 登录

    在这里插入图片描述

  • 注册

    在这里插入图片描述

前台
  • 主页

    在这里插入图片描述

  • 分类

    在这里插入图片描述

  • 主页标签和评论

    在这里插入图片描述

  • 文章

    在这里插入图片描述

  • 文章页评论

    在这里插入图片描述

  • 页面和菜单

    在这里插入图片描述

  • 链接

    在这里插入图片描述

  • 基本信息

    在这里插入图片描述

后台
管理员admin
  • 文章

    • 全部文章

      在这里插入图片描述

    • 写文章

      在这里插入图片描述

      在这里插入图片描述

    • 全部分类/编辑分类

      在这里插入图片描述

      在这里插入图片描述

    • 全部标签/编辑标签

      在这里插入图片描述

      在这里插入图片描述

  • 页面

    • 全部页面

      在这里插入图片描述

    • 编辑页面

      在这里插入图片描述

    • 添加页面

      在这里插入图片描述

  • 链接

    • 全部链接

      在这里插入图片描述

    • 编辑链接

      在这里插入图片描述

    • 添加链接

      在这里插入图片描述

  • 公告

    • 全部公告

      在这里插入图片描述

    • 编辑公告

      在这里插入图片描述

    • 添加公告

      在这里插入图片描述

  • 评论

    在这里插入图片描述

  • 用户

    • 全部用户

      [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-cNRHgu6N-1675865229054)(E:\LearnProject\ForestBlog-master\forest_blog前端图\全部用户.jpg)]

    • 编辑用户

      在这里插入图片描述

    • 添加用户

      在这里插入图片描述

  • 设置

    • 菜单

      • 编辑菜单

        在这里插入图片描述

      • 添加菜单

        在这里插入图片描述

    • 主要选项

      • 基本信息

        在这里插入图片描述

      • 小工具

        在这里插入图片描述

普通用户user
  • 文章

    • 我的文章

      在这里插入图片描述

    • 写文章

      同admin

  • 评论

    • 我的评论

      在这里插入图片描述

    • 评论我的

      在这里插入图片描述

  • 基本资料

    • 查看

      在这里插入图片描述

    • 修改

      在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值