实战项目(一)内容管理系统

一、实现技术 

前端技术:html、javascript(jquery、ajax、json)、css

后端技术:java、mysql、servlet

开发工具:eclipse、vscode

二、项目描述

首页仿写某大学网页,上面有各种栏目及栏目内容,管理员能登录进去对首页展示的栏目和内容进行增删改查的管理,以及注册的用户信息进行管理。

三、页面展示

①首页页面

②栏目内容 more+

 ③单个内容详情

 ④登录页面

⑤注册页面

⑥忘记密码页面

 ⑦内容管理页面

⑧内容管理:新增,能够上传图片,引用富文本编辑器

⑨内容管理:修改,实现回显

 四、关键代码展示

①首页

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>hbu页面</title>
    <link rel="stylesheet" href="resources/css/hbu.css">
    <script src="resources/js/jquery.js"></script>
	<script src="resources/js/jquery.cookie.js"></script>
    <script src="resources/js/hbu.js" defer></script>
</head>

<body>
    <a name="top"></a>
    <!-- 页面头部开始 -->
    <div class="top">
        <div class="left">
            <img src="resources/images/logo.png" class="logo" alt="">
            <div class="sublogobox">
                <img src="resources/images/yinxin.png" class="sublogo" alt="">
                <h3>Newcomers' Session</h3>
            </div>
        </div>
        <div class="right">
            <a href="">河大主页</a> |
            <a href="">学工网</a>
        </div>
    </div>
    <!-- 页面头部结束 -->

    <!-- 页面菜单开始 -->
    <div class="menubox">
        <ul>
            <li><a href="hbu.html">首页</a></li>
            <li><a href="#5" class="toChannel">网上报到</a></li>
            <li><a href="#6" class="toChannel">入学指南</a></li>
            <li><a href="#7" class="toChannel">走进河大</a></li>
            <li><a href="#8" class="toChannel">学在河大</a></li>
            <li><a href="#9" class="toChannel">家在河大</a></li>
            <li><a href="#10" class="toChannel">联系我们</a></li>
            <li><a href="#11" class="toChannel">河大易班</a></li>
        </ul>
    </div>
    <!-- 页面菜单结束 -->

    <!-- 轮播开始 -->
    <div class="slider">
        <img src="resources/images/lunbo1.jpg" alt="">
    </div>
    <!-- 轮播结束 -->

    <!-- 页面主体开始 -->
    <div class="main">
        <div class="left">
            <h3>
                <span>快捷方式</span>
            </h3>
            <ul>
                <li>
                    <a href="#12" class="toChannel">
                        <img src="resources/images/1.png" alt="">
                        <h4>学院简介</h4>
                    </a>
                </li>
                <li>
                    <a href="#13" class="toChannel">
                        <img src="resources/images/2.png" alt="">
                        <h4>辅导员风采</h4>
                    </a>
                </li>
                <li>
                    <a href="#14" class="toChannel">
                        <img src="resources/images/3.png" alt="">
                        <h4>防控疫情</h4>
                    </a>
                </li>
                <li>
                    <a href="#15" class="toChannel">
                        <img src="resources/images/4.png" alt="">
                        <h4>咨询留言</h4>
                    </a>
                </li>
            </ul>
        </div>
        <div class="middle">
            <h3>
                <span>通知公告</span>
                <a href="#1" class="toChannel">more+</a>
            </h3>
            <ul>

            </ul>
        </div>
        <div class="right">
            <h3>
                <span>心理测试</span>
                <a href="#2" class="toChannel">more+</a>
            </h3>
            <img src="resources/images/tu1.jpg" alt="">
            <h4>河大学子深情演唱《不忘初心》</h4>
            <ul>
                
            </ul>
        </div>
    </div>
    <!-- 页面主体结束 -->

    <!-- 页面军训开始 -->
    <div class="jxbox">
        <div class="jx">
            <h3>
                <span>军训专区</span>
                <a href="#3" class="toChannel">more+</a>
            </h3>
            <ul>
               
            </ul>
        </div>
    </div>
    <!-- 页面军训结束 -->
    <!-- 页面底部开始 -->
    <div class="bottom">
        <div class="bottombox">
            <div class="left">
                <img src="resources/images/logo2.png" alt="">
                <div class="text">
                    <h3>迎新网</h3>
                    <h3>Newcomers' Session</h3>
                </div>
            </div>
            <div class="right">
                <img src="resources/images/yxwerweima.png" alt="">
                <div class="text">
                    <h3>邮箱:hbdxxsc@126.com </h3>
                    <h3>版权所有:河北大学党委学生工作部 <a href="login.html">管理登录</a></h3>
                </div>
            </div>
        </div>
    </div>
    <!-- 页面底部结束 -->

    <!-- 返回顶部开始-->
    <a href="#top" class="backTop">
        <span>TOP</span>
        <img src="resources/images/top.png" alt="">
    </a>
    <!-- 返回顶部结束 -->
</body>

</html>
/* 公共样式开始 */

* {
    margin: 0;
    padding: 0;
    transition: all ease 2s;
}

ul {
    list-style: none;
}

a {
    text-decoration: none;
}


/* 公共样式结束 */


/* 页面头部样式开始 */

