Spring boot博客demo

功能

1.登录注册,上传头像
2.超文本编辑器插件UEditor
3.整合mybatis

环境

pom.xml


<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0modelVersion>
    <parent>
        <groupId>org.springframework.bootgroupId>
        <artifactId>spring-boot-starter-parentartifactId>
        <version>2.3.0.RELEASEversion>

        <relativePath/> 
    parent>
    <groupId>com.xiaowuqinggroupId>
    <artifactId>xiaoyobbsartifactId>
    <version>0.0.1-SNAPSHOTversion>
    <name>xiaoyobbsname>
    <description>Demo project for Spring Bootdescription>

    <properties>
        <java.version>1.8java.version>
    properties>

    <dependencies>
        <dependency>
            <groupId>commons-fileuploadgroupId>
            <artifactId>commons-fileuploadartifactId>
            <version>1.3.2version>
        dependency>
        
        <dependency>
            <groupId>org.jsongroupId>
            <artifactId>jsonartifactId>
            <version>20180130version>
        dependency>

        <dependency>
            <groupId>commons-iogroupId>
            <artifactId>commons-ioartifactId>
            <version>2.4version>
        dependency>



        <dependency>
            <groupId>commons-codecgroupId>
            <artifactId>commons-codecartifactId>
            <version>1.9version>
        dependency>
        <dependency>
            <groupId>org.webjarsgroupId>
            <artifactId>jqueryartifactId>
            <version>2.2.4version>
        dependency>
        <dependency>
            <groupId>com.gitee.qdbp.thirdpartygroupId>
            <artifactId>ueditorartifactId>
            <version>1.4.3.6version>
        dependency>

        <dependency>
            <groupId>org.mybatis.spring.bootgroupId>
            <artifactId>mybatis-spring-boot-starterartifactId>
            <version>2.1.1version>
        dependency>

        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-jdbcartifactId>
        dependency>
        <dependency>
            <groupId>mysqlgroupId>
            <artifactId>mysql-connector-javaartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-thymeleafartifactId>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-webartifactId>
        dependency>

        <dependency>
            <groupId>org.projectlombokgroupId>
            <artifactId>lombokartifactId>
            <optional>trueoptional>
        dependency>
        <dependency>
            <groupId>org.springframework.bootgroupId>
            <artifactId>spring-boot-starter-testartifactId>
            <scope>testscope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintagegroupId>
                    <artifactId>junit-vintage-engineartifactId>
                exclusion>
            exclusions>
        dependency>
        <dependency>
            <groupId>org.xmlunitgroupId>
            <artifactId>xmlunit-coreartifactId>
        dependency>
    dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.apache.maven.pluginsgroupId>
                <artifactId>maven-compiler-pluginartifactId>
                <configuration>
                    <source>1.8source>
                    <target>1.8target>
                    <encoding>UTF-8encoding>
                    <compilerArguments>
                        <verbose />
                        <bootclasspath>${java.home}/lib/rt.jar;${java.home}/lib/jce.jarbootclasspath>
                    compilerArguments>
                configuration>
            plugin>
            <plugin>
                <groupId>org.springframework.bootgroupId>
                <artifactId>spring-boot-maven-pluginartifactId>
            plugin>
        plugins>
    build>

project>

application.yml

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

application.properties

