用Spring boot 写 公告模块

Pom.xml 依赖

<?xml version="1.0" encoding="UTF-8"?>
<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.0</modelVersion>
    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.6.3</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>cn.kgc</groupId>
    <artifactId>office-automatic</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>office-automatic</name>
    <description>Demo project for Spring Boot</description>
    <properties>
        <java.version>1.8</java.version>
    </properties>
    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.1</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.76</version>
        </dependency>

        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper-spring-boot-starter</artifactId>
            <version>1.4.0</version>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
        </dependency>
    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>false</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <configuration>
                    <excludes>
                        <exclude>
                            <groupId>org.projectlombok</groupId>
                            <artifactId>lombok</artifactId>
                        </exclude>
                    </excludes>
                </configuration>
            </plugin>
        </plugins>
    </build>

</project>

 application.yml

spring:
  datasource:
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql:  /oa2022?useUnicode=true&characterEncoding=utf-8&useSSL=true
    username: root
    password: Qwe159357root@
  thymeleaf:
    cache: false #thymeleaf缓存
  output:
    ansi:
      enabled: always #彩虹日志
  main:
    allow-circular-references: true

  servlet:
    multipart:
      enabled: true


mybatis:
  type-aliases-package: cn.kgc.pojo
  mapper-locations: classpath:cn/kgc/mapper/**/*.xml
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl

server:
  port: 8081

pagehelper:
  reasonable: true
  auto-dialect: true

实体类


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

import java.util.Date;
@Data
@AllArgsConstructor
@NoArgsConstructor
/**
 * 公告表
 */
public class Notity {
  /**
   * 公告表id
   */
  private Integer id;

  /**
   * 标题
   */
  private String title;

  /**
   * 内容
   */
  private String conetxt;

  /**
   * 用户id-外键-用户表
   */
  private Integer u_id;

  /**
   * 发布时间
   */
  @DateTimeFormat(pattern = "yyy-MM-dd")
  private Date createDate;

  /**
   * -1拒绝 0审核中 1通过
   */
  private Integer state;

  private User user;



}

Dao接口

package cn.kgc.dao.annunciate;

import cn.kgc.pojo.Notity;
import com.github.pagehelper.Page;
import org.apache.ibatis.annotations.Mapper;




@Mapper
public interface NotityDao {
    /**
     * //添加公告信息
     * @param notity
     * @return
     */
    int ADD (Notity notity);

    /**
     * 查询单条数据
     * @param id
     * @return
     */

     Notity sa (int id);

    /**
     * //查询公告信息
     * @return
     */
    Page<Notity> selQxmbyId (Integer u_id);

    /**
     * 删除公告信息
     * @param id
     * @return
     */

    int del(Integer id);

    /**
     * 修改
     * @param id
     * @return
     */

    int upd(Integer id);



}

