1. 程式人生 > >layui框架與SSM前後臺互動

layui框架與SSM前後臺互動

    採用layui前臺框架實現前後臺互動,資料分頁顯示以及刪除操作,具體方式如下:

一、資料分頁顯示

1.前端

(1)html頁面

<!--輪播資料分頁顯示-->
<table class="layui-hide" id="content_lbt" lay-filter="content_lbt_filter"></table>

(2)請求渲染資料

$(function() {
	/*輪播資料分頁顯示*/
	layui.use(['table', 'update'], function() {
		var table = layui.table,
			upload = layui.upload;

		table.render({
			elem: '#content_lbt',
			height: 500
				//,url: 'data/content_lbt.json' //資料介面
				,
			url: 'http://localhost:9911/cms/queryCarouselList' //資料介面
				,
			page: true //開啟分頁
				,
			loading: true,//分頁查詢是否顯示等待圖示
			text: {//若查詢記錄為空,執行此操作
				none: '暫無相關資料'
			} //預設:無資料。注:該屬性為 layui 2.2.5 開始新增
			,
			cellMinWidth: 80 //全域性定義常規單元格的最小寬度,layui 2.2.1 新增
				,
			cols: [
				[{
					field: 'id',
					width: '10%',
					title: 'ID',
					sort: true
				}, {
					field: 'posterId',
					width: '10%',
					title: '上傳者ID',
					sort: true
				}, {
					field: 'posterName',
					width: '15%',
					title: '上傳者姓名'
				}, {
					field: 'description',
					width: '28%',
					title: '描述',
					minWidth: 200
				}, {
					field: 'photoPath',
					width: '10%',
					title: '圖片',
					minWidth: 100
				}, {
					field: 'createTime',
					width: '10%',
					title: '上傳時間',
					minWidth: 100
				}]
			],
			request: {
				pageName: 'page',
				limitName: 'size'
			},
			limit: 10,
			limits: [10, 20, 30, 40, 50]
		});
     });

2.後端

        後端採用SpringBoot,利用SSM框架

(1)mapper:(注意@Mapper註解)

/**
     * 查詢所有輪播圖資訊
     *
     * @return
     */
    List<Carousel> queryCarousel(@Param("start") Integer start, @Param("size") Integer size);

    /**
     * 查詢輪播記錄條數
     *
     * @return
     */
    Integer countCarousel();
注意po類採用駝峰式寫法
<select id="queryCarousel"  resultType="com.jingling.basic.po.Carousel">
          SELECT id, poster_id AS posterId, poster_name AS posterName, description AS description  , photo_path AS photoPath, create_time  AS createTime
          FROM carousel
          LIMIT #{start}, #{size}
    </select>

    <select id="countCarousel" resultType="int">
        SELECT  COUNT(*) FROM carousel
    </select>

(2)service

    /**
     * 查詢全部輪播資訊
     *
     * @return
     */
    List<Carousel> queryCarousel(Integer page,Integer size);

    /**
     * 查詢輪播記錄條數
     *
     * @return
     */
    Integer countCarousel();

(3)serviceImpl(注意要有@Service註解)

 @Autowired
    private CarouselMapper carouselMapper;

    @Override
    public List<Carousel> queryCarousel(Integer page,Integer size) {
        if(page == null || page <= 0){
           page = 1;
        }
        if (size == null || size <= 0){
            size = 10;
        }

        Integer start = (page - 1) * size;
        return  carouselMapper.queryCarousel(start,size);
    }

    @Override
    public Integer countCarousel() {
        return carouselMapper.countCarousel();
    }

(4)Controller(注意要有@RequestController註解)

@RestController
@RequestMapping("/cms")
    @Autowired
    public CmsService cmsService;

    /**
     * 查詢輪播圖資訊
     *
     * @return
     */
    @GetMapping("/queryCarouselList")
    public Object queryCarouselList(HttpServletResponse response, @RequestParam("page") Integer page, @RequestParam("size") Integer size){
        response.setHeader("Access-Control-Allow-Origin", "*");//解決跨域的問題
        List<Carousel> carouselList = cmsService.queryCarousel(page,size);
        if (carouselList == null){
            return  RecycleResult.build(500,"輪播圖為空");
        }
        //return RecycleResult.ok(carouselList);
        //return carouselList;
        Integer count = cmsService.countCarousel();
        return new LayuiReplay<Carousel>(0, "OK", count, carouselList);
    }

二、刪除操作

1.前端

                <script type="text/html" id="barDemo">
		  <a class="layui-btn layui-btn-xs" lay-event="detail">檢視</a>
		  <!--<a class="layui-btn layui-btn-xs" lay-event="edit">編輯</a>-->
		  <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">刪除</a>
		</script>
                                {
					fixed: 'right',
					width: '15%',
					align: 'center',
					title: '操作',
					toolbar: '#barDemo'
				}
//監聽工具條
		table.on('tool(content_lbt_filter)', function(obj) { //注:tool是工具條事件名,test是table原始容器的屬性 lay-filter="對應的值"
			var data = obj.data //獲得當前行資料
				,
				layEvent = obj.event; //獲得 lay-event 對應的值
			if(layEvent === 'detail') {
				layer.msg('檢視操作');
			} else if(layEvent === 'del') {
				layer.confirm('真的刪除行麼', function(index) {
					//obj.del(); //刪除對應行(tr)的DOM結構
					delCarouselById(data.id);
					layer.close(index);
					//向服務端傳送刪除指令
				});
			}
			/*else if(layEvent === 'edit'){
	      layer.msg('編輯操作');
	    }*/
		});


		//刪除記錄
		function delCarouselById(id) {
			$.get("http://localhost:9911/cms/delCarouselById?id=" + id,
				function(data, status) {
					layer.msg('刪除成功');
				});
		}

2.後端(此處僅顯示controller層和mapper)

 @GetMapping("/delCarouselById")
    public RecycleResult delCarouselById(HttpServletResponse response,@RequestParam("id") Integer id){
        response.setHeader("Access-Control-Allow-Origin", "*");
        cmsService.delCarouselById(id);
        return RecycleResult.ok();
    }
<delete id="delCarouselById">
        DELETE FROM carousel
        WHERE id = #{id}
    </delete>

   -------------------------------------------------------------------------------------------------------------------------------

補充LayuiReplay類(其中get、set方法省略)

public class LayuiReplay <T> {
    private int code;
    private String msg;
    private int count;
    private List<T> data;

    public LayuiReplay(int code, String msg, int count, List<T> data) {
        this.code = code;
        this.msg = msg;
        this.count = count;
        this.data = data;
    }

    public String toJson() {
        Gson gson = new Gson();
        String json = gson.toJson(this);
        return json;
    }

    public static <T> String toJson(int count, List<T> data) {
        LayuiReplay<T> replay = new LayuiReplay<>(ReplyCode.OK.getCode(), ReplyCode.OK.getMessage(), count, data);
        return replay.toJson();
    }
}

 歡迎讀者提出建議,還有問題的童鞋可後臺留言!!!!