.top {
    width: 80%;
    margin: 20px auto;
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.top .left {
    display: flex;
    align-items: flex-end;
}

.top .left .sublogobox {
    margin-bottom: 5px;
    margin-left: 4px;
}

.top .left .logo {
    width: 250px;
}

.top .left .sublogobox .sublogo {
    width: 54px;
}

.top .left .sublogobox h3 {
    font-size: 14px;
    color: rgb(165, 41, 31)
}

.top .right {}

.top .right a {
    color: rgb(165, 41, 31);
    font-size: 14px;
}


/* 页面头部样式结束 */


/* 页面菜单样式开始 */

.menubox {
    background: rgb(165, 41, 31);
}

.menubox ul {
    display: flex;
    width: 80%;
    margin: 0 auto;
    justify-content: space-between;
}

.menubox ul li {}

.menubox ul li a {
    padding: 10px;
    display: block;
    color: #fff;
    cursor: pointer;
}

.menubox ul li a:hover {
    background: #fff;
    color: rgb(165, 41, 31)
}


/* 页面菜单样式结束 */


/* 页面轮播开始 */

.slider {}

.slider img {
    width: 100%;
}


/* 页面轮播结束 */


/* 页面主体开始 */

.main {
    display: flex;
    width: 80%;
    margin: 20px auto;
    justify-content: space-between;
}

.main>.left {
    width: 14%;
}

.main>.left>h3,
.main>.middle>h3,
.main>.right>h3,
.jx>h3 {
    border-bottom: 1px solid rgb(221, 221, 221);
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.main>.left>h3 span,
.main>.middle>h3 span,
.main>.right>h3 span,
.jx>h3 span {
    border-bottom: 2px solid rgb(165, 41, 31);
    padding-bottom: 6px;
    font-weight: 500;
    font-size: 15px;
}

.main>.middle>h3 a,
.main>.right>h3 a,
.jx>h3 a {
    color: #aaa;
    font-size: 12px;
}

.main>.middle>h3 a:hover,
.main>.right>h3 a:hover,
.jx>h3 a:hover {
    color: rgb(165, 41, 31)
}

.main>.left ul {}

.main>.left ul li {
    margin: 10px 0;
}

.main>.left ul li:hover {
    opacity: 0.7;
}

.main>.left ul li:nth-child(1) {
    background: rgb(129, 194, 222);
}

.main>.left ul li:nth-child(2) {
    background: rgb(254, 194, 15);
}

.main>.left ul li:nth-child(3) {
    background: rgb(191, 214, 47);
}

.main>.left ul li:nth-child(4) {
    background: rgb(47, 163, 220);
}

.main>.left ul li a {
    display: block;
    text-align: center;
    padding: 10px 0;
    color: #fff;
}

.main>.middle {
    width: 55%;
}

.main>.middle ul {}

.main>.middle ul li {
    margin: 10px 0 20px;
    border-bottom: 1px dashed rgb(221, 221, 221);
    padding-bottom: 20px;
}

.main>.middle ul li:last-child {
    border: none;
}

.main>.middle ul li a {
    display: flex;
    justify-content: space-between;
}

.main>.middle ul li a .left {
    width: 12%;
}

.main>.middle ul li a .left h3 {
    background: rgb(238, 238, 238);
    color: rgb(217, 49, 36);
    text-align: center;
    font-size: 30px;
    padding: 4px 0;
}

.main>.middle ul li a .left p {
    background: rgb(217, 49, 36);
    color: #fff;
    text-align: center;
    font-size: 12px;
    padding: 4px 0;
}

.main>.middle ul li a .right {
    width: 85%;
}

.main>.middle ul li a .right h3 {
    color: rgb(217, 49, 36);
    font-weight: 500;
    font-size: 15px;
}

.main>.middle ul li a .right p {
    color: rgb(119, 119, 119);
    font-size: 14px;
    margin-top: 9px;
}

.main>.middle ul li:hover a .right p {
    color: rgb(217, 49, 36)
}

.main>.right {
    width: 28%;
}

.main>.right img {
    width: 100%;
    margin-top: 10px;
    filter: brightness(80%);
}

.main>.right img:hover {
    filter: brightness(100%);
}

.main>.right h4 {
    background: rgb(165, 41, 31);
    color: #fff;
    padding: 10px;
    font-size: 14px;
    font-weight: 500;
}

.main>.right ul {}

.main>.right ul li:nth-child(odd) {
    background: rgb(238, 238, 238);
}

.main>.right ul li:nth-child(even) {
    background: rgb(245, 245, 245);
}

.main>.right ul li a {
    color: #666;
    padding: 8px 10px;
    display: block;
    font-size: 14px;
}

.main>.right ul li a:hover {
    color: rgb(165, 41, 31);
    transform: translate(20px);
}


/* 页面主体结束 */


/* 页面军训开始 */

.jxbox {
    background: url("../images/bg.jpg");
}

.jx {
    width: 80%;
    margin: 0 auto 30px;
    padding: 15px 0;
}

.jx ul {
    display: flex;
    justify-content: space-between;
    margin-top: 20px;
}

.jx ul li {
    width: 24%;
    background: #fff;
}

.jx ul li a {
    display: block;
    position: relative;
    overflow: hidden;
}

.jx ul li a span {
    background: rgb(247, 140, 131);
    color: #fff;
    font-size: 12px;
    padding: 5px;
    position: absolute;
    left: 0;
    top: 0
}

.jx ul li a img {
    width: 100%;
}

.jx ul li a h3 {
    padding: 3px 10px;
    color: rgb(217, 49, 36);
    font-weight: 500;
    font-size: 15px;
}

.jx ul li a p {
    padding: 3px 10px 10px;
    color: rgb(119, 119, 119);
    font-size: 14px;
}

.jx ul li:hover a p {
    color: rgb(217, 49, 36)
}

.jx ul li:hover a img {
    transform: scale(1.2, 1.2);
    /*skew()倾斜 rotate()旋转 scale()缩放 translate()位移*/
}


/* 页面军训结束 */


/* 页面底部开始 */

.bottom {
    background: rgb(165, 41, 31);
}

.bottom .bottombox {
    width: 80%;
    margin: 0 auto;
    display: flex;
    justify-content: space-between;
    padding: 20px 0;
    align-items: center;
}

.bottom .bottombox .left {
    display: flex;
    align-items: flex-end;
}

.bottom .bottombox .left img {
    height: 60px;
}

.bottom .bottombox .left .text {
    color: #fff;
    font-size: 12px;
    margin-bottom: 2px;
    margin-left: 6px;
}

.bottom .bottombox .left .text h3 {
    font-weight: 500;
}

.bottom .bottombox .right {
    display: flex;
    align-items: center;
}

.bottom .bottombox .right img {
    height: 80px;
}

.bottom .bottombox .right .text {
    color: #fff;
    font-size: 12px;
}

.bottom .bottombox .right .text h3 {
    font-weight: 500;
}

.bottom .bottombox .right .text h3 a {
    color: #fff;
}

.bottom .bottombox .right .text h3 a:hover {
    background: #fff;
    padding: 2px;
    color: rgb(165, 41, 31)
}


/* 页面底部结束 */

.backTop {
    position: fixed;
    bottom: 10px;
    right: 10px;
    width: 50px;
    height: 50px;
    display: block;
    text-align: center;
    background: rgb(217, 49, 36);
    color: #fff;
    padding-top: 5px;
}


/* 页面栏目样式开始 */

.hbu_channel,
.hbu_detail{
    min-height: 500px;
    width: 80%;
    margin:20px auto;
}

.hbu_channel h2{
    color: #910000;
    font-size: 17px;
    border-bottom: 2px solid #910000;
    padding-bottom: 4px;
    margin-bottom: 10px;
}

.hbu_channel ul li{
    margin: 10px 0;
    border-bottom: 1px #aaa dashed;
    padding:5px 0;
}

.hbu_channel ul li a{
    display: flex;
    justify-content: space-between;
    align-items: center;
    color: #666;
}

.hbu_channel ul li a div{
    width: 90%;
}

.hbu_channel ul li a h3{
    font-size: 14px;
    color: #555;
}

.hbu_channel ul li a p{
    font-size: 13px;
    line-height: 25px;
    margin-top: 5px;
}

.hbu_channel ul li a span{
    font-size: 13px;
}

/* 页面栏目样式开始 */

/* 详情页面样式开始 */

.hbu_detail h5{
    border-bottom: 1px solid #aaa;
    margin: 10px 0;
    padding-bottom: 5px;
    color: #666;
}

.hbu_detail h5 a{
    color: #666;
}

.hbu_detail div h3{
    text-align: center;
    font-size: 20px;
    margin: 30px 0;
}

.hbu_detail div .subinfo{
    text-align: end;
    font-size: 13px;
    font-weight: 600;
    margin-bottom: 30px;
}

.hbu_detail div .subinfo span{
    font-weight: 500;
    margin-right: 15px;
}

/* 详情页面样式结束 */

//剪裁方法
function cut_str(str,len){
	if(str.length>len){
		str=str.substring(0,len)+"..."
	}
	return str
}

//加载通知公告
$.ajax({
	url:"hbu?action=getContent&channelid=1&limit=4",
	type:"get",
	success:function(value){
		$(".middle ul").empty()
		var arr = value.data
		for(var i=0; i<arr.length;i++){
			$(".middle ul").append("<li>"+
                    "<a href='#"+arr[i].id+"' class='toDetail'>"+
                        "<div class='left'>"+
                            "<h3>"+arr[i].createtime.substring(8,10)+"</h3>"+
                            "<p>"+arr[i].createtime.substring(0,7)+"</p>"+
                        "</div>"+
                        "<div class='right'>"+
                            "<h3>"+cut_str(arr[i].title,30)+"</h3>"+
                            "<p>"+cut_str(arr[i].desc,80)+"</p>"+
                        "</div>"+
                    "</a>"+
                "</li>")
		}	
	},
	error:function(){
		console.log("加载通知公告失败")
	}
})

//加载心理测试
$.ajax({
	url:"hbu?action=getContent&channelid=2&limit=5",
	type:"get",
	success:function(value){
		$(".right ul").empty()
		var arr = value.data
		for(var i=0; i<arr.length;i++){
			$(".right ul").append("<li><a href='#"+arr[i].id+"' class='toDetail'>"+cut_str(arr[i].title,10)+"</a></li>")
		}
		
	},
	error:function(){
		console.log("加载心理测试失败")
	}
})

//加载军训专区
$.ajax({
	url:"hbu?action=getContent&channelid=3&limit=4",
	type:"get",
	success:function(value){
		$(".jx ul").empty()
		var arr = value.data
		for(var i=0; i<arr.length;i++){
			$(".jx ul").append("<li>"+
                    "<a href='#"+arr[i].id+"' class='toDetail'>"+
                        "<span>"+arr[i].createtime.substring(0,10)+"</span>"+
                        "<img src='upload/"+arr[i].imgurl+"' alt=''>"+
                        "<h3>"+cut_str(arr[i].title,10)+"</h3>"+
                        "<p>"+cut_str(arr[i].desc,50)+"</p>"+
                    "</a>"+
                "</li>")
		}
		
	},
	error:function(){
		console.log("加载心理测试失败")
	}
})

//跳转到栏目页面
$(".toChannel").on("click",function(){
	$.cookie("channelid",$(this).attr("href"))
	location.href="hbu_channel.html"
})

//跳转到详情页面
$("body").on("click",".toDetail",function(){
	$.cookie("contentid",$(this).attr("href"))
	location.href="hbu_detail.html"
})

②内容管理

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>内容管理页面</title>
    <link rel="stylesheet" href="resources/css/content.css">
	<script src="resources/js/jquery.js"></script>
	<script src="resources/js/jquery.cookie.js"></script>
	<script src="resources/layer/layer.js"></script>
    <script src="resources/js/content.js" defer></script>
</head>
<body>
    <div class="container">
        <div class="search_box">
            <div class="search">
            	<select class='searchChannel'>
            		
            	</select>
                <input type="text" placeholder="请输入标题" class="searchTitle">
                <input type="text" placeholder="请输入作者" class="searchAuthor">
                <input type="button" value="查找" class="search_btn">
            </div>
            <div class="btns">
                <input type="button" value="批量删除" class="deleteAll">
                <input type="button" value="添加" class="add">
            </div>
        </div>
    </div>
    <table border="1" >
        <thead>
            <tr>
            <th width="25px"><input type="checkbox" name="" id="" class="checkAll"></th>
            <th width="30px">序号</th>
            <th width="90px">栏目</th>
            <th width="">题目</th>
            <th width="">摘要</th>
            <th width="90px">创建时间</th>
            <th width="80px">封面图</th>
            <th width="">作者</th>
            <th width="90px">操作</th>
            </tr>
        </thead>
        <tbody>
            
        </tbody>
    </table>
    <ul class="page">
      
    </ul>
</body>
</html>
*{
    padding: 0;
    margin: 0;
}

.container{
    width: 98%;
    margin: 20px auto;
}

.container .search_box{
    display: flex;
    justify-content: space-between;
    margin-bottom: 20px;
}

.container .search_box .search{
    display: flex;
    align-items: center;
}

.container .search_box .search select,
.container .search_box .search input{
    padding: 3px 3px;
    margin-right: 10px;
    font-size: 13px;
}

.container .search_box .search select,
.container .search_box .search input[type=text]{
    border: 1.5px solid rgb(243, 104, 104);
    outline: none;
    padding: 8px 10px;
}

.container .search_box .search select:focus,
.container .search_box .search input[type=text]:focus{
    border: 3px solid rgb(243, 104, 104); 
}

.container .search_box .search input[type=button]{
    background: linear-gradient(30deg, plum, pink);
    color: white;
    border: none;
    font-size: 15px;
    padding: 6px 8px;
    cursor: pointer;
}

.container .search_box .search input:hover{
    box-shadow: 1px 1px 2px plum;
}

.container .search_box .btns input{
    background: rgb(227, 232, 141);
    font-size: 15px;
    color: rgb(237, 137, 137);
    padding: 5px 5px;
    border: none;
    margin-right: 15px;
    margin-top: 5px;
    cursor: pointer;
}

.container .search_box .btns input:hover{
    background: rgb(244, 118, 118);
}

table{
    width: 98%;
    margin: 20px auto;
    border: 1px solid wheat;
}

table thead tr{
    background: rgb(244, 118, 118);
    color: white;
    font-size: 13px;
}

table th tr th{
    padding: 3px 0;
}

table tr td,
table tr th{
    border: 1px solid white;
    text-align: center;
}

table tbody tr:nth-child(odd){
    background: rgb(244, 226, 226);
}
table tbody tr:nth-child(even){
    background: whitesmoke;
}

table tbody input[type=button]{
    background: rgb(124, 233, 245);
    border:2px solid rgb(106, 230, 244);
    font-size: 14px;
    margin-left: 5px;
    padding: 2px 3px;
    color: rgb(247, 127, 127);
}

.page{
    display: flex;
    justify-content: center;
}

.page li{
    list-style: none;
    margin: 5px;
    border: 1px solid plum;
    padding: 3px 6px;
    font-size: 13px;
    color: brown;
    cursor: pointer;
}

.page .current{
    background: rgb(255, 217, 47);
}
//页面大小
var pageSize=4

function loadData(page){
	var title = $(".searchTitle").val().trim()
	var author = $(".searchAuthor").val().trim()
	var channelid = $(".searchChannel").val()
	$.ajax({
	url:"ContentServlet?action=getContent&title="+title+"&author="+author+"&page="+page+"&pageSize="+pageSize+"&channelid="+channelid,
	type:"get",
	success:function(value){
		var arr = value.data
		$("tbody").empty()
		for(var i=0; i<arr.length;i++){
			$("tbody").append("<tr>"+
                "<td><input type='checkbox' index='"+arr[i].id+"' class='option'></td>"+
      			"<td>"+arr[i].id+"</td>"+
                "<td>"+arr[i].channelname+"</td>"+
                "<td>"+arr[i].title+"</td>"+
                "<td>"+arr[i].desc+"</td>"+
                "<td>"+arr[i].createtime.substring(0,10)+"</td>"+
                //"<td>"+arr[i].imgurl+"</td>"+
                "<td><img src='upload/"+arr[i].imgurl+"' style='width:70px;height:55px;object-fit:cover'></td>"+
                "<td>"+arr[i].author+"</td>"+
                "<td><input type='button' value='修改' class='update' index='"+arr[i].id+"'><input type='button' value='删除' class='delete' index='"+arr[i].id+"' ></td>"+
            "</tr>")
		}
	},
	error:function(){
    	alert("查找失败")
    }
})
}

//加载分页
function loadPage(){
	var title = $(".searchTitle").val().trim()
	var author = $(".searchAuthor").val().trim()
	var channelid = $(".searchChannel").val()
	$.ajax({
	url:"ContentServlet?action=getCount&title="+title+"&author="+author+"&channelid="+channelid,
	type:"get",
	success:function(value){
		var count = value.msg
		$(".page").empty()
		$(".page").append("<li class='first'>首页</li>")
		$(".page").append("<li class='prev'>上一页</li>")
        for(var i=0;i<Math.ceil(count/pageSize);i++){
			if(i==0){
				$(".page").append("<li class='current item'>"+(i+1)+"</li>")
			}else{
				$(".page").append("<li class='item'>"+(i+1)+"</li>")
			}
		}
        $(".page").append("<li class='next'>下一页</li>")
        $(".page").append("<li class='last'>尾页</li>")
	},
	error:function(){
    	alert("查找失败")
    }
})
}

//加载栏目
function loadChannel(){
	$.ajax({
		url:"ChannelServlet?action=getChannel",
		type:"get",
		async:false,     //默认为异步请求,设置为同步
		success:function(value){
			var arr = value.data
			$(".searchChannel").append("<option value='0'>全部</option>")
			for(var i=0; i<arr.length;i++){
				$(".searchChannel").append("<option value='"+arr[i].id+"'>"+arr[i].channelname+"</option>")
			}
		},
		error:function(){
    		alert("栏目加载失败")
    }
	})
}
loadChannel()
//加载数据
loadData(1)
loadPage()

//搜索框搜索
$(".search_btn").on("click",function(){
	loadData(1)	
	loadPage()
})

//指定页码加载
$(".page").on("click",".item",function(){
	//数据切换
	loadData($(this).text())
	//样式切换
	$(this).addClass("current").siblings().removeClass("current")
	$(".checkAll").prop("checked",false)
})

//首页切换
$(".page").on("click",".first",function(){
	//数据切换
	loadData(1)
	//样式切换
	$(".item").removeClass("current").first().addClass("current")
})

//尾页切换
$(".page").on("click",".last",function(){
	//数据切换
	loadData($(".item").length)
	//样式切换
	$(".item").removeClass("current").last().addClass("current")
	$(".checkAll").prop("checked",false)
})

//上一页切换
$(".page").on("click",".prev",function(){
	if($("li.current").text()==1){
		layer.alert("当前已经是第一页啦")
		return
	}
	//数据切换
	loadData($("li.current").text()-1)
	//样式切换
	$("li.current").removeClass("current").prev().addClass("current")
	$(".checkAll").prop("checked",false)
})

//下一页切换
$(".page").on("click",".next",function(){
	if($("li.current").text()==$(".item").length){
		layer.alert("当前已经是最后页啦")
		return
	}
	//数据切换
	loadData(parseInt($("li.current").text())+1)
	//样式切换
	$("li.current").removeClass("current").next().addClass("current")
	$(".checkAll").prop("checked",false)
})

//单个删除
$("tbody").on("click",".delete",function(){
	var id = $(this).attr("index")
	
	layer.confirm('确定要删除吗?', function(){
	  $.ajax({
			url:"ContentServlet",
			type:"post",
			data:{
				id,
				action:"delete_id"
			},
			success:function(value){				
				layer.msg(value.msg,{
					  icon: 2,
					  time: 2000 // 设置 2 秒后自动关闭
					  },function(){
						location.reload()	``
					})		
			},
			error:function(){
				layer.msg("删除信息失败啦")
			}
			
		})
	}, function(){
		layer.msg("感谢手下留情")
	})
	
	/**if(confirm("确定要删除吗?")){
		$.ajax({
			url:"ContentServlet",
			type:"post",
			data:{
				id,
				action:"delete_id"
			},
			success:function(value){				
				alert(value.msg)
				location.reload()			
			},
			error:function(){
				alert("删除信息失败啦")
			}
			
		})
	}else{
		alert("感谢手下留情")
	}**/

})

//批量删除
$(".deleteAll").on("click",function(){
	var ids=""
	for(var i=0;i<$(".option:checked").length;i++){
		//$(".option:checked")[i].getAttribute("index")   //js方法
		ids +=$(".option:checked").eq(i).attr("index")+","
	}
	ids=ids.slice(0,-1)    //slice(start,end)  不包含end,支持负数截取
	
	if(ids.length==0){
		alert("请至少选择一项")
		return
	}
	
	if(confirm("确定要删除吗?")){
		$.ajax({
			url:"ContentServlet",
			type:"post",
			data:{
				ids,
				action:"deleteAll"
			},
			success:function(value){				
				alert(value.msg)
				location.reload()			
			},
			error:function(){
				alert("批量删除信息失败啦")
			}
			
		})
	}else{
		alert("感谢手下留情")
		location.reload()	
	}
})

//全选
$(".checkAll").on("change",function(){
	if($(".checkAll").prop("checked")){
		$(".option").prop("checked",true)
	}else{
		$(".option").prop("checked",false)
	}
	
})

$("tbody").on("click",".option",function(){
	var flag = true
	for(var i=0;i<$(".option").length;i++){
		flag &= $(".option").eq(i).prop("checked")
	}
	if(flag){
		$(".checkAll").prop("checked",true)
	}else{
		$(".checkAll").prop("checked",false)
	}
})

//添加
$(".add").on("click",function(){
	location.href="router?path=add"
})

//修改
$("tbody").on("click",".update",function(){
	$.cookie("id",$(this).attr("index"))
	location.href="router?path=add"
})

③内容管理添加|修改

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>添加|修改页面</title>
    <link rel="stylesheet" href="resources/css/add.css">
    <script src="resources/js/jquery.js"></script>
    <script src="resources/js/jquery.cookie.js"></script>
    <script src="resources/layer/layer.js"></script>
    <script src="resources/js/add.js" defer></script>
</head>
<body>
    <div class="container">
        <h3>信息添加</h3>
        <div class="item">
            <span>标题</span>
            <input type="text" class="title">
        </div>
        <div class="item">
            <span>栏目</span>
            <select class='channel'></select>
        </div>
        <div class="item">
            <span>摘要</span>
            <input type="text" class="desc">
        </div>
        <div class="item">
            <span>作者</span>
            <input type="text" class="author">
        </div>
        <div class="item">
            <span>创建时间</span>
            <input type="datetime-local" class="createtime">
        </div>
        <div class="item">
            <span>封面图</span>
            <form class="imgbox">
            	<input type="file" class="imgurl" name="imgurl">
            	<input type="hidden" class="file_value">
            </form>
            <div class="img_display"></div>
        </div>
        <div class="item">
            <span>内容</span>
            <!--  <textarea name="" id="" cols="30" rows="10" class="content"></textarea> -->
            <!-- 加载编辑器的容器 -->
			<script id="container" name="content" type="text/plain"></script>
			<!-- 配置文件 -->
			<script type="text/javascript" src="resources/utf8-jsp/ueditor.config.js"></script>
			<!-- 编辑器源码文件 -->
			<script type="text/javascript" src="resources/utf8-jsp/ueditor.all.js"></script>	
        </div>
        <div class="item">
            <input type="button" value="添加" class="add">
            <input type="button" value="取消" class="back">
        </div>
    </div>
</body>
</html>

*{
    padding: 0;
    margin: 0;
}

.container{
    width: 97%;
    margin: 30px auto;
    border: 7px solid rgb(247, 146, 146);
    border-radius: 70px 70px 70px 70px;
}

.container h3{
    position: relative;
    left: 450px;
    top: -28px;
    font-size: 30px;
    padding: 4px 6px;
    color: rgb(235, 136, 136);
    background: whitesmoke;
    display: inline;
}

.container .item{
    margin: 20px;
    display: flex;
    flex-direction: column;
}

.container .item span{
    font-size: 15px;
    margin-bottom: 8px;
    color: gray;
}

.container .item textarea,
.container .item select,
.container .item input{
    outline: none;
    padding: 3px 6px;
    border-radius: 3px;
    border: 1px solid gray;
}

.container .item textarea:hover,
.container .item select:hover,
.container .item input:hover{
    box-shadow: 1px 1px 2px greenyellow
}

.container .item textarea{
    min-height: 130px;
}

.container .item:last-child{
    flex-direction: row;
}

.container .item:last-child input{
    background: none;
    margin-left: 15px;
    font-size: 13px;
    padding: 2px 8px;
    color: gray;
}

.container .item:last-child input:hover{
    cursor: pointer;
}

var ue = UE.getEditor('container');
var action = "add"

//上传图片
$(".imgurl").on("change",function(){
	if($(".imgurl").val()){
		//对图片进行序列化
		console.log($(".imgbox")[0])
		var data = new FormData($(".imgbox")[0])  //把表单数据序列化
		console.log(data.get("imgurl").name)
		$.ajax({
			url:"upload",
			type:"post",
			data:data,
			contentType:false,       //发送的数据格式,默认是文本
			processData:false,       //处理数据,以对象形式上传的数据会被转化成字符串的形式上传
			success:function(value){
				console.log(value)
				$(".img_display").empty()
				$(".img_display").append("<img src='upload/"+value.imgurl+"' style='width:80px;height:auto;'>")
				//给隐藏域设置值
				$(".file_value").val(value.imgurl)
			},
			error:function(){
				alert("上传图像出错啦!")
			}
		})
		
	}else{
		$("file_value").val("")
		$(".img_display").empty()
		alert("请上传图片")
	}
})

//加载栏目
function loadChannel(){
	$.ajax({
		url:"ChannelServlet?action=getChannel",
		type:"get",
		async:false,     //默认为异步请求,设置为同步
		success:function(value){
			var arr = value.data
			for(var i=0; i<arr.length;i++){
				$(".channel").append("<option value='"+arr[i].id+"'>"+arr[i].channelname+"</option>")
			}
		},
		error:function(){
    		alert("栏目加载失败")
    	}
	})
}
loadChannel()

//修改
var id = $.cookie("id")

$.cookie("id","")
if(id){
	//回显	
	$.ajax({
		url:"ContentServlet?action=getById&id="+id,
		type:"get",
		success:function(value){
			var obj = value.data[0]
			$(".title").val(obj.title)
			$(".channel").val(obj.channelid)
			$(".desc").val(obj.desc)
			$(".author").val(obj.author)
			$(".createtime").val(obj.createtime)
			//隐藏域设置值
			$(".file_value").val(obj.imgurl)
			//缩略图回显
			$(".img_display").append("<img src='upload/"+obj.imgurl+"' style='width:80px;height:60px;object-fit:cover'>")
			//$(".content").val(obj.content)
			ue.ready(function(){
			    //设置编辑器的内容
			    ue.setContent(obj.content);
			});
			$(".add").val("修改")
			$("h3").text("信息修改")
			action="update"
		},
		error:function(){
			alert("回显信息失败")
		}
	})
}

//添加|修改
$(".add").on("click",function(){
	var title = $(".title").val()
	var desc = $(".desc").val()
	var author = $(".author").val()
	var createtime = $(".createtime").val()
	//获取隐藏域的值
	var imgurl = $(".file_value").val()
	//var content = $(".content").val()
	var content = ue.getContent()
	var channelid = $(".channel").val()
	
	$.ajax({
		url:"ContentServlet",
		type:"post",
		data:{
			id,
			title,
			channelid,
			desc,
			author,
			createtime,
			imgurl,
			content,
			action
		},
		success:function(value){
			alert(value.msg)
			location.href="router?path=content"
		},
		error:function(){
			alert("添加信息失败")
		}
	})
})

//取消
$(".back").on("click",function(){
	location.href="router?path=content"
})

 ④数据库连接|数据语句执行

package sql;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection {

	public static void main(String[] args) {

	}

	String driver = "com.mysql.jdbc.Driver";
//	String url = "jdbc:mysql://127.0.0.1:3306/first?useUnicode=true&characterEncoding=utf-8&serverTimezone=UTC&useSSL=true";
	String url="jdbc:mysql://localhost:3306/hbu?useUnicode=true&characterEncoding=UTF-8";
	String user = "root";
	String password = "123456";

	public Connection conn;

	public DBConnection() {

		try {
			Class.forName(driver);
			conn = (Connection) DriverManager.getConnection(url, user, password);//

			// if(!conn.isClosed())
			// System.out.println("Succeeded connecting to the Database!");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void close() {
		try {
			this.conn.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
package sql;

import java.rmi.StubNotFoundException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MysqlUtil {

	public static void main(String[] args) {
		
//		String sqlcount = "select count(*) from admin";
//		String sql = "select * from admin";
//		String[] colums = {"id","account","password"};
//		String json = getJsonBySql(sqlcount, sql, colums);
//		System.out.println(json);
		
		/*String sql = "insert into t_student(name,age,sex) values(\"张三\",21,\"男\")";
        System.out.println(add(sql));*/
		
		
		/*String sqldel = "delete from gq_user where id=11";
        System.out.println(del(sqldel));*/

		/*String sqlupdate ="update gq_user set age = 30 where username=\"gs1\"";
        System.out.println(update(sqlupdate));*/

		/*String sql = "select count(*) from gq_user";
		System.out.println(getCount(sql));*/
		
		/*String[] col = {"id","name","age"};
		String sql = "select * from t_student";
		String sqlCount = "select count(*) from t_student";
		String strJson = getJsonBySql(sqlCount,sql,col);
        System.out.println(strJson);*/
		
		/*String sqlcount = "select count(*) from gq_user";
		String sql="select * from gq_user";
		String[] col = {"username","age","id","sex","salary"};
		System.out.println(getJsonBySql(sqlcount, sql, col));*/

		/*String sql = "select * from t_user";
        String[] column = {"id","username","password","available"};
        ArrayList<String[]> strings = MysqlUtil.showUtil(sql, column);
        for (String[] string : strings) {
            System.out.println(Arrays.toString(string));
        }*/

		String sql = "select * from student";
		String[] strs = {"s_id","s_name"};
		String data = getJsonBySql(sql,strs);
		System.out.println(data);


	}
	
	/*添加*/
	public static int add(String sql) {
		// System.out.println("sql语句是:" + sql);
        int i=0;
        //数据库连接
        DBConnection db = new DBConnection();
        try {        
            PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
            i=preStmt.executeUpdate();
            preStmt.close();
            db.close();//关闭连接 
            System.out.println("数据插入成功,sql语句是:" + sql);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i;//返回影响的行数,1为执行成功;
    }



   /*修改数据*/
    public static int update(String sql) {
        int i =0;
        DBConnection db = new DBConnection();
        try {
            PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
            i = preStmt.executeUpdate();
            preStmt.close();
            db.close();
            System.out.println("数据更新成功,sql语句是:" + sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }
    

    /*删除*/
    public static int del(String delstr) {
        int i=0;
        DBConnection db = new DBConnection();
        try {    
            PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(delstr);
            i=preStmt.executeUpdate();
            //executeUpdate()返回受影响的行数
            preStmt.close();
            db.close();
            System.out.println("数据删除成功,sql语句是:" + delstr);
        } catch (SQLException e){
            e.printStackTrace();
        }
        return i;
    }

    /*查询数量*/
    public static int getCount(String sql) {
        int sum = 0;
        DBConnection db = new DBConnection();
        try {
            Statement stmt = (Statement) db.conn.createStatement();
            ResultSet rs = (ResultSet) stmt.executeQuery(sql);
            while (rs.next()) {
                sum += rs.getInt(1);
            }
            rs.close();
            db.close();
        } catch (Exception e) {
            // TODO: handle exception
        }
        return sum;
    }

    /**
     *功能描述 查询json数据带数据总量
     * @author 郭帅
     * @date 2021-03-22 10:30
     * @param sqlcount 查询数量的sql
     * @param sql 查询具体数据的sql
     * @param colums 查询的字段
     * @return java.lang.String
     */
    public static String getJsonBySqlDataGrid( String sqlcount,String sql,String[] colums){
        int count = getCount(sqlcount);
        System.err.println("标红信息展示sql:" + sql);
        ArrayList<String[]>  result = new ArrayList<String[]>();
        DBConnection db = new DBConnection();
        try {
            Statement stmt = (Statement) db.conn.createStatement();
            ResultSet rs = (ResultSet) stmt.executeQuery(sql);
            while(rs.next()){
                String[] dataRow = new String[colums.length];
                for( int i = 0; i < dataRow.length; i++ ) {
                    dataRow[i] = rs.getString( colums[i] );
                }
                result.add(dataRow);
            }
            rs.close();
            db.close();//
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return listToJsonDataGrid(result,colums,count);
    }
    
    /**
     *功能描述 查询json数据
     * @author 郭帅
     * @date 2021-03-22 10:30
     * @param sql 查询具体数据的sql
     * @param colums 查询的字段
     * @return java.lang.String
     */
    public static String getJsonBySql( String sql,String[] colums){
       
        System.err.println("标红信息展示sql:" + sql);
        ArrayList<String[]>  result = new ArrayList<String[]>();
        DBConnection db = new DBConnection();
        try {
            Statement stmt = (Statement) db.conn.createStatement();
            ResultSet rs = (ResultSet) stmt.executeQuery(sql);
            while(rs.next()){
                String[] dataRow = new String[colums.length];
                for( int i = 0; i < dataRow.length; i++ ) {
                    dataRow[i] = rs.getString( colums[i] );
                }
                result.add(dataRow);
            }
            rs.close();
            db.close();//
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return listToJson(result,colums);
    }

    /**
     *功能描述 查询数据
     * @author 郭帅
     * @date 2021-03-22 10:38
     * @param sql 查询具体数据的sql
     * @param colums  查询的字段
     * @return java.util.ArrayList<java.lang.String[]>
     */
    public static ArrayList<String[]> showUtil( String sql, String[] colums){

        ArrayList<String[]>  result = new  ArrayList<String[]>();
        DBConnection db = new DBConnection();
        try {
            Statement stmt = (Statement) db.conn.createStatement();
            ResultSet rs = (ResultSet) stmt.executeQuery(sql);

            while(rs.next()){
                String[] dataRow = new String[colums.length];
                for( int i = 0; i < dataRow.length; i++ ) {
                    dataRow[i] = rs.getString( colums[i] );
                }
                result.add(dataRow);
            }
            rs.close();
            db.close();//
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return result;
    }

    /**
     * 转化为json数据字符串
     * @param
     * @return
     */
    public static String listToJsonDataGrid( ArrayList<String[]> list,String[] colums,int count) {

    	String jsonStr = "{\"code\":0,\"msg\":\"成功了\",\"count\":"+count+",\"data\":[";
    			for(int i = 0; i < list.size(); i++) {
    				String arr = "{";
    				for( int j = 0; j < list.get(0).length; j++) {
    					
    					if( list.get(i)[j] == null || "NULL".equals(list.get(i)[j])) {
    						arr += "\"" + colums[j] + "\":\"\"";
    					}else {
    						arr += "\"" + colums[j] + "\""+":" ;
    						arr +=  "\"" + list.get(i)[j].replace("\"","\\\"") + "\"";
    					}
    					
    					if( j < list.get(0).length - 1 ) {
    						arr += ",";
    					}
    				}
    				arr += "}";
    				if( i < list.size() - 1 ) {
						arr += ",";
					}
    				
    				jsonStr += arr;
    			}
    			jsonStr += "]}";
    	
    	return jsonStr;
    }
    
    /**
     * 转化为json数据字符串
     * @param
     * @return
     */
    public static String listToJson( ArrayList<String[]> list,String[] colums) {

    	String jsonStr = "{\"code\":0,\"msg\":\"成功了\",\"data\":[";
    			for(int i = 0; i < list.size(); i++) {
    				String arr = "{";
    				for( int j = 0; j < list.get(0).length; j++) {
    					
    					if( list.get(i)[j] == null || "NULL".equals(list.get(i)[j])) {
    						arr += "\"" + colums[j] + "\":\"\"";
    					}else {
    						arr += "\"" + colums[j] + "\""+":" ;
    						arr +=  "\"" + list.get(i)[j].replace("\"","\\\"") + "\"";
    					}
    					
    					if( j < list.get(0).length - 1 ) {
    						arr += ",";
    					}
    				}
    				arr += "}";
    				if( i < list.size() - 1 ) {
						arr += ",";
					}
    				
    				jsonStr += arr;
    			}
    			jsonStr += "]}";
    	
    	return jsonStr;
    }

}

 ⑤首页栏目内容加载servlet

package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sql.MysqlUtil;

/**
 * Servlet implementation class HbuServlet
 */
@WebServlet("/hbu")
public class HbuServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HbuServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json;charset=utf-8");
		String action = request.getParameter("action");
		String[] colums = {"id","title","desc","content","author","createtime","channelid","imgurl"};
		String[] channel_colums = {"id","channelname"};
		String res = "";
		switch(action) {
		//查找内容
		case "getContent":
			String channelid = request.getParameter("channelid");
			String limit = request.getParameter("limit");
			String sql = "select * from content where available = 1 and channelid = "+channelid+" order by createtime desc";
			if(limit!=null&&!"".equals(limit)) {
				sql +=" limit 0,"+limit;
			}
			res = MysqlUtil.getJsonBySql(sql, colums);
			break;
			
		//查找栏目名称
		case "getChannel":
			channelid = request.getParameter("channelid");
			sql = "select * from channel where id = "+channelid;
			res = MysqlUtil.getJsonBySql(sql, channel_colums);
			break;
			
		//查找根据id查内容
		case "getDetail":
			String contentid = request.getParameter("contentid");
			sql = "select * from content where id = "+contentid;
			res = MysqlUtil.getJsonBySql(sql, colums);
			break;
			
		default:
			break;
		}
		response.getWriter().write(res);
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

⑥内容管理servlet

package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sql.MysqlUtil;

/**
 * Servlet implementation class ContentServlet
 */
@WebServlet("/ContentServlet")
public class ContentServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ContentServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json;charset=utf-8");
		String action = request.getParameter("action");
		String title = request.getParameter("title");
		String author = request.getParameter("author");
		String page = request.getParameter("page");
		String pageSize = request.getParameter("pageSize");
		String channelid = request.getParameter("channelid");
		String[] colums = {"id","title","desc","content","author","createtime","channelid","imgurl"};
		String[] colums_all = {"id","title","channelname","desc","content","author","createtime","channelid","imgurl"};
		String res = "{\"msg\":\"查找失败\",\"code\":0}";
		switch(action) {
		case "getContent":
			String sql="select content.*,channelname from content,channel where content.channelid = channel.id and available=1 and title like \"%"+title+"%\" and author like \"%"+author+"%\"";
			if(!"0".equals(channelid)) {
				sql +=" and channelid="+channelid;
			}
			sql +=" order by createtime desc limit "+(Integer.parseInt(page)-1)*Integer.parseInt(pageSize)+","+pageSize;
			res = MysqlUtil.getJsonBySql(sql, colums_all);
			
			break;
			
		case "getCount":
			channelid = request.getParameter("channelid");
			sql="select count(*) from content where available=1 and title like \"%"+title+"%\" and author like \"%"+author+"%\"";
			if(!"0".equals(channelid)) {
				sql +=" and channelid="+channelid;
			}
			int count = MysqlUtil.getCount(sql);
			res = "{\"msg\":\""+count+"\",\"code\":0}";
			break;
			
		case "getById":
			String id = request.getParameter("id");
			sql="select * from content where id="+id;
			res = MysqlUtil.getJsonBySql(sql, colums);
			
			break;
		
		default:
			break;
		}
		response.getWriter().write(res);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json;charset=utf-8");
		String action = request.getParameter("action");
		String res = "{\"msg\":\"删除失败\",\"code\":0}";
		String id = request.getParameter("id");
		switch(action) {
		case "delete_id":
			String sql="update content set available=0 where id="+id;
			int num = MysqlUtil.update(sql);
			if(num>0) {
				res = "{\"msg\":\"删除成功\",\"code\":1}";
			}
			break;
			
		case "deleteAll":
			String ids = request.getParameter("ids");
			sql="update content set available=0 where id in("+ids+")";
			num = MysqlUtil.update(sql);
			if(num>0) {
				res = "{\"msg\":\"批量删除成功\",\"code\":1}";
			}
			break;
		
		case "add":
			String title = request.getParameter("title");
			String desc = request.getParameter("desc");
			String author = request.getParameter("author");
			String imgurl = request.getParameter("imgurl");
			String createtime = request.getParameter("createtime");
			String channelid = request.getParameter("channelid");
			String content = request.getParameter("content");
			content = content.replaceAll("\"", "\'");
			sql="insert into content(title,`desc`,content,author,createtime,channelid,imgurl,available) values(\""+title+"\",\""+desc+"\",\""+content+"\",\""+author+"\",\""+createtime+"\","+channelid+",\""+imgurl+"\",1)";
			res = "{\"msg\":\"添加信息失败\",\"code\":0}";
			num = MysqlUtil.add(sql);
			if(num>0) {
				res = "{\"msg\":\"添加信息成功\",\"code\":1}";
			}
			break;
			
		case "update":
			id = request.getParameter("id");
			System.out.println(id);
			title = request.getParameter("title");
			channelid = request.getParameter("channelid");
			imgurl = request.getParameter("imgurl");
			desc = request.getParameter("desc");
			author = request.getParameter("author");
			createtime = request.getParameter("createtime");
			content = request.getParameter("content");
			sql="update content set title='"+title+"',`desc`='"+desc+"',content='"+content+"',author='"+author+"',createtime='"+createtime+"',channelid='"+channelid+"',imgurl='"+imgurl+"' where id = "+id;
			res = "{\"msg\":\"修改信息失败\",\"code\":0}";
			num = MysqlUtil.update(sql);
			if(num>0) {
				res = "{\"msg\":\"修改信息成功\",\"code\":1}";
			}
			break;
		
		default:
			break;
		}
		response.getWriter().write(res);
	}

}

 ⑦验证码servlet

package servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;

/**
 * Servlet implementation class CaptchaServlet
 */
@WebServlet("/captcha")
public class CaptchaServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CaptchaServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		//定义图形验证码的长、宽、验证码字符数、干扰元素个数
		CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 100, 4, 20);
		//CircleCaptcha captcha = new CircleCaptcha(200, 100, 4, 20);
		//图形验证码写出,可以写出到文件,也可以写出到流
		//captcha.write("d:/circle.png");
		//获取验证码的文字内容
		//System.out.println(captcha.getCode());
		
		HttpSession session = request.getSession();
		session.setAttribute("captcha", captcha.getCode());
		
		//写出到浏览器
		captcha.write(response.getOutputStream());
		//验证图形验证码的有效性,返回boolean值
		//captcha.verify("1234");
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

}

⑧图片上传servlet

package servlet;

import java.io.IOException;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

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

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import sql.MysqlUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class UploadServlet
 */
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//设置请求和响应的编码格式
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/json;charset=UTF-8"); 
		resp.setCharacterEncoding("utf-8");
        
		//表单
		String realFileName="";
		
        //核心Api
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload fileUpload = new ServletFileUpload(factory);
        
        //判断是否是muitipart/form-data类型
        if(!ServletFileUpload.isMultipartContent(req)) {
            //resp.getWriter().println("表单的enctype属性不是multipart/form-data类型");
        	System.out.println("表单的enctype属性不是multipart/form-data类型");
            return;
        }
        
        //设置单个文件上传大小
        fileUpload.setFileSizeMax(8*1024*1024); 
        //设置总上传文件大小
        fileUpload.setSizeMax(60*1024*1024);
        
        //解析请求
        try {
            List<FileItem> parseRequest = fileUpload.parseRequest(req);
            //获取数据
            for (FileItem fileItem : parseRequest) {
                //判断数据类型是不是普通的form表单字段
                if(!fileItem.isFormField()) {
                    //上传文件
                    String fileName = fileItem.getName();
                    InputStream fileStream = fileItem.getInputStream();
                    //定义保存的父路径(服务器部署的真实路径)
                    String parentDir = this.getServletContext().getRealPath("/upload");
                    //定义绝对路径
                    //String parentDir = "D:\\eclipse-workspace-new\\myWish\\WebContent\\upload";
                    //使用UUID+文件名的方式,避免文件重名
                    realFileName = UUID.randomUUID().toString()+"-"+fileName;
                    //创建要保存的文件
                    File file = new File(parentDir,realFileName);
                    //判断文件夹是否存在
                    if(!file.getParentFile().exists()) {
                        //创建文件夹[多级文件夹]file.madir是创建单一文件夹
                        file.getParentFile().mkdirs();
                    }
                    
                    //创建输出流
                    OutputStream out = new FileOutputStream(file);
                    //创建字节缓存
                    byte[] buffer = new byte[1024];
                    int len = -1;
                    //一次读取1kb(1024byte),返回-1表明读取完毕
                    while((len = fileStream.read(buffer))!=-1) {
                        //一次写入1kb(1024byte)
                        out.write(buffer,0, len);
                    }
                    System.out.println(realFileName);
                  
                    //冲刷流资源
                    out.flush();
                    //关闭流
                    out.close();
                    fileStream.close();
                    
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } 
        String json="";
        if(realFileName!=null && !"".equals(realFileName)) {
        	 json = "{\"msg\":\"上传成功\",\"imgurl\":\""+realFileName+"\"}";
        }else {
        	 json = "{\"msg\":\"上传失败\"}";
        }
		resp.getWriter().print(json);
		
	}

}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:/a/339745.html

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

[pip] pip 包管理及虚拟环境的使用

文章目录 &#x1f4e6;Python & pip&#x1f680;pip 常用功能&#x1f528; Flask 应用示例&#xff1a;常用功能&#x1f528;Flask 应用示例&#xff1a;用虚拟环境管理 Flask 的不同版本 &#x1f680;总结 &#x1f4e6;Python & pip https://www.python.org/htt…

AtCoder Beginner Contest 221 H. Count Multiset(容斥 dp 拆分数 差分 数形结合)

题目 给定m,n(m<n<5e3)&#xff0c; 求大小为k的多重集合&#xff0c;满足元素和为n&#xff0c; 且每种数在集合中出现的次数都小于等于m的集合数有多少个 答案对998244353取模 思路来源 官方题解 「解题报告」[ABC221H] Count Multiset - K8He - 洛谷博客 Solu…

【RT-DETR有效改进】遥感旋转网络 | LSKNet动态的空间感受野网络(轻量又提点)

前言 大家好&#xff0c;我是Snu77&#xff0c;这里是RT-DETR有效涨点专栏。 本专栏的内容为根据ultralytics版本的RT-DETR进行改进&#xff0c;内容持续更新&#xff0c;每周更新文章数量3-10篇。 专栏以ResNet18、ResNet50为基础修改版本&#xff0c;同时修改内容也支持Re…

掌上单片机实验室 – 低分辨率编码器测速方式完善(24)

一、背景 本以为“掌上单片机实验室”这一主题已告一段落&#xff0c;可最近在测试一批新做的“轮式驱动单元”时&#xff0c;发现原来的测速算法存在问题。 起因是&#xff1a;由于轮式驱动单元的连线较长&#xff0c;PCB体积也小&#xff0c;导致脉冲信号有干扰&#xff0c;加…

Linux系统监控:保障稳定性与性能的关键

Linux操作系统作为广泛应用于服务器和嵌入式设备的开源操作系统&#xff0c;对于系统监控的需求尤为重要。通过对Linux系统进行有效的监控&#xff0c;管理员可以实时了解系统的运行状态、识别潜在问题并采取相应的措施。本文将介绍Linux系统监控的基本原理、常用工具和关键指标…

央视推荐的护眼台灯是哪款?学生专用台灯第一品牌

近视问题在我国十分严重&#xff0c;据相关调查数据显示&#xff0c;我国有7亿近视人口。特别是在现代&#xff0c;青少年成为近视高发人群&#xff0c;其中大部分近视的原因与长时间不正确用眼导致的眼睛疲劳有关。台灯作为许多家庭中的小家电&#xff0c;不论是上班族还是孩子…

一文搞懂Microsoft Copilot品种及定价说明

Microsoft Copilot 是一个 AI 助手&#xff0c;提供跨 Microsoft Cloud 的创新解决方案。Copilot 使复杂的任务更易于管理&#xff0c;从而促进协作环境并增强用户体验。 目前Copilot一共有这么几种&#xff1a; 一、必应中的copilot 在edge浏览器侧边栏中使用&#xff0c;这…

ESP32-TCP服务端(Arduino)

将ESP32设置为TCP服务器 介绍 TCP&#xff08;Transmission Control Protocol&#xff09;传输控制协议&#xff0c;是一种面向连接的&#xff08;一个客户端对应一个服务端&#xff09;、可靠的传输层协议。在TCP的工作原理中&#xff0c;它会将消息或文件分解为更小的片段&a…

通俗易懂理解小波池化/WaveCNet

重要说明&#xff1a;本文从网上资料整理而来&#xff0c;仅记录博主学习相关知识点的过程&#xff0c;侵删。 一、参考资料 github代码&#xff1a;WaveCNet 通俗易懂理解小波变换(Wavelet Transform) 二、相关介绍 关于小波变换的详细介绍&#xff0c;请参考另一篇博客&…

大模型学习之书生·浦语大模型6——基于OpenCompass大模型评测

基于OpenCompass大模型评测 关于评测的三个问题Why/What/How Why What 有许多任务评测&#xff0c;包括垂直领域 How 包含客观评测和主观评测&#xff0c;其中主观评测分人工和模型来评估。 提示词工程 主流评测框架 OpenCompass 能力框架 模型层能力层方法层工具层 支持丰富…

使用Go发送HTTP GET请求

在Go语言中&#xff0c;我们可以使用net/http包来发送HTTP GET请求。以下是一个简单的示例&#xff0c;展示了如何使用Go发送HTTP GET请求并获取响应。 go复制代码 package main import ( "fmt" "io/ioutil" "net/http" …

用BK7251播放音乐

单片机的第一道难关无疑是烧录&#xff0c;如果烧录解决了&#xff0c;那么就有资格挑战各种坑了。 BK7251播放MP3 一、折腾材料 1、软件SDK&#xff1a; bk7251_audio_release_20190826_0701&#xff08;BK7251 rtt sdk&#xff09;&#xff0c;可以从github&#xff0c;gite…

HCIP网络的类型

一.网络类型&#xff1a; 点到点 BMA&#xff1a;广播型多路访问 -- 在一个MA网络中同时存在广播&#xff08;泛洪&#xff09;机制 NBMA&#xff1a;非广播型多路访问 -- 在一个MA网络中&#xff0c;没有泛洪机制-----不怎么使用了 MA&#xff1a;多路访问 -- 在一个…

基于光口的以太网 udp 回环实验

文章目录 前言一、系统框架整体设计二、系统工程及 IP 创建三、UDP回环模块修改说明四、接口讲解五、顶层模块设计六、下载验证前言 本章实验我们通过网络调试助手发送数据给 FPGA,FPGA通过光口接收数据并将数据使用 UDP 协议发送给电脑。 提示:任何文章不要过度深思!万事万…

电工技术实验-电路元件伏安特性测绘

一、 实验目的 1、学会识别常用电路元件的方法 2、验证线性电阻、非线性电阻元件的伏安特性 3、熟悉实验台上直流电工仪表和设备的使用方法 二、实验器材 可调直流稳压电源、直流数字毫安表、直流数字电压表、万用表 二极管、稳压管、白炽灯、线性电阻 三、实验原理 任…

低压防雷箱综合选型应用方案

低压防雷箱是一种用于保护低压配电系统免受雷电过电压的影响的装置&#xff0c;它主要由防雷箱模块、浪涌保护器SPD、接地线等组成。本文将介绍低压防雷箱的作用原理和行业应用解决方案&#xff0c;以及低压防雷箱的选型方法。 低压防雷箱的作用原理 低压防雷箱的作用原理是利…

革新区块链:代理合约与智能合约升级的未来

作者 张群&#xff08;赛联区块链教育首席讲师&#xff0c;工信部赛迪特聘资深专家&#xff0c;CSDN认证业界专家&#xff0c;微软认证专家&#xff0c;多家企业区块链产品顾问&#xff09;关注张群&#xff0c;为您提供一站式区块链技术和方案咨询。 代理合约&#xff08;Prox…

职业规划,软件开发工程师的岗位任职资格

软件工程师是指从事软件开发的人&#xff0c;主要的工作涉及到项目培训和项目设计两个方面。在实际工作中&#xff0c;软件工程师是一个广义的概念&#xff0c;包括了很多与软件相关的人员。除开最基础的编程语言&#xff0c;还有数据库语言等等。从事这份工作&#xff0c;需要…

多标签节点分类

Multi-Label Node Classification on Graph-Structured Data,TMLR’23 Code 学习笔记 图结构数据的多标签分类 节点表示或嵌入方法 通常会生成查找表&#xff0c;以便将相似的节点嵌入的更近。学习到的表示用作各种下游预测模块的输入特征。 表现突出的方法是基于随机游走(ran…

【Spring 篇】MyBatis注解开发:编写你的数据乐章

欢迎来到MyBatis的音乐殿堂&#xff01;在这个充满节奏和韵律的舞台上&#xff0c;注解是我们编写数据乐章的得力助手。无需繁琐的XML配置&#xff0c;通过简单而强大的注解&#xff0c;你将能够轻松地与数据库交互。在这篇博客中&#xff0c;我们将深入探讨MyBatis注解开发的精…