Mapper

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.kgc.dao.annunciate.NotityDao">

    <resultMap id="ab" type="cn.kgc.pojo.Notity">
        <id property="id" column="id"></id>
        <result property="title" column="title"></result>
        <result property="conetxt" column="conetxt"></result>
        <result property="u_id" column="u_id"/>
        <result property="createDate" column="createDate"/>
        <result property="state" column="state"/>
        <association property="user" javaType="cn.kgc.pojo.User">
         <result property="username" column="username"></result>
        </association>

    </resultMap>
    <resultMap id="ity" type="cn.kgc.pojo.Notity">
        <result property="id" column="nid"></result>
        <result property="title" column="title"></result>
        <result property="conetxt" column="conetxt"></result>
        <result property="createDate" column="createDate"></result>
       <association property="user" javaType="cn.kgc.pojo.User">
           <result property="id" column="uid"></result>
           <result property="name" column="name"></result>
       </association>
    </resultMap>
    
    <!--查询倒叙-->
    <select id="selQxmbyId" resultMap="ity">
        SELECT n.id nid ,u.id uid,u.name ,n.title,n.conetxt,n.createDate,n.state,u.userName FROM
        notity AS n,
        user AS u
        WHERE u.id=n.u_id and n.state>=0
        ORDER BY n.id DESC
    </select>

    <!--单条查询-->
    <select id="sa" resultType="cn.kgc.pojo.Notity">
        select *
        from notity
        where id =#{id}
    </select>


    <!--添加-->
    <insert id="ADD">
        insert notity(title, conetxt, u_id,createDate,state)
        values (#{title}, #{conetxt}, #{u_id}, #{createDate}, #{state})
    </insert>

    <!--删除-->
    <delete id="del">
        delete
        from notity
        where id = #{id}
    </delete>
    <!-- 修改-->
    <update id="upd">
        update notity
        set state = -1
        where id = #{id}
    </update>

</mapper>

service层

package cn.kgc.service.annunciate;

import cn.kgc.pojo.Notity;
import com.github.pagehelper.Page;

public interface NotityService {
    /**
     * //添加公告信息
     * @param notity
     * @return
     */
    int ADD (Notity notity);

    /**
     * 查询单条数据
     * @param id
     * @return
     */

    Notity sa (int id);

    /**
     * //查询公告信息
     * @return
     */
    Page<Notity> selQxmbyId (Integer u_id);

    /**
     * 删除公告信息
     * @param id
     * @return
     */

    int del(Integer id);

    /**
     * 修改
     * @param id
     * @return
     */

    boolean upd(Integer id);

}
package cn.kgc.service.annunciate;

import cn.kgc.dao.annunciate.NotityDao;
import cn.kgc.pojo.Notity;
import com.github.pagehelper.Page;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;

@Service
public class NotityServiceImpl implements NotityService
{
    @Resource
    private NotityDao notityDao;

    @Override
    public int ADD(Notity notity) {
        return notityDao.ADD(notity);
    }

    @Override
    public Notity sa(int id) {
        return notityDao.sa(id);
    }

    @Override
    public Page<Notity> selQxmbyId(Integer u_id) {
        return notityDao.selQxmbyId(u_id);
    }

    @Override
    public int del(Integer id) {
        return notityDao.del(id);
    }

    @Override
    public boolean upd(Integer id) {
        if (notityDao.upd(id)>-1){
            return true;
        }
        return false;
    }

}

controller

  //公告查看
    @RequestMapping("/zym-index")
    public String announcement() {
        return "annunciate/zym-index";
    }

    //公告添加
    @RequestMapping("/zym-tianjia")
    public String add() {
        return "annunciate/zym-tianjia";
    }

    //公告详情
    @RequestMapping("/zym_xiangqing")
    public String xq() {
        return "annunciate/zym_xiangqing";
    }

 

package cn.kgc.controller.logic.annunciate;
import cn.kgc.pojo.Notity;
import cn.kgc.service.annunciate.NotityService;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;


import javax.annotation.Resource;
import java.sql.Date;


@Controller
@RequestMapping("/si")
public class Zyn_controller {

    @Resource
    private NotityService notityService;


    //分页查询
    @RequestMapping("/sle")
    @ResponseBody
    public String sel(@Param("currentPage") Integer currentPage,@Param("pageSize") Integer pageSize) {
        PageHelper.startPage(currentPage,pageSize);
        System.out.println("id"+currentPage);
        Page<Notity> sel1 = (Page<Notity>) notityService.selQxmbyId(currentPage);
        PageInfo p = new PageInfo(sel1,pageSize);
        System.out.println("p--------------"+p);
        return JSON.toJSONString(p);


    }

    //添加公告
    @RequestMapping("/save")
    @ResponseBody
    public boolean save(@ModelAttribute Notity notity ,String createDates){
        notity.setCreateDate(Date.valueOf(createDates));
        int insert = notityService.ADD(notity);
        System.out.println("insert"+insert);
        if (insert>0){
            return true;
        }
        return false;
    }

    //删除页面上的 保留数据库里的
    @RequestMapping("/upd")
    @ResponseBody
    public boolean upd(@RequestParam Integer id){
        boolean upd = notityService.upd(id);
        return  upd;
    }


    //单条查询
    @RequestMapping("/sa")
    public String as(@RequestParam int id, Model model){
        Notity i = notityService.sa(id);
        model.addAttribute("contact",i);
        return "/annunciate/zym_xiangqing";
    }

    //公告查看
    @RequestMapping("/zym-index")
    public String announcement() {
        return "annunciate/zym-index";
    }

}

HTML

<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>


    <link rel="stylesheet" type="text/css" href="../css/annunciate/daxiao.css">
    <link rel="stylesheet" type="text/css" href="../css/annunciate/zym_tianjia.css">


    <script src="/js/jquery-3.6.0.js"></script>
    <script src="/lib/layui/layui.all.js"></script>
    <link href="/lib/layui/css/layui.css" rel="stylesheet">
    <script src="../js/annunciate/zym_a.js"></script>
    <script src="../js/annunciate/zym.js"></script>
    <link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">

</head>
<body onload="pageInfo()" class="col-md-offset-2 col-lg-offset-2 col-xl-offset-1" id="body">
<input type="hidden" th:value="${session.user.getId()}" id="u_id">
<div class="adax">
    <div class="col-md-12">
        <div class="panel panel-primary">
            <div class="panel-heading clearfix" style="background-color: #009688;">
                <h3 class="panel-title" style="text-align:center">公告<span
                        class="glyphicon glyphicon-leaf pull-right"></span></h3>
            </div>
            <div class="panel-body">
                <!--						<button class="btn btn-success" style="background-color: #DEDEDE;"><a href="/to/zym-tianjia">新增</a></button>-->
                <form class="form-inline pull-right">
                    <div class="form-group">

                        <div class="input-group">
                        </div>
                    </div>
                </form>
                <table class="table table-hover table-striped table-bordered table-page" style="margin-top: 10px">
                    <thead>
                    <tr>
                        <th>序号</th>
                        <th>公告名</th>
                        <th>发布人</th>
                        <th>发布时间</th>
                    </tr>
                    </thead>
                    <tbody>
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>

                    </tr>
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>

                    <tr>
                        <td></td>
                        <td></td>
                        <td></td>
                        <td></td>
                    </tr>
                    </tbody>
                </table>
                <div style="text-align: center;margin-right: 200px">


                    <h5 align="center">
                        <a href="javascript:void(0)" onclick="starts()">首页</a>&nbsp;&nbsp;&nbsp;
                        <a href="javascript:void(0)" onclick="prevs()">上一页</a>&nbsp;&nbsp;&nbsp;
                        <a href="javascript:void(0)" onclick="nexts()">下一页</a>&nbsp;&nbsp;&nbsp;
                        <a href="javascript:void(0)" onclick="ends()">尾页</a>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                        <span class="showPage">第1页/共1页</span>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
                    </h5>


                </div>
            </div>

        </div>
    </div>
</div>
</body>
</html>
<!DOCTYPE html>

<html lang="en" xmlns:th="http://www.thymeleaf.org">
	<head>
		<meta charset="UTF-8">
		<title>Title</title>
		<link rel="stylesheet" type="text/css" href="../css/annunciate/daxiao.css">
		<script src="/js/annunciate/zym_a.js"></script>
		<link href="https://cdn.bootcss.com/twitter-bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet">
		<script src="/js/jquery-3.6.0.js"></script>
		<script  src="/lib/layui/layui.all.js"></script>
		<link rel="stylesheet" type="text/css" href="../lib/layui/css/layui.css">
		<link rel="stylesheet" type="text/css" href="../css/annunciate/zym_tianjia.css">
		<script  src="/js/annunciate/zym_add.js"></script>

	</head>
	<body class="col-md-offset-2 col-lg-offset-2 col-xl-offset-1" id="body" onload="lookTime()">
	<input type="hidden" th:value="${session.user.getId()}" id="u_id">
		<div>
			<div class="col-md-12">
				<div class="panel panel-primary">
					<div class="panel-heading clearfix" style="background-color: #009688;">
						<h3 class="panel-title" style="text-align:center">增加公告<span
								class="glyphicon glyphicon-leaf pull-right"></span></h3>
					</div>
					<div class="panel-body">
						<form class="form-inline pull-right">
							<div class="form-group">

								<div class="input-group">
								</div>
							</div>
						</form>
						<table class="table table-hover table-striped table-bordered" style="margin-top: 10px">
						</table>
						<div class="box1">

							<form class="layui-form">
								<table class="layui-table">
									<tr>
										<td>标题</td>
										<td>
											<input type="text" class="layui-inpu title"/>
										</td>
									</tr>

									<td>内容:</td>
									<td colspan="3">
										<textarea name="textarea" cols="100" rows="5" class="conetxt">请填写</textarea>
									</td>
									</tr>

									<tr>
										<td>时间段:</td>
										<td>
											<input type="text" class="layui-inpu" id="time" readonly/>
									<tr>

										<td colspan="3">
											<div style="text-align: center;">
												<button class="btn btn-success" onclick="save()">添加</button>
											</div>

										</td>
									</tr>
								</table>
							</form>
						</div>
					</div>
				</div>
			</div>
		</div>
	</body>
</html>
<!DOCTYPE html >

<html lang="en" xmlns:th="http://www.thymeleaf.org">
	<head>
		<meta charset="UTF-8">
		<title>Title</title>
		<script src="/js/annunciate/zym_a.js"></script>
		<link rel="stylesheet" type="text/css" href="../css/annunciate/bootstrap.min.css">
		<script src="/js/annunciate/bootstrap.min.js"></script>
		<script  src="/js/annunciate/zym_upd.js"></script>
	</head>
	<body class="col-md-offset-2 col-lg-offset-2 col-xl-offset-1">
		<div>
			<div class="col-md-10">
				<div class="panel panel-primary">
					<div class="panel-heading clearfix" style="background-color: #009688;">
						<h3 class="panel-title" style="text-align:center">公告详情<span
								class="glyphicon glyphicon-leaf pull-right"></span></h3>
					</div>
					<div class="panel-body" align="center" th:each="op:${contact}">

						<!--标题-->
						<div th:text="${contact.getTitle}"></div>
						<hr />

						<!--内容-->
						<div th:text="${contact.getConetxt}"></div>
						<hr />

						<!--日期-->
						<div style="float: right;" th:text="${#dates.format(contact.getCreateDate(),'yyy-MM-dd')}">
						</div>

						<div style="float: left">
							<button  class="btn btn-success" onclick="save()">返回主页</button>
						</div>

						<form class="form-inline pull-right">
							<div class="form-group">
								<div class="input-group">
								</div>
							</div>
						</form>
					</div>
				</div>
			</div>
		</div>
	</body>
</html>

 Js

        

var currentPage = 1;
var totalPage = 1;
var pageSize = 6;


function pageInfo() {
    //清空
    $(".table-page tr:gt(0) td").html("&nbsp;");
    //声明json串,并赋值
    let jsonA = {
        currentPage: currentPage,
        pageSize: pageSize,
    };
    $.ajaxSettings.async = false;
    $.getJSON("/si/sle", jsonA, function (dataA) {
        console.log(dataA);
        // 总页数
        totalPage = dataA.pages;
        //渲染数据
        $(dataA.list).each(function (i, v) {
            console.log(v);
            let state = v.state;
            if (state == 0) {
                state = "审核中";
            } else if (state == -1) {
                state = "不通过";
            } else {
                state = "通过"
            }
            let date = new Date(v.createDate);
            var m = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1)
            var d = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate())

            $(".table-page").find("tr").eq(i + 1).find("td").eq(0).text((currentPage - 1) * pageSize + i + 1);
            $(".table-page").find("tr").eq(i + 1).find("td").eq(1).html('<a href="javascript:void(0)" onclick="orderby(' + v.id + ',' + v.user.id + ',\'' + v.conetxt + '\')"   >' + v.title + '</a>');
            $(".table-page").find("tr").eq(i + 1).find("td").eq(2).text(v.user.name);
            $(".table-page").find("tr").eq(i + 1).find("td").eq(3).text(date.getFullYear() + "-" + m + "-" + d);
        })
    })

    $.ajaxSettings.async = true;
    showPage();

}