#################################### common config : ####################################
spring.application.name=xiaoyobbs
# 应用服务web访问端口
server.port=8080
# ActuatorWeb访问端口
management.server.port=8081
management.endpoints.jmx.exposure.include=*
management.endpoints.web.exposure.include=*
management.endpoint.health.show-details=always
# spring cloud access&secret config
# 可以访问如下地址查看: https://usercenter.console.aliyun.com/#/manage/ak
alibaba.cloud.access-key=****
alibaba.cloud.secret-key=****
spring.thymeleaf.cache=false
# 整合mybatis
mybatis.type-aliases-package=com.xiaowuqing.pojo
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
web.upload-path-boke=/boke/
web.upload-path=/img/
spring.mvc.static-path-pattern=/**
spring.resources.static-locations=classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path},file:${web.upload-path-boke}



注意:上方的"web.upload-path-boke="
“web.upload-path=”
为自定义的服务器文件初始化路径。!!!!

mybatis

引入依赖的前提下:
1.创建pojo
Spring boot博客demo_第1张图片

package com.xiaowuqing.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

@Data
@AllArgsConstructor
@NoArgsConstructor
public class Boke {
     
    private Integer id;
    private String user_id;
    private String chtml;
    private Integer dianzhang;
    private Integer pinglun;
    private String riqi;
    private String title;
    private String name;
    private String tx;
    private Integer liulang;

}

2.Mapper包下新建接口
在这里插入图片描述

package com.xiaowuqing.mapper;

import com.xiaowuqing.pojo.Boke;
import com.xiaowuqing.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;

import java.util.List;

@Mapper
@Repository
public interface BokeMapper {
     
    List<Boke> queryBokeList();//查找所有
    List<Boke> queryBokeListMohu(String title);//查询模糊
    List<Boke> queryBokeListByUserId(String user_id);//通过用户id查找博客

    Boke queryBokeById(Integer id);//通过博客id查博客

    int addBoke(Boke boke);

    int updateBoke(Boke boke);

    int deleteBoke(Integer id);//通过博客id删除博客
}

3.编写xml文件
Spring boot博客demo_第2张图片



<mapper namespace="com.xiaowuqing.mapper.BokeMapper">
    <select id="queryBokeList" resultType="Boke">
            select * from boke
    select>
    <select id="queryBokeListMohu" resultType="Boke">
            select * from boke where title like  "%"#{title}"%"
    select>

    <select id="queryBokeListByUserId" resultType="Boke" parameterType="java.lang.String">
            select * from boke where user_id=#{user_id}
    select>
    <select id="queryBokeById" resultType="Boke" parameterType="java.lang.Integer">
            select * from boke where id=#{id}
    select>
    <insert id="addBoke" parameterType="Boke">
            insert into boke (user_id,chtml,dianzhang,pinglun,riqi,title,name,tx,liulang) values (#{user_id},#{chtml},#{dianzhang},#{pinglun},#{riqi},#{title},#{name},#{tx},#{liulang})
    insert>
    <update id="updateBoke" parameterType="Boke">
            update boke set user_id=#{user_id},chtml=#{chtml},dianzhang=#{dianzhang},pinglun=#{pinglun},riqi=#{riqi},title=#{title},name=#{name},tx=#{tx},liulang=#{liulang} where id=#{id}
    update>
    <delete id="deleteBoke" parameterType="java.lang.Integer" >
            delete  from boke where id=#{id}
    delete>


mapper>

4.自动注入

 @Autowired
    private BokeMapper bokeMapper;

整合Ueditor

1.引入插件
Spring boot博客demo_第3张图片
2.配置自定义json(Spring boot不适用JSP)
Spring boot博客demo_第4张图片

package com.xiaowuqing.controller;

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

@RestController
public class UeditController {
     
    @GetMapping("/ueditor/config")
    public String uedit(){
     
        String s = "{\n" +
                "            \"imageActionName\": \"uploadimage\",\n" +
                "                \"imageFieldName\": \"upfile\", \n" +
                "                \"imageMaxSize\": 2048000, \n" +
                "                \"imageAllowFiles\": [\".png\", \".jpg\", \".jpeg\", \".gif\", \".bmp\"], \n" +
                "                \"imageCompressEnable\": true, \n" +
                "                \"imageCompressBorder\": 1600, \n" +
                "                \"imageInsertAlign\": \"none\", \n" +
                "                \"imageUrlPrefix\": \"\",\n" +
                "                \"imagePathFormat\": \"/ueditor/jsp/upload/image/{yyyy}{mm}{dd}/{time}{rand:6}\" }";
        return s;
    }
}

3.网页创建实例js插件
Spring boot博客demo_第5张图片

<script type="text/javascript" charset="utf-8" th:src="@{/UEditor/ueditor.config.js}"></script>
    <script type="text/javascript" charset="utf-8" th:src="@{/UEditor/ueditor.all.min.js}"></script>
    <script type="text/javascript" charset="utf-8" th:src="@{/UEditor/lang/zh-cn/zh-cn.js}"></script>

<script type="text/javascript">
    var ue=UE.getEditor('editor');
    UE.Editor.prototype._bkGetActionUrl = UE.Editor.prototype.getActionUrl;
    UE.Editor.prototype.getActionUrl = function(action) {
     
        if (action == 'uploadimage'){
     
            return '/boke/upload'; /* 你自己的图片上传action */
        }else{
     
            return this._bkGetActionUrl.call(this, action);
        }
    };
    document.getElementById('fabu').addEventListener('click', function () {
     
        // var json = editor.txt.getJSON();  // 获取 JSON 格式的内容
        // var jsonStr = JSON.stringify(json);
        // console.log(jsonStr);
        var content = ue.getContent();
        var txxt=$("#txt").val();

        $.ajax({
     
            type:"post",
            url:"/upboke",
            data:{
     "num" : content,
                "txt":txxt

            },

            success:function(data){
     
                alert(data);
                window.location.href="/index.html";


            },
            error:function(data){
     
                console.log("error");
                console.log(data);
            }
        })





        // console.log(content)
    })
    document.getElementById('fh').addEventListener('click', function () {
     
        window.location.replace("index.html");

    })
