結組作業,第二次衝刺(5)

saccharin發表於2024-06-14

今天是第二次衝刺的第5天,昨天完成了收藏功能,今天我們準備完成廣告功能,可以將廣告掛在想要掛的地方,可以是圖片,可以是文字,這個功能更可能現在用不到,但是以後可能用的到,以下為今日部分程式碼:

package com.work.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.work.common.utils.BaseUtil;
import com.work.common.utils.JsonUtil;
import com.work.pojo.Adver;
import com.work.pojo.User;
import com.work.service.AdverService;

@Controller
@RequestMapping("/server/adver")
public class AdverController extends BaseUtil{

    @Autowired
    private AdverService adverService;
    
    //去廣告列表
    @RequestMapping("/goAdverList")
    public ModelAndView goAdverList(ModelAndView mv){
        mv.setViewName("server/adverManage/adverList");
        return mv;
    }
    
    //獲取廣告列表
    @RequestMapping("/getAdverList")
    public void getAdverList(HttpServletResponse response,Adver adver,Integer page,Integer limit){
        if(page == null){
            page = 1;
        }
        if(limit == null){
            limit = 10;
        }
        int totalCount = adverService.getAdverListCount(adver);
        List<Adver> list = adverService.getAdverList(adver,(page-1) * limit, limit);
        output(response,JsonUtil.buildJsonByTotalCount(list, totalCount));
    }
    
    //去新增廣告
    @RequestMapping("/goAddAdver")
    public ModelAndView goAddAdver(ModelAndView mv){
        mv.setViewName("server/adverManage/addAdver");
        return mv;
    }
    
    //新增廣告
    @RequestMapping("/addAdver")
    public void addAdver(HttpServletRequest request,HttpServletResponse response,Adver adver){
        User serverUser = (User) request.getSession().getAttribute("serverUser");
        adver.setCreateTime(new Date());
        adver.setUserId(serverUser.getUserId());
        adverService.addAdver(adver);
        output(response,JsonUtil.buildFalseJson(0, "新增成功!"));
    }
    
    //去編輯廣告
    @RequestMapping("/goUpdateAdver")
    public ModelAndView goUpdateAdver(ModelAndView mv,Integer id){
        Adver adver = adverService.getAdverById(id);
        mv.addObject("adver", adver);
        mv.setViewName("server/adverManage/updateAdver");
        return mv;
    }
    
    //編輯廣告
    @RequestMapping("/updateAdver")
    public void updateAdver(HttpServletResponse response,Adver adver){
        adverService.updateAdver(adver);
        output(response,JsonUtil.buildFalseJson(0, "編輯成功!"));
    }

    //刪除廣告
    @RequestMapping("/deleteAdver")
    public void deleteAdver(HttpServletResponse response,Integer id){
        adverService.deleteAdverById(id);
        output(response,JsonUtil.buildFalseJson(0, "刪除成功!"));
    }

    
}

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<html>
<head>
<meta charset="utf-8">
<title>新增廣告</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">

<link rel="stylesheet" href="${ctx}/server/layui/css/layui.css"
    media="all" />
<link rel="stylesheet" href="${ctx}/server/font-awesome/css/font-awesome.min.css">
<style type="text/css">
#Images li{
    float:left;
    margin-left:10px;
    height:300px;
    margin-bottom:20px;
}
#Images img{
    height:300px;
}
.img_del{
    cursor: pointer;
}
</style>
</head>
<body>
    <div style="margin: 15px;">
        <div class="layui-form">
            <div class="layui-form-item">
                <label class="layui-form-label">標題:</label>
                <div class="layui-input-block">
                    <input type="text" name="title" autocomplete="off" class="layui-input" lay-verify="title" placeholder="請輸入標題" style="width:390px">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">內容:</label>
                <div class="layui-input-block">
                     <textarea placeholder="請輸入內容" class="layui-textarea" name="content" lay-verify="content"></textarea>
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">廣告位置:</label>
                <div class="layui-input-block">
                    <input type="text" name="position" autocomplete="off" class="layui-input" lay-verify="position" placeholder="請輸入位置" style="width:390px">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">圖片:</label>
                <div class="layui-input-block">
                    <button type="button" class="layui-btn" id="uploadNewImg">圖片上傳</button> 
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <ul class="layer-photos-demo" id="Images" lay-verify="uploadNewImg"></ul>
            </div>            
            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit="" lay-filter="demo1">確認</button>
                    <button onclick="goBack();" class="layui-btn layui-btn-primary">返回</button>
                </div>
            </div>
        </div>
    </div>
</body>
<script type="text/javascript" src="${ctx}/server/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="${ctx}/server/layui/layui.js"></script>