//查看详情跳转
function orderby(id, uid, cenetxt) {
    let dengLuId = $("#u_id").val()
    console.log(id + "--------------" + uid + "----------" + cenetxt);
    if (dengLuId == uid) {
        layer.msg(cenetxt, {
            btn: ['删除', '返回'],
            area: ['300px', '300px'],
            btnAlign: 'c',
            time: 0,
            yes: function (index) {
                del(id, uid);
            }
        })
    } else {
        layer.msg(cenetxt, {
            btn: ['返回'],
            area: ['300px', '300px'],

            btnAlign: 'c',
            time: 0,
            yes: function (index) {
                layer.close(index)
            }
        })
    }

}

//展示页码
function showPage() {
    $(".showPage").text("第" + currentPage + "页 / 共" + totalPage + "页");
    if (totalPage < currentPage) {
        currentPage = totalPage;
        pageInfo();
    }
}


// /下一页

function nexts() {
    currentPage++;
    if (currentPage > totalPage) {
        currentPage = totalPage;
        return;
    }
    pageInfo();
}


//上一页
function prevs() {
    currentPage--;
    if (currentPage < 1) {
        currentPage = 1;
        return;
    }
    pageInfo();
}

//首页
function starts() {
    currentPage = 1;
    pageInfo();
}