</script>

图片处理如下:

package com.xiaowuqing.controller;

import com.xiaowuqing.pojo.ImgInfo;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class setImgUrlController {
     
    @RequestMapping("/boke/upload")
    public Map<String, String> setImgUrl(MultipartFile upfile, HttpServletResponse response, HttpServletRequest request)
            throws Exception {
     
        // Get the file and save it somewhere
        byte[] bytes = upfile.getBytes();
//        System.out.println(new String(bytes));
        String path ="/boke/";
        File imgFile = new File(path);
        if (!imgFile.exists()) {
     
            imgFile.mkdirs();
        }
        String fileName = UUID.randomUUID()+upfile.getOriginalFilename();// 文件名称
        System.out.println(path + fileName);

        try (FileOutputStream fos = new FileOutputStream(new File(path + fileName))) {
     
            int len = 0;
            fos.write(bytes);
        } catch (Exception e) {
     
            e.printStackTrace();
        }

        String value = "http://服务器地址:8080/" + fileName;
//        String[] values = { value };
//
//        ImgInfo imgInfo = new ImgInfo();
//        imgInfo.setError(0);
//        imgInfo.setUrl(values);
//
//        System.out.println(imgInfo.toString());
//        return imgInfo;
        Map<String,String> map=new HashMap<>();
        map.put("state","SUCCESS");
        map.put("url",value);
        map.put("title",fileName);
        map.put("original",fileName);
        return map;
    }

}

内容处理:

package com.xiaowuqing.controller;

import com.xiaowuqing.mapper.BokeMapper;
import com.xiaowuqing.mapper.UserMapper;
import com.xiaowuqing.pojo.Boke;
import com.xiaowuqing.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;


@Controller
public class UpBokeController {
     
    @Autowired
    private BokeMapper bokeMapper;
    @Autowired
    private UserMapper userMapper;
    @RequestMapping(value="upboke",method= RequestMethod.POST)
    @ResponseBody
    public String upboke(@RequestParam("num") String num, @RequestParam("txt") String txt, HttpSession session) throws IOException {
     
        //先检查用户登录
        User user = (User)session.getAttribute("user");
        if(user==null) return "请先返回登录";
        if(txt.equals("")||num.equals(""))return "请不要乱搞,发送空内容";
        Date date=new Date();
        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format1 = format.format(date);
        int i = bokeMapper.addBoke(new Boke(0, user.getAccount(), num, 0, 0, format1, txt,user.getName(),user.getAvatar(),0));
        if(i>0) {
     
            user.setBnumber(user.getBnumber()+1);
            userMapper.updateUser(user);
            return "发布成功!";
        }

        return "发布失败";

    }
}

thymeleaf

<html lang="en" xmlns:th="http://www.thymeleaf.org">

你可能感兴趣的:(web)