<script type="text/javascript">
var image = '';

//圖片集合刪除
function delImages(){
    var i_s=$("#Images .img_del");
    for(var i=0;i<i_s.length;i++){
        $("#Images .img_del").get(i).index=i;
        $("#Images .img_del:eq("+i+")").click(function(){
            var i=this.index;
            $("#Images li:eq("+i+")").remove();
        })
    }
}
layui.use('upload', function() {
    var $ = layui.jquery, upload = layui.upload;
    upload.render({
        url: '${ctx}/imageUpload/systemImage.action'
        ,elem: '#uploadNewImg' //指定原始元素,預設直接查詢class="layui-upload-file"
        ,method: 'post', //上傳介面的http型別
        dataType:"json"
        ,multiple: true
        ,before: function(obj){
          //預讀本地檔案示例,不支援ie8
          obj.preview(function(index, file, result){
          });
        }
        ,done: function(res){
            //$('#Images').append('<li><img layer-src="'+ res.msg +'" src="'+ res.msg +'" alt="'+ res.msg +'" class="layui-upload-img"><div class="operate"><i class="layui-icon img_del">&#xe640;</i></div></li>');
            $('#Images').html('<li><img src="'+ res.msg +'" class="layui-upload-img"><div class="operate"><i class="layui-icon img_del">&#xe640;</i></div></li>');
            image = res.msg;
            delImages();
        }
    });
});



layui.use([ 'form', 'layer'],
        function() {
         form = layui.form, layer = layui.layer;
         //自定義驗證規則
        form.verify({    
            title : function(value) {
                if (value.trim() == '') {
                    return '標題不能為空';
                }
            },
            content : function(value) {
                if (value.trim() == '') {
                    return '內容不能為空';
                }
            },
            position : function(value) {
                if (value.trim() == '') {
                    return '位置不能為空';
                }
            },
            uploadNewImg : function(value) {
                if ($('#Images li').length < 1) {
                    return '請上傳圖片';
                }
            }
        });
         
        //監聽提交
        form.on('submit(demo1)', function(data) {
            $.ajax({
                type : "post",
                url : "${ctx}/server/adver/addAdver.action",
                dataType:"json",
                data : {
                    "title":data.field.title,
                    "content":data.field.content,
                    "position":data.field.position,
                    "image":image
                },
                success : function(result) {
                    if(result.code==0){
                        layer.msg("新增成功");
                        setTimeout(function () {
                             layer.closeAll("iframe");
                              //重新整理父頁面
                               parent.location.reload();
                          }, 1000);
                    } else{
                        layer.msg(result.msg,{time:2000});
                    }
                },error:function(){
                    layer.msg("新增失敗");
                }
            });
            return false;
        });
    });

function goBack(){
    window.history.go(-1);
}
</script>
</html>

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<html>
<head>
<title>廣告列表</title>
<link rel="stylesheet" href="${ctx}/server/layui/css/layui.css"
    media="all">