//尾页
function ends() {
    currentPage = totalPage;
    pageInfo();
}

function a() {
    location.href = "/add";

}

//删除
function del(id, uid) {
    layer.confirm("确认删除吗",{
        btn:['确认','取消'],
        btnAlign:'c',
        yes:function () {
            $.ajaxSettings.async = false;
            $.post("/si/upd", "id=" + id, function (data) {
                if (data) {
                    layer.msg("删除成功!")
                } else {
                    layer.msg("删除失败!")
                }
            })
            $.ajaxSettings.async = true;
            pageInfo();
        }
    })
}
function save() {

    var title = $(".title").val();
    var conetxt = $ (".conetxt").val();
    var createDate = $("#time").val();
    var u_id = $("#u_id").val();
    var state = 1;



    function boo() {
        if (title == "") {
            alert("必须填写标题");
            return false;
        } else if (conetxt == "") {
            alert("内容不能为空!");
            return false;
        } else if (createDate == "") {
            alert("时间不能为空!");
            return false;
        }
        return true;
    }

    let json = {
        title: title,
        conetxt: conetxt,
        createDates: createDate,
        u_id: u_id,
        state: state
    };

    var bo = boo();
    console.log(bo);
    console.log(json);
    $.ajaxSettings.async = false;
    $.post("/si/save", json, function (data) {
        console.log(data)
        if (data == true && bo == true) {
            alert("添加成功")
        } else {
            alert("添加失败")
        }
    });

    $.ajaxSettings.async = true;

}
function lookTime() {

    var $today = new Date();
    var y = $today.getFullYear();//获取年份
    var m = ($today.getMonth() + 1) < 10 ? ('0' + ($today.getMonth() + 1)) : ($today.getMonth() + 1);//获取月份
    var d = $today.getDate() < 10 ? ('0' + $today.getDate()) : $today.getDate();//获取天
    $today = y + "-" + m + "-" + d; //获取当前时间
    $("#time").val($today);
}
function save() {
    location.href="/si/zym-index";
}

 

 

 

  • 2
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值