前端技术: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);
}
}