基于javaweb+mysql的springboot个人博客系统(前后端分离+java+vue+springboot+ssm+mysql+maven+redis)

  • Post author:
  • Post category:java


基于javaweb+mysql的springboot个人博客系统(前后端分离+java+vue+springboot+ssm+mysql+maven+redis)

运行环境

Java≥8、MySQL≥5.7、Node.js≥10

开发工具

后端:eclipse/idea/myeclipse/sts等均可配置运行

前端:WebStorm/VSCode/HBuilderX等均可

适用

课程设计,大作业,毕业设计,项目练习,学习演示等

功能说明

基于javaweb+mysql的SpringBoot个人博客系统(前后端分离+java+vue+springboot+ssm+mysql+maven+redis)

一、项目简述

本系统功能包括:文章展示、热门文章、文章分类、标签云用户登录评论、匿名评论用户留言、匿名留言评论管理、文章发布、文章管理文章数据统计等等.

二、项目运行

环境配置: Jdkl . 8 + Tomcats . 5 + Mysql + HBuilderX ( Webstorm 也行) + Eclispe ( IntelliJ 10 以,三 clispe , MyEclispe , Sts 都支持)。

项目技术: Springboot + Maven + Mybatis + Vue + Redis 组成, BIS 模式+ M aven 等等,附带支付宝沙箱环境以及支付环节代码。

    public ResultVO profile(@RequestBody @Validated ProfileDTO profile) {
        configMapper.insert(new ConfigDO(Constants.ConfigKey.NAME, profile.getName()));
        configMapper.insert(new ConfigDO(Constants.ConfigKey.PEN_NAME, profile.getPenName()));
        configMapper.insert(new ConfigDO(Constants.ConfigKey.MOTTO, profile.getMotto()));
        configMapper.insert(new ConfigDO(Constants.ConfigKey.INTRODUCTION, profile.getIntroduction()));
        configMapper.insert(new ConfigDO(Constants.ConfigKey.AVATAR, profile.getAvatar()));
        configMapper.insert(new ConfigDO(Constants.ConfigKey.WEBSITES, StrUtil.EMPTY));
        configService.initConfig();
        return ResultVO.ok("个人信息初始化完成");
    }
}
package com.qianyucc.blog.controller.admin;

/**
 * @e-mail 1413979079@qq.com
 * @description 自定义图床
 */
@Slf4j
@RestController
@RequestMapping("/admin/image")
public class ImageController {
    @Value("${blog.images.path}")
    private String imagesPath;
    @Value("${blog.url}")
        res.setStatus(302);
        res.setHeader("location", clientUrl + "?token=" + token);
    }
}
package com.qianyucc.blog.controller.admin;

/**
 * @e-mail 1413979079@qq.com
 * @description 草稿
 */
@RestController
@RequestMapping("admin/draft")
public class DraftController {
    @Autowired
    private DraftMapper draftMapper;

    @ApiOperation("获取所有草稿")
    @GetMapping("/")
    public List<DraftVO> getAllDrafts() {
        List<DraftVO> draftVOS = draftMapper.findAll()
                .stream()
                .map(DraftVO::create)
                .collect(Collectors.toList());
        return draftVOS;
    }

    @ApiOperation("根据id获取对应草稿信息")
    @GetMapping("/{id}")
    @Value("${blog.url}")
    private String uri;

