1. 程式人生 > >layui與java後臺互動

layui與java後臺互動

layui是現在比較火的一個前端設計框架,下面介紹一下它的資料分頁及其與java後臺的互動。

一、返回的Json格式

按照layui官網給的示例,自己封裝了工具類


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();
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public int getCount() {
        return count;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public List<T> getData() {
        return data;
    }

    public void setData(List<T> data) {
        this.data = data;
    }
}

二、前臺程式碼

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<link rel="stylesheet" href="../../tools/layui/css/layui.css" media="all">
		<title>社群使用者管理</title>
	</head>
	<body>
		
		<!--社群使用者資料分頁顯示-->
		<div  style="width: 95%;margin: 0 auto;">
			<table class="layui-hide" id="user_info_manager" lay-filter="user_info_manager_filter"></table>
		</div>
		<!--狀態展示 -->
		<script type="text/html" id="status">
		    {{#  if(d.isLocked == 1){ }}
		    <i class="layui-icon" style="color: #1E9FFF;">စ正常</i>
		    {{#  } }}
		    {{#  if(d.isLocked == 0){ }}
		    <i class="layui-icon">待啟用</i>
		    {{#  } }}
		    {{#  if(d.isLocked == 2) { }}
		    <i class="layui-icon">ဆ鎖定</i>
		    {{#  } }}
		</script>
		
		<!--時間格式修改 -->
		<script id="createTime" type="text/html">  
			{{timestampToTime(d.createTime)}}  
		</script> 
		<script id="updateTime" type="text/html">  
			{{timestampToTime(d.updateTime)}}  
		</script> 
		
		<!--操作-->
		<script type="text/html" id="barDemo">
			{{#  if(d.isLocked == 0){ }}
			<a class="layui-btn layui-btn-disabled layui-btn-xs" lay-event="user_unlock">不可操作</a>
			{{#  } }}	
			{{#  if(d.isLocked == 1){ }}
			<a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="user_lock">鎖定</a>
			{{#  } }}
			{{#  if(d.isLocked == 2){ }}
			<a class="layui-btn layui-btn-normal layui-btn-xs" lay-event="user_unlock">已鎖定</a>
			{{#  } }}	  
		</script>
		
		<!--引入的js -->
		<script type="text/javascript" src="../../tools/layui/layui.js"></script>
		<script type="text/javascript" src="../../tools/bootstrap/js/jquery-2.1.0.js" ></script>
		<script type="text/javascript" src="../../js/web/user_info_manage.js"></script>

		
		
	</body>
</html>
$(function() {
	/*社群使用者資料分頁顯示*/
	layui.use('table', function() {
		var table = layui.table;

		table.render({
			elem: '#user_info_manager',
			height: 'full-50',
			url: 'http://localhost:9901/user/getAllUserInfo',
			page: true ,
			loading: true,
			text: {
				none: '暫無相關資料'
			},
			cellMinWidth: 80,
			cols: [
				[{
					field: 'username',
					width: '10%',
					title: '使用者名稱',
					sort: true
				}, {
					field: 'nickname',
					width: '10%',
					title: '暱稱',
					sort: true
				}, {
					field: 'email',
					width: '13%',
					title: '郵箱'
				}, {
					field: 'phone',
					width: '12%',
					title: '電話'
				}, {
					field: 'address',
					width: '10%',
					title: '地址',
					minWidth: 100
				}, {
					field: 'createTime',
					width: '13%',
					title: '建立時間',
					templet: '#createTime'
				}, {
					field: 'updateTime',
					width: '13%',
					title: '更新時間',
					templet: '#updateTime'
				}, {
					field: 'isLocked',
					width: '10%',
					title: '當前狀態',
					templet: '#status'
				}, {
					fixed: 'right',
					width: '9%',
					align: 'center',
					title: '操作',
					toolbar: '#barDemo'
				}]
			],
			request: {
				pageName: 'page',
				limitName: 'size'
			},
			limit: 10,
			limits: [10, 20, 30, 40, 50]
		});

		//監聽工具條
		table.on('tool(user_info_manager_filter)', function(obj) { //注:tool是工具條事件名,test是table原始容器的屬性 lay-filter="對應的值"
			//獲得當前行資料
			var data = obj.data;
			layEvent = obj.event; //獲得 lay-event 對應的值
			if(layEvent === 'user_lock') {
				//鎖定使用者
				layer.confirm('您確定要鎖定此使用者嗎?', {icon: 3, title:'鎖定使用者'}, function(index){  		
					$.get("http://localhost:9901/user/lockUser/2/" + data.username, function(result) {	
						if(result.status == 200) {
							layer.msg('已鎖定', {
								icon: 1,
							  	time: 2000 
							}, 	function(){
							  window.location.reload()
							});
						} else {
							layer.msg(result.msg, {
								icon: 2,
							  	time: 2000 
							}, 	function(){
							  window.location.reload()
							});
						}

						
					})				
				});		
			} else if(layEvent === 'user_unlock') {
				//解鎖使用者
				layer.confirm('您確定要解鎖此使用者嗎?', {icon: 3, title:'解鎖使用者'}, function(index){		
					$.get("http://localhost:9901/user/lockUser/1/" + data.username, function(result) {			
						if(result.status == 200) {
							layer.msg('已解鎖', {
								icon: 1,
							  	time: 2000 
							}, 	function(){
							  window.location.reload()
							});
						} else {
							layer.msg(result.msg, {
								icon: 2,
							  	time: 2000 
							}, 	function(){
							  window.location.reload()
							});
						}						
					})										
				});	
			}
		});
		
	});
});


		
<!--時間格式化-->
function timestampToTime(timestamp) {

	var date = new Date(timestamp);//時間戳為10位需*1000,時間戳為13位的話不需乘1000
    Y = date.getFullYear() + '-';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '-';
    D = date.getDate() + ' ';
    h = date.getHours() + ':';
    m = date.getMinutes() + ':';
    s = date.getSeconds();
    return Y+M+D+h+m+s;
}

在js的table.render中,cols的field欄位對應後臺po的屬性,template連結到html中的的script標籤,用於格式化一些資料,或者按照自己的意願顯示。

三、po類

package com.jingling.basic.po;

import java.io.Serializable;
import java.sql.Timestamp;

/**
 * @Source: JDK 1.8
 * @Author: Zhao
 * @Since: version 1.0
 **/
public class User implements Serializable {

    private Integer id;
    private String username;
    private String nickname;
    private String password;
    private String openid;
    private String unionid;
    private String email;
    private String phone;
    private String address;
    private String salt;
    private String validateCode;
    private String isLocked;
    private Timestamp createTime;
    private Timestamp updateTime;

    public User() {
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getNickname() {
        return nickname;
    }

    public void setNickname(String nickname) {
        this.nickname = nickname;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getOpenid() {
        return openid;
    }

    public void setOpenid(String openid) {
        this.openid = openid;
    }

    public String getUnionid() {
        return unionid;
    }

    public void setUnionid(String unionid) {
        this.unionid = unionid;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getSalt() {
        return salt;
    }

    public void setSalt(String salt) {
        this.salt = salt;
    }

    public String getValidateCode() {
        return validateCode;
    }

    public void setValidateCode(String validateCode) {
        this.validateCode = validateCode;
    }

    public String getIsLocked() {
        return isLocked;
    }

    public void setIsLocked(String isLocked) {
        this.isLocked = isLocked;
    }

    public Timestamp getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Timestamp createTime) {
        this.createTime = createTime;
    }

    public Timestamp getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Timestamp updateTime) {
        this.updateTime = updateTime;
    }
}

四、controller程式碼

    @GetMapping("/getAllUserInfo")
    public Object getAllUserInfo(@RequestParam("page") Integer page, @RequestParam("size") Integer size) {

        int count = userService.getUserCount();
        List<User> userList  = userService.getAllUserInfo(page, size);
        return new LayuiReplay<User>(0, "OK", count, userList);

    }

layui要求,不僅傳入資料,還得傳入資料的總數,這樣就可以使用其自帶的分頁效果。

五、小結

layui的互動其實並不難,很多人覺得layui的官方文件寫的不好,因為好多東西拿過來不能直接使用,但其實他官網上好多示例都需要請求到資料才能執行。