</head>
<body>
    <form class="layui-form layui-form-pane" action="">
        <blockquote class="layui-elem-quote news_search">
            <div class="layui-form-item">
                <div class="layui-inline pane-select">
                    <label class="layui-form-label">廣告編號</label>
                    <div class="layui-input-block ">
                        <input type="text" id="adverId" name="adverId"
                            lay-verify="required|number" placeholder="請輸入廣告編號"
                            autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div class="layui-inline pane-select">
                    <label class="layui-form-label">標題</label>
                    <div class="layui-input-block ">
                        <input type="text" id="title" name="title"
                            lay-verify="required|number" placeholder="請輸入標題"
                            autocomplete="off" class="layui-input">
                    </div>
                </div>
                <div style="float: right;">
                    <a class="layui-btn search_btn" onclick="doSearch()"> <i
                        class="layui-icon">&#xe615;</i>查詢
                    </a>
                </div>
            </div>
        </blockquote>
    </form>
    <fieldset class="layui-elem-field site-demo-button">
        <div>
            <button id="addAdver" style="margin-left: 10px;"
                class="layui-btn layui-btn-primary">新增廣告</button>
        </div>
    </fieldset>
    <table class="layui-table" id="forum" lay-filter="forum"
        lay-data="{id: 'forum'}"></table>
    <script type="text/html" id="toolBar">
        <a class="layui-btn layui-btn-mini" lay-event="updateAdver" >編輯</a>
        <a class="layui-btn layui-btn-mini layui-btn-danger" lay-event="deleteAdver" >刪除</a>
    </script>
    
    <script type="text/javascript" src="${ctx}/server/js/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="${ctx}/server/layui/layui.all.js"></script>
    <script>
        layui.use([ 'layer', 'table', 'laydate' ], function() {
            table = layui.table;
            layer = layui.layer;
            var laydate = layui.laydate;
            //--------------方法渲染TABLE----------------
            //日期範圍
            laydate.render({
                elem : '#startAndendTime',
                calendar : true,
                range : '~'
            });
            getlist(null, null);
        });
        function doSearch() {
            var adverId = $("#adverId").val();
            var title = $("#title").val();
            getlist(adverId, title);
        }

        function getlist(adverId, title) {
            tableIns = table.render({
                elem : '#forum',
                id : 'forum',
                method : 'post',
                where : {
                    'id' : adverId,
                    'title' : title
                },
                url : '${ctx}/server/adver/getAdverList.action',
                cols : [ [ {
                    field : 'id',
                    title : '編號',
                    width : 80,
                    align : 'center',
                    fixed : true,
                    sort : true
                }, {
                    field : 'userId',
                    title : '所屬使用者',
                    width : 140,
                    align : 'center'
                }, {
                    field : 'title',
                    title : '標題',
                    width : 140,
                    align : 'center'
                }, {
                    field : 'position',
                    title : '位置',
                    width : 140,
                    align : 'center'
                }, {
                    field : 'createTime',
                    title : '釋出時間',
                    width : 180,
                    align : 'center',
                    sort : true,
                }, {
                    title : '操作',
                    width : 180,
                    align : 'center',
                    fixed : 'right',
                    toolbar : '#toolBar'
                } ] ],
                page : true,
                limits : [ 10, 20, 30, 50, 100 ],
                limit : 10, //預設採用20
                width : '100%',
                height : 'auto',
                loading : true,
                even : true,
                response : {
                    statusName : 'code' //資料狀態的欄位名稱,預設:code
                    ,
                    statusCode : 0 //成功的狀態碼,預設:0
                    ,
                    countName : 'count' //資料總數的欄位名稱,預設:count
                    ,
                    dataName : 'data' //資料列表的欄位名稱,預設:data
                },
                done : function(res, curr, count) {
                }
            });
        }
        table.on('tool(forum)', function(obj) {
            var data = obj.data;
            if (obj.event === 'updateAdver') {
                var index = layui.layer.open({
                    title : "編輯帖子",
                    type : 2,
                    content : "${ctx}/server/adver/goUpdateAdver.action?id="
                            + data.id,
                    success : function(layero, index) {
                        setTimeout(function() {
                            layui.layer.tips('點選此處返回',
                                    '.layui-layer-setwin .layui-layer-close', {
                                        tips : 3
                                    });
                        }, 500)
                    }
                })
                layui.layer.full(index);
            }else if (obj.event === 'deleteAdver') {
                layer.confirm('確定刪除該條廣告嗎?', function(index){
                    //向服務端傳送刪除指令
                    $.ajax({
                        type : "post",
                        url : "${ctx}/server/adver/deleteAdver.action",
                        dataType : "json",
                        data : {
                            "id" : data.id,
                        },
                        success : function(data) {
                            if(data.code==0){
                                layer.msg("刪除成功!");
                                setTimeout(function () {
                                       window.location.reload();
                                 }, 1000);
                            }else{
                                layer.msg("刪除失敗!");
                            }
                        }
                    });
                 });
            }
        });
        $(window).one("resize",function() {
            $("#addAdver").click(function() {
                var index = layui.layer.open({
                    title : "新增廣告",
                    type : 2,
                    content : "${ctx}/server/adver/goAddAdver.action",
                    success : function(layero,index) {
                        setTimeout(function() {
                            layui.layer.tips('點選此處返回','.layui-layer-setwin .layui-layer-close',{
                                tips : 3
                            });
                        }, 500)
                    }
                })
                layui.layer.full(index);
            })
        }).resize();
    </script>
</body>
</html>

<!DOCTYPE html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<c:set var="ctx" value="${pageContext.request.contextPath}" />
<html>
<head>
<meta charset="utf-8">
<title>編輯廣告</title>
<meta name="renderer" content="webkit">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="format-detection" content="telephone=no">

<link rel="stylesheet" href="${ctx}/server/layui/css/layui.css"
    media="all" />