    @ApiOperation("上传图片")
    @PostMapping("/upload")
    public String upload(@RequestParam("image") MultipartFile multipartFile) {
        // "." 、"\"、"|"需要转义
        String[] split = multipartFile.getOriginalFilename().split("\\.");
        String fileName = UUID.randomUUID().toString() + "." + split[split.length - 1];
        try {
            File dir = new File(imagesPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            FileUtil.writeFromStream(multipartFile.getInputStream(), imagesPath + fileName);
            String url = uri + "admin/image/get/" + fileName;
            log.debug("image-url:{}", url);
            return url;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ImageUploadFailureException(e);
        }
    }

    @ApiOperation("根据图片地址获取图片")
    @GetMapping("/get/{fileName}.{type}")
    public void get(HttpServletResponse res, @PathVariable String fileName, @PathVariable String type) {
        BufferedInputStream in = null;
        ServletOutputStream out = null;
        try {
            in = FileUtil.getInputStream(imagesPath + fileName + "." + type);
            out = res.getOutputStream();
            StreamUtils.copy(in, out);
            out.flush();
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        log.error(e.getMessage());
                    }
                }
            }
        configMapper.insert(new ConfigDO(Constants.ConfigKey.BLOG_DESC, info.getBlogDesc()));
        configMapper.insert(new ConfigDO(Constants.ConfigKey.BLOG_ICON, info.getBlogIcon()));
        return ResultVO.ok("博客信息初始化完成");
    }

    @PostMapping("/profile")
    public ResultVO profile(@RequestBody @Validated ProfileDTO profile) {
        configMapper.insert(new ConfigDO(Constants.ConfigKey.NAME, profile.getName()));
        configMapper.insert(new ConfigDO(Constants.ConfigKey.PEN_NAME, profile.getPenName()));
        configMapper.insert(new ConfigDO(Constants.ConfigKey.MOTTO, profile.getMotto()));
        configMapper.insert(new ConfigDO(Constants.ConfigKey.INTRODUCTION, profile.getIntroduction()));
        configMapper.insert(new ConfigDO(Constants.ConfigKey.AVATAR, profile.getAvatar()));
        configMapper.insert(new ConfigDO(Constants.ConfigKey.WEBSITES, StrUtil.EMPTY));
        configService.initConfig();
        return ResultVO.ok("个人信息初始化完成");
    }
}
package com.qianyucc.blog.controller.admin;

/**
 * @e-mail 1413979079@qq.com
 * @description 自定义图床
 */
@Slf4j
@RestController
@RequestMapping("/admin/image")
public class ImageController {
    @Value("${blog.images.path}")
    private String imagesPath;
    @Value("${blog.url}")
    private String uri;
        commentService.deleteById(id);
        return ResultVO.ok("操作成功!");
    }
}
package com.qianyucc.blog.controller.comm;

/**
 * @description 获取blog的信息
 */
@Slf4j
@RestController("commBlogController")
@RequestMapping("/comm/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;
    @Autowired
    private Configs configs;

    @ApiOperation("获取博客信息")
    @GetMapping("/info")
    public BlogInfoVO getInfo() {
        BlogInfoVO blogInfo = blogService.getBlogInfo();
        return blogInfo;
    }

    @ApiOperation("获取博客配置信息")
    @GetMapping("/profile")

/**
 * @e-mail 1413979079@qq.com
 * @description 草稿
 */
@RestController
@RequestMapping("admin/draft")
public class DraftController {
    @Autowired
    private DraftMapper draftMapper;

    @ApiOperation("获取所有草稿")
    @GetMapping("/")
    public List<DraftVO> getAllDrafts() {
        List<DraftVO> draftVOS = draftMapper.findAll()
                .stream()
                .map(DraftVO::create)
                .collect(Collectors.toList());
        return draftVOS;
    }

    @ApiOperation("根据id获取对应草稿信息")
    @GetMapping("/{id}")
    public DraftDO getById(@PathVariable String id) {
        DraftDO draftDO = draftMapper.findById(id);
        return draftDO;
    }

    @ApiOperation("新增草稿")
    @PostMapping("/")
    public Map<String, Object> saveDraft(@RequestBody DraftDTO draftDTO) {
        // 生成唯一id
        String id = IdUtil.simpleUUID();
        DraftDO draftDO = new DraftDO();
        draftDO.setTitle(draftDTO.getTitle());
        draftDO.setContent(draftDTO.getContent());
        draftDO.setGmtUpdate(System.currentTimeMillis());
        draftDO.setGmtCreate(draftDO.getGmtUpdate());
        draftDO.setId(id);

        draftMapper.insDraft(draftDO);
        Map<String, Object> map = new HashMap<>();
        map.put("msg", "文章已自动保存,上次保存时间:" + Utils.formatDate(draftDO.getGmtUpdate(), DATE_TIME_PATTERN));
        map.put("id", id);
        return map;
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @ApiOperation("导入博客数据")
    @PostMapping("/import")
    public ResultVO importData(@RequestParam("blogData") MultipartFile file) {
        try {
            ObjectInputStream ois = new ObjectInputStream(file.getInputStream());
            BlogData blogData = (BlogData) ois.readObject();
            blogService.importData(blogData);
        } catch (IOException e) {
            log.error("导入博客数据,文件上传失败:{}", e.getMessage());
            return ResultVO.error("数据导入失败");
        } catch (ClassNotFoundException e) {
            log.error("导入博客数据,{}", e.getMessage());
            return ResultVO.error("数据导入失败");
        }
        return ResultVO.ok("数据导入成功");
    }

    @ApiOperation("修改或插入博客信息")
    @PostMapping("/profile")
    public ResultVO updProfile(@RequestBody ProfileDTO profileDTO) {
        configService.updConfig(profileDTO);
        return ResultVO.ok("操作成功");
    }

    @ApiOperation("获取统计图表的信息")
    @GetMapping("/chart")
    public Map<String, Object> getArticlesCountByMouth() {
        return blogService.countByMonth();
    }
}
package com.qianyucc.blog.controller.comm;


    @ApiOperation("插入文章")
    @PostMapping("/")
    public ResultVO insArticle(@RequestBody @Validated ArticleDTO articleDTO) {
        articleService.insArticle(articleDTO);
        return ResultVO.ok("插入文章成功!");
    }

    @ApiOperation("修改文章")
    @PutMapping("/")
    public ResultVO updArticle(@RequestBody @Validated ArticleDTO articleDTO) {
        articleService.updArticle(articleDTO);
        return ResultVO.ok("更新文章成功!");
    }

    @ApiOperation("根据对应文章id删除文章")
    @DeleteMapping("/{id}")
    public ResultVO delArticleById(@PathVariable String id) {
        articleService.delete(id);
        return ResultVO.ok("ID为" + id + "的文章删除成功!");
    }

    @ApiOperation("分页获取文章列表")
    @GetMapping("/")
    public PageInfoVO<SimpleArticleVO> getPageArticles(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber) {
        PageInfoVO<SimpleArticleVO> pageInfoVO = articleService.findByCondition(pageNumber, ADMIN_PAGE_SIZE, null, null);
        return pageInfoVO;
    }

    @ApiOperation("根据查询条件筛选文章")
    @PostMapping("/query")
    public PageInfoVO<SimpleArticleVO> searchArticles(@RequestBody QueryConditionDTO condition) {
        PageInfoVO<SimpleArticleVO> pageInfoVO = articleService.findArticles(condition);
        return pageInfoVO;
    }
}
package com.qianyucc.blog.global;

/**
 * @e-mail 1413979079@qq.com
        BlogData blogData = blogService.export();
        ServletOutputStream out = null;
        try {
            out = res.getOutputStream();
            byte[] bytes = ObjectUtil.serialize(blogData);
            out.write(bytes);
        } catch (IOException e) {
            log.error("导出博客数据中,文件下载失败:{}", e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @ApiOperation("导入博客数据")
    @PostMapping("/import")
    public ResultVO importData(@RequestParam("blogData") MultipartFile file) {
        try {
            ObjectInputStream ois = new ObjectInputStream(file.getInputStream());
            BlogData blogData = (BlogData) ois.readObject();
            blogService.importData(blogData);
        } catch (IOException e) {
            log.error("导入博客数据,文件上传失败:{}", e.getMessage());
            return ResultVO.error("数据导入失败");
        } catch (ClassNotFoundException e) {
            log.error("导入博客数据,{}", e.getMessage());
            return ResultVO.error("数据导入失败");
        }
        return ResultVO.ok("数据导入成功");
    }

    @ApiOperation("修改或插入博客信息")
    @PostMapping("/profile")
    public ResultVO updProfile(@RequestBody ProfileDTO profileDTO) {
        configService.updConfig(profileDTO);
        return ResultVO.ok("操作成功");
    private CommentService commentService;

    @ApiOperation("提交评论")
    @PostMapping("/")
    public ResultVO comment(@RequestBody @Validated CommentDTO commentDTO) {
        commentService.insComment(commentDTO);
        return ResultVO.ok("评论成功!");
    }

    @ApiOperation("根据文章id获取该文章下所有评论")
    @GetMapping("/{id}")
    public List<CommentVO> getAllComments(@PathVariable String id) {
        List<CommentVO> comments = commentService.findCommentByArticleId(id);
        return comments;
    }
}
package com.qianyucc.blog.controller.admin;

/**
 * @description 与评论有关的api
 */
@RestController("adminCommentController")
@RequestMapping("admin/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @ApiOperation("分页展示评论列表")
    @GetMapping("/")
    public PageInfoVO<CommentItemVO> getComment(
            @RequestParam(value = "pageNumber", defaultValue = "1", required = false) Integer pageNumber) {
        PageInfoVO<CommentItemVO> pageInfoVO = commentService.findAllComments(pageNumber);
        return pageInfoVO;
    }

    @ApiOperation("根据id删除对应评论")
    @DeleteMapping("/{id}")
    public ResultVO delById(@PathVariable Long id) {
        commentService.deleteById(id);
        return ResultVO.ok("操作成功!");
    }
}
package com.qianyucc.blog.controller.admin;

/**
 * @description 与评论有关的api
 */
@RestController("adminCommentController")
@RequestMapping("admin/comment")
public class CommentController {
    @Autowired
    private CommentService commentService;

    @ApiOperation("分页展示评论列表")
    @GetMapping("/")
    public PageInfoVO<CommentItemVO> getComment(
            @RequestParam(value = "pageNumber", defaultValue = "1", required = false) Integer pageNumber) {
        PageInfoVO<CommentItemVO> pageInfoVO = commentService.findAllComments(pageNumber);
        return pageInfoVO;
    }

    @ApiOperation("根据id删除对应评论")
    @DeleteMapping("/{id}")
    public ResultVO delById(@PathVariable Long id) {
        commentService.deleteById(id);
        return ResultVO.ok("操作成功!");
    }
}
package com.qianyucc.blog.controller.comm;

        // 登录之后生成token
        userService.qqLogin(userDTO, token);
        res.setStatus(302);
        res.setHeader("location", clientUrl + "?token=" + token);
    }
}
package com.qianyucc.blog.controller.admin;