<link rel="stylesheet" href="${ctx}/server/font-awesome/css/font-awesome.min.css">
<style type="text/css">
#Images li{
    float:left;
    margin-left:10px;
    height:300px;
    margin-bottom:20px;
}
#Images img{
    height:300px;
}
.img_del{
    cursor: pointer;
}
</style>
</head>
<body>
    <div style="margin: 15px;">
        <div class="layui-form">
            <div class="layui-form-item">
                <label class="layui-form-label">標題:</label>
                <div class="layui-input-block">
                    <input type="text" name="title" value="${adver.title}"  autocomplete="off" class="layui-input" lay-verify="title" placeholder="請輸入標題" style="width:390px">
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label">內容:</label>
                <div class="layui-input-block">
                     <textarea placeholder="請輸入內容" class="layui-textarea" name="content" lay-verify="content">${adver.content}</textarea>
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">廣告位置:</label>
                <div class="layui-input-block">
                    <input type="text" name="position" value="${adver.position}"  autocomplete="off" class="layui-input" lay-verify="position" placeholder="請輸入位置" style="width:390px">
                </div>
            </div>
            
            <div class="layui-form-item">
                <label class="layui-form-label">圖片:</label>
                <div class="layui-input-block">
                    <button type="button" class="layui-btn" id="uploadNewImg">圖片上傳</button> 
                </div>
            </div>
            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <ul class="layer-photos-demo" id="Images" lay-verify="uploadNewImg"></ul>
            </div>            
            <div class="layui-form-item">
                <label class="layui-form-label"></label>
                <div class="layui-input-block">
                    <button class="layui-btn" lay-submit="" lay-filter="demo1">確認</button>
                    <button onclick="goBack();" class="layui-btn layui-btn-primary">返回</button>
                </div>
            </div>
        </div>
    </div>
</body>
<script type="text/javascript" src="${ctx}/server/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="${ctx}/server/layui/layui.js"></script>

<script type="text/javascript">
var image = '${adver.image}';
if(image != ''){
    $('#Images').html('<li><img src="'+ image +'" class="layui-upload-img"><div class="operate"><i class="layui-icon img_del">&#xe640;</i></div></li>');
}

//圖片集合刪除
function delImages(){
    var i_s=$("#Images .img_del");
    for(var i=0;i<i_s.length;i++){
        $("#Images .img_del").get(i).index=i;
        $("#Images .img_del:eq("+i+")").click(function(){
            var i=this.index;
            $("#Images li:eq("+i+")").remove();
        })
    }
}
delImages();
layui.use('upload', function() {
    var $ = layui.jquery, upload = layui.upload;
    upload.render({
        url: '${ctx}/imageUpload/systemImage.action'
        ,elem: '#uploadNewImg' //指定原始元素,預設直接查詢class="layui-upload-file"
        ,method: 'post', //上傳介面的http型別
        dataType:"json"
        ,multiple: true
        ,before: function(obj){
          //預讀本地檔案示例,不支援ie8
          obj.preview(function(index, file, result){
          });
        }
        ,done: function(res){
            //$('#Images').append('<li><img layer-src="'+ res.msg +'" src="'+ res.msg +'" alt="'+ res.msg +'" class="layui-upload-img"><div class="operate"><i class="layui-icon img_del">&#xe640;</i></div></li>');
            $('#Images').html('<li><img src="'+ res.msg +'" class="layui-upload-img"><div class="operate"><i class="layui-icon img_del">&#xe640;</i></div></li>');
            image = res.msg;
            delImages();
        }
    });
});



layui.use([ 'form', 'layer'],
        function() {
         form = layui.form, layer = layui.layer;
         //自定義驗證規則
        form.verify({    
            title : function(value) {
                if (value.trim() == '') {
                    return '標題不能為空';
                }
            },
            content : function(value) {
                if (value.trim() == '') {
                    return '內容不能為空';
                }
            },
            position : function(value) {
                if (value.trim() == '') {
                    return '位置不能為空';
                }
            },
            uploadNewImg : function(value) {
                if ($('#Images li').length < 1) {
                    return '請上傳圖片';
                }
            }
        });
         
        //監聽提交
        form.on('submit(demo1)', function(data) {
            $.ajax({
                type : "post",
                url : "${ctx}/server/adver/updateAdver.action",
                dataType:"json",
                data : {
                    "id" : '${adver.id}',
                    "title":data.field.title,
                    "content":data.field.content,
                    "position":data.field.position,
                    "image":image
                },
                success : function(result) {
                    if(result.code==0){
                        layer.msg("編輯成功");
                        setTimeout(function () {
                             layer.closeAll("iframe");
                              //重新整理父頁面
                               parent.location.reload();
                          }, 1000);
                    } else{
                        layer.msg(result.msg,{time:2000});
                    }
                },error:function(){
                    layer.msg("編輯失敗");
                }
            });
            return false;
        });
    });

function goBack(){
    window.history.go(-1);
}
</script>
</html>

相關文章