/**
 * @e-mail 1413979079@qq.com
 * @description 草稿
 */
@RestController
@RequestMapping("admin/draft")
public class DraftController {
    @Autowired
    private DraftMapper draftMapper;

    @ApiOperation("获取所有草稿")
    @GetMapping("/")
    public List<DraftVO> getAllDrafts() {
        List<DraftVO> draftVOS = draftMapper.findAll()
                .stream()
                .map(DraftVO::create)
                .collect(Collectors.toList());
        return draftVOS;
    }
        return pageInfoVO;
    }

    @ApiOperation("根据id删除对应评论")
    @DeleteMapping("/{id}")
    public ResultVO delById(@PathVariable Long id) {
        commentService.deleteById(id);
        return ResultVO.ok("操作成功!");
    }
}
package com.qianyucc.blog.controller.comm;

/**
 * @description 获取blog的信息
 */
@Slf4j
@RestController("commBlogController")
@RequestMapping("/comm/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;
    @Autowired
    private Configs configs;

    @ApiOperation("获取博客信息")
    @GetMapping("/info")
    public BlogInfoVO getInfo() {
        BlogInfoVO blogInfo = blogService.getBlogInfo();
        return blogInfo;
    }

    @ApiOperation("获取博客配置信息")
    @GetMapping("/profile")
    public ProfileVO profile() {
        return ProfileVO.create(configs);
    @Value("${blog.images.path}")
    private String imagesPath;
    @Value("${blog.url}")
    private String uri;

    @ApiOperation("上传图片")
    @PostMapping("/upload")
    public String upload(@RequestParam("image") MultipartFile multipartFile) {
        // "." 、"\"、"|"需要转义
        String[] split = multipartFile.getOriginalFilename().split("\\.");
        String fileName = UUID.randomUUID().toString() + "." + split[split.length - 1];
        try {
            File dir = new File(imagesPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            FileUtil.writeFromStream(multipartFile.getInputStream(), imagesPath + fileName);
            String url = uri + "admin/image/get/" + fileName;
            log.debug("image-url:{}", url);
            return url;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ImageUploadFailureException(e);
        }
    }

    @ApiOperation("根据图片地址获取图片")
    @GetMapping("/get/{fileName}.{type}")
    public void get(HttpServletResponse res, @PathVariable String fileName, @PathVariable String type) {
        BufferedInputStream in = null;
        ServletOutputStream out = null;
        try {
            in = FileUtil.getInputStream(imagesPath + fileName + "." + type);
            out = res.getOutputStream();
            StreamUtils.copy(in, out);
            out.flush();
        } catch (IOException e) {
            log.error(e.getMessage());
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error(e.getMessage());
                }
                if (out != null) {
                    try {
@RestController
@RequestMapping("plugins")
public class WebSitesController {
    @Autowired
    private ConfigMapper configMapper;

    @ApiOperation("获取网站导航信息")
    @GetMapping("/websites")
    public Map<String, String> get() {
        ConfigDO configDO = configMapper.findByKey("websites");
        return MapUtil.of("content", configDO != null ? configDO.getValue() : "");
    }

    @ApiOperation("增加或更新网站导航信息")
    @PostMapping("/websites")
    public ResultVO post(@RequestBody ConfigDO configDO) {
        ConfigDO config = configMapper.findByKey(configDO.getKey());
        if (config != null) {
            configMapper.update(configDO);
        } else {
            configMapper.insert(configDO);
        }
        return ResultVO.ok("操作成功!");
    }
}
package com.qianyucc.blog.controller.comm;

/**
 * @description 与评论相关的api
 */
@RestController("commCommentController")
@RequestMapping("comm/comment")
public class CommentController {

@RestController("adminBlogController")
@RequestMapping("/admin/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;
    @Autowired
    private ConfigService configService;

    @ApiOperation("导出博客数据")
    @GetMapping("/export")
    public void export(HttpServletResponse res, String token) {
        boolean isValid = configService.checkToken(token);
        if (!isValid) {
            res.setStatus(HttpStatus.FORBIDDEN.value());
            return;
        }
        res.setContentType("application/forc-download");
        res.setHeader("Content-Disposition", "attachment;filename=blog_data.db");
        BlogData blogData = blogService.export();
        ServletOutputStream out = null;
        try {
            out = res.getOutputStream();
            byte[] bytes = ObjectUtil.serialize(blogData);
            out.write(bytes);
        } catch (IOException e) {
            log.error("导出博客数据中,文件下载失败:{}", e.getMessage());
        } finally {
            try {
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @ApiOperation("导入博客数据")
    @PostMapping("/import")
    public ResultVO importData(@RequestParam("blogData") MultipartFile file) {
        try {
            ObjectInputStream ois = new ObjectInputStream(file.getInputStream());
            BlogData blogData = (BlogData) ois.readObject();
            blogService.importData(blogData);
        } catch (IOException e) {
            log.error("导入博客数据,文件上传失败:{}", e.getMessage());
/**
 * @description 用户相关api
 */
@Controller("commUserController")
@RequestMapping("/comm/user")
@Slf4j
public class UserController {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private GiteeProvider giteeProvider;
    @Autowired
    private UserService userService;
    @Autowired
    private QQProvider qqProvider;
    @Value("${blog.client}")
    private String clientUrl;

    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    @ResponseBody
    public UserVO getUserInfo(@ApiParam("用户登录态标识") @NotNull(message = "token不能为空") String token) {
        UserDO userDO = userMapper.findByToken(token);
        if (userDO != null) {
            UserVO userVO = UserVO.create(userDO);
            return userVO;
        }
        throw new TokenExpiredException();
    }

    @ApiOperation("用户登录,返回用户登录地址")
    @GetMapping("/login")
    @ResponseBody
    public ResultVO login(@ApiParam("用户登录类型") String type) {
        if (LoginType.QQ.getType().equals(type)) {
            return ResultVO.ok(qqProvider.getLoginUrl());
        } else if (LoginType.GITEE.getType().equals(type)) {
            return ResultVO.ok(giteeProvider.getLoginUrl());
        } else {
            throw new InvalidLoginTypeException();
package com.qianyucc.blog.controller.comm;

/**
 * @e-mail 1413979079@qq.com
 * @description 博客初始化
 */
@RestController
@RequestMapping("/init")
public class InitController {
    @Autowired
    private ConfigMapper configMapper;
    @Autowired
    private ConfigService configService;

    @GetMapping("/check")
    public ResultVO check() {
        List<ConfigDO> all = configMapper.findAll();
        if (all.isEmpty()) {
            return ResultVO.error("博尚未初始化");
        }
        return ResultVO.ok("博客已经初始化");
    }

    @PostMapping("/user")
    public ResultVO user(@RequestBody @Validated AdminUserDTO user) {
        configMapper.insert(new ConfigDO(Constants.ConfigKey.USERNAME, user.getUsername()));
        configMapper.insert(new ConfigDO(Constants.ConfigKey.PASSWORD, user.getPassword()));
    @ApiOperation("分页获取文章列表")
    @GetMapping("/")
    public PageInfoVO<SimpleArticleVO> getPageArticles(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber) {
        PageInfoVO<SimpleArticleVO> pageInfoVO = articleService.findByCondition(pageNumber, ADMIN_PAGE_SIZE, null, null);
        return pageInfoVO;
    }

    @ApiOperation("根据查询条件筛选文章")
    @PostMapping("/query")
    public PageInfoVO<SimpleArticleVO> searchArticles(@RequestBody QueryConditionDTO condition) {
        PageInfoVO<SimpleArticleVO> pageInfoVO = articleService.findArticles(condition);
        return pageInfoVO;
    }
}
package com.qianyucc.blog.global;

/**
 * @e-mail 1413979079@qq.com
 * @description 拦截器:用于日志打印
 */
@Component
@Slf4j
public class LogInterceptor implements HandlerInterceptor {
    @Override
    public synchronized boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("request-method:{}", request.getMethod());
        log.info("request-url:{}", request.getRequestURL());
        String remoteAddr = request.getRemoteAddr();
        log.info("remote-addr:{}", remoteAddr);
        StringBuffer sb = new StringBuffer();
        request.getParameterMap().forEach((k, v) -> sb.append(k).append(Arrays.toString(v)));
        log.info("request-parameters:{}", sb.toString());
        // 根据ip定位
        //((Runnable) () -> {
        //    try {
        //        String res = HttpUtil.get(TAOBAO_IP_INFO + "?ip=" + remoteAddr);
        //        JSONObject jsonObject = JSONUtil.parseObj(res);
        //        if ("0".equals(jsonObject.get("code"))) {
        //            JSONObject data = jsonObject.getJSONObject("data");
        //            log.info("ip-info:country:{}、area:{}、region:{}、city:{}、isp:{}", data.get("country"), data.get("area"), data.get("region"), data.get("city"), data.get("isp"));
        //        }
        //    } catch (Exception e) {
/**
 * @e-mail 1413979079@qq.com
 * @description 自定义图床
 */
@Slf4j
@RestController
@RequestMapping("/admin/image")
public class ImageController {
    @Value("${blog.images.path}")
    private String imagesPath;
    @Value("${blog.url}")
    private String uri;

    @ApiOperation("上传图片")
    @PostMapping("/upload")
    public String upload(@RequestParam("image") MultipartFile multipartFile) {
        // "." 、"\"、"|"需要转义
        String[] split = multipartFile.getOriginalFilename().split("\\.");
        String fileName = UUID.randomUUID().toString() + "." + split[split.length - 1];
        try {
            File dir = new File(imagesPath);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            FileUtil.writeFromStream(multipartFile.getInputStream(), imagesPath + fileName);
            String url = uri + "admin/image/get/" + fileName;
            log.debug("image-url:{}", url);
            return url;
        } catch (Exception e) {
            log.error(e.getMessage());
            throw new ImageUploadFailureException(e);
        }
    }

    @ApiOperation("根据图片地址获取图片")
    @GetMapping("/get/{fileName}.{type}")
    public void get(HttpServletResponse res, @PathVariable String fileName, @PathVariable String type) {
        BufferedInputStream in = null;
        ServletOutputStream out = null;
    }

    @ApiOperation("获取热门文章列表")
    @GetMapping(value = "/hot", produces = "application/json;charset=UTF-8")
    public String getHotArticles() {
        return redisTemplate.opsForValue().get("hotArticles");
    }

    @ApiOperation("获取所有文章分类")
    @GetMapping("/categories")
    public List<Map<String, Object>> getCategories() {
        return articleMapper.findCategoriesCount();
    }

    @ApiOperation("获取所有文章标签")
    @GetMapping("/tags")
    public Set<String> getTags() {
        Set<String> tags = articleService.findAllTags();
        return tags;
    }

    @ApiOperation("获取文章的所有月份")
    @GetMapping("/archives")
    public Set<String> getArchivesMonths() {
        Set<String> months = articleService.archivesMonths();
        return months;
    }
}
package com.qianyucc.blog.controller.admin;

/**
 * @description 管理博客文章
 */
@RestController("adminArticleController")
@RequestMapping("admin/articles")
@Slf4j
public class ArticleController {
    @Autowired
    private ArticleService articleService;
 * @description 网站导航
 */
@Slf4j
@RestController
@RequestMapping("plugins")
public class WebSitesController {
    @Autowired
    private ConfigMapper configMapper;

    @ApiOperation("获取网站导航信息")
    @GetMapping("/websites")
    public Map<String, String> get() {
        ConfigDO configDO = configMapper.findByKey("websites");
        return MapUtil.of("content", configDO != null ? configDO.getValue() : "");
    }

    @ApiOperation("增加或更新网站导航信息")
    @PostMapping("/websites")
    public ResultVO post(@RequestBody ConfigDO configDO) {
        ConfigDO config = configMapper.findByKey(configDO.getKey());
        if (config != null) {
            configMapper.update(configDO);
        } else {
            configMapper.insert(configDO);
        }
        return ResultVO.ok("操作成功!");
    }
}
package com.qianyucc.blog.controller.comm;

/**

/**
 * @description 与评论相关的api
 */
@RestController("commCommentController")
@RequestMapping("comm/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @ApiOperation("提交评论")
    @PostMapping("/")
    public ResultVO comment(@RequestBody @Validated CommentDTO commentDTO) {
        commentService.insComment(commentDTO);
        return ResultVO.ok("评论成功!");
    }

    @ApiOperation("根据文章id获取该文章下所有评论")
    @GetMapping("/{id}")
    public List<CommentVO> getAllComments(@PathVariable String id) {
        List<CommentVO> comments = commentService.findCommentByArticleId(id);
        return comments;
    }
}
package com.qianyucc.blog.controller.admin;

/**
 * @description 与评论有关的api
 */
@RestController("adminCommentController")
@RequestMapping("admin/comment")

    @ApiOperation("分页获取文章列表")
    @GetMapping("/")
    public PageInfoVO<SimpleArticleVO> getPageArticles(@RequestParam(value = "pageNumber", defaultValue = "1") Integer pageNumber) {
        PageInfoVO<SimpleArticleVO> pageInfoVO = articleService.findByCondition(pageNumber, ADMIN_PAGE_SIZE, null, null);
        return pageInfoVO;
    }

    @ApiOperation("根据查询条件筛选文章")
    @PostMapping("/query")
    public PageInfoVO<SimpleArticleVO> searchArticles(@RequestBody QueryConditionDTO condition) {
        PageInfoVO<SimpleArticleVO> pageInfoVO = articleService.findArticles(condition);
        return pageInfoVO;
    }
}
package com.qianyucc.blog.global;

/**
 * @e-mail 1413979079@qq.com
 * @description 拦截器:用于日志打印
 */
@Component
@Slf4j
public class LogInterceptor implements HandlerInterceptor {
    @Override
    public synchronized boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        log.info("request-method:{}", request.getMethod());
        log.info("request-url:{}", request.getRequestURL());
        String remoteAddr = request.getRemoteAddr();
        log.info("remote-addr:{}", remoteAddr);
        StringBuffer sb = new StringBuffer();
        request.getParameterMap().forEach((k, v) -> sb.append(k).append(Arrays.toString(v)));
        log.info("request-parameters:{}", sb.toString());
        // 根据ip定位
        //((Runnable) () -> {
        //    try {
        //        String res = HttpUtil.get(TAOBAO_IP_INFO + "?ip=" + remoteAddr);
        //        JSONObject jsonObject = JSONUtil.parseObj(res);
        //        if ("0".equals(jsonObject.get("code"))) {
        //            JSONObject data = jsonObject.getJSONObject("data");
        //}).run();
        return true;
    }
}
package com.qianyucc.blog.global;

/**
 * @description 管理员token拦截器
 */
@Component
@Slf4j
public class TokenInterceptor implements HandlerInterceptor {
    @Autowired
    private ConfigMapper configMapper;

    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) {
        if ("OPTIONS".equals(req.getMethod())) {
            res.setStatus(HttpServletResponse.SC_OK);
            return true;
        }

        String token = req.getHeader("Authorization");
        log.info("admin token:" + token);
        if (token == null) {
            res.setStatus(403);
            res.setHeader("Access-Control-Allow-Origin", "*");
            return false;
        }
        ConfigDO cdo = configMapper.findByKey("admin_token");
        if (!cdo.getValue().equals(token)) {
            res.setStatus(403);
            res.setHeader("Access-Control-Allow-Origin", "*");
            return false;
        }
        return true;
    }
    @DeleteMapping("/{id}")
    public ResultVO delById(@PathVariable Long id) {
        commentService.deleteById(id);
        return ResultVO.ok("操作成功!");
    }
}
package com.qianyucc.blog.controller.comm;

/**
 * @description 获取blog的信息
 */
@Slf4j
@RestController("commBlogController")
@RequestMapping("/comm/blog")
public class BlogController {
    @Autowired
    private BlogService blogService;
    @Autowired
    private Configs configs;

    @ApiOperation("获取博客信息")
    @GetMapping("/info")
    public BlogInfoVO getInfo() {
        BlogInfoVO blogInfo = blogService.getBlogInfo();
        return blogInfo;
    }

    @ApiOperation("获取博客配置信息")
    @GetMapping("/profile")

请添加图片描述

请添加图片描述

请添加图片描述

请添加图片描述





版权声明:本文为m0_71016350原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。