如實現menu.html與menu_add.html之間的id傳遞
id傳遞的核心代碼:menu.html

menu_add.html:
1.引入插件

2.通過$.query.get()取值


后台取id可以使用request(代碼詳見下邊的代碼action)
舉例說明 業務需求如圖所示:
要實現勾選menu.html要修改的項,再點擊修改菜單的時候到menu_add.html中對數據進行回顯。
一.html與html之間id值傳遞的方法

回顯的效果如下:

前端代碼:add.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>菜單列表頁面</title>
<!-- 導入jquery核心類庫 -->
<script type="text/javascript" src="../../js/jquery-1.8.3.js"></script>
<!-- 導入easyui類庫 -->
<link rel="stylesheet" type="text/css" href="../../js/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="../../js/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="../../js/easyui/ext/portal.css">
<link rel="stylesheet" type="text/css" href="../../css/default.css">
<script type="text/javascript" src="../../js/easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="../../js/easyui/ext/jquery.portal.js"></script>
<script type="text/javascript" src="../../js/easyui/ext/jquery.cookie.js"></script>
<script src="../../js/easyui/locale/easyui-lang-zh_CN.js" type="text/javascript"></script>
<script type="text/javascript">
$(function(){
$("#grid").datagrid({
toolbar : [
{
id : 'add',
text : '添加菜單',
iconCls : 'icon-add',
handler : function(){
location.href='menu_add.html';
}
},{
id : 'edit',
text : '修改菜單',
iconCls : 'icon-edit',
handler : function (){
//獲取選中的行
var rows=$("#grid").datagrid("getSelections");
//是否僅選中一行數據
if(rows.length != 1) {
$.messager.alert('提示','請且僅選中一行','info');
return;
}
alert(rows[0].id);
location.href="menu_add.html?id="+rows[0].id;
}
}
],
url : '../../menu_list.action',
columns : [[
{
checkbox : true,
field : 'id',
title : '編號',
width : 200
},
{
field : 'name',
title : '名稱',
width : 200
},
{
field : 'description',
title : '描述',
width : 200
},
{
field : 'priority',
title : '優先級',
width : 200
},
{
field : 'page',
title : '路徑',
width : 200
}
]]
});
});
</script>
</head>
<body class="easyui-layout">
<div data-options="region:'center'">
<table id="grid"></table>
</div>
</body>
</html>
添加/保存的html窗口代碼add.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>菜單添加</title>
<!-- 導入jquery核心類庫 -->
<script type="text/javascript" src="../../js/jquery-1.8.3.js"></script>
<!-- 引入的jquery.params.js插件 -->
<script type="text/javascript" src="../../js/jquery.params.js"></script>
<!-- 導入easyui類庫 -->
<link rel="stylesheet" type="text/css" href="../../js/easyui/themes/default/easyui.css">
<link rel="stylesheet" type="text/css" href="../../js/easyui/themes/icon.css">
<link rel="stylesheet" type="text/css" href="../../js/easyui/ext/portal.css">
<link rel="stylesheet" type="text/css" href="../../css/default.css">
<script type="text/javascript" src="../../js/easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="../../js/easyui/ext/jquery.portal.js"></script>
<script type="text/javascript" src="../../js/easyui/ext/jquery.cookie.js"></script>
<script src="../../js/easyui/locale/easyui-lang-zh_CN.js" type="text/javascript"></script>
<script type="text/javascript" src="../../js/easyui/ext/jquery.portal.js"></script>
<script type="text/javascript">
$(function(){
var menuId = $.query.get("id");
alert(menuId);
if(menuId) {
//菜單id不為空,則為修改
$.post("../../menu_findMenuById.action",{"id":menuId},
function(menu) {
$("#functionForm").form("load",menu);
$("#parentCombobox").combobox("setValue",menu.pId);
})
}
//alert(menuId);
// 點擊保存
$('#save').click(function(){
if($("#functionForm").form("validate")) {
$("#functionForm").submit();
}
});
$('#back').click(function(){
location.href='menu.html';
});
});
</script>
</head>
<body class="easyui-layout">
<div data-options="region:'north'">
<div class="datagrid-toolbar">
<a id="save" icon="icon-save" href="#" class="easyui-linkbutton" plain="true">保存</a>
<a id="back" icon="icon-undo" href="#" class="easyui-linkbutton" plain="true">返回</a>
</div>
</div>
<div data-options="region:'center'">
<form id="functionForm" action="../../menu_add.action" method="post">
<input type="hidden" name="id"/>
<table class="table-edit" width="80%" align="center">
<tr class="title">
<td colspan="2">菜單項信息</td>
</tr>
<tr>
<td>名稱</td>
<td>
<input type="text" name="name" class="easyui-validatebox" data-options="required:true" />
</td>
</tr>
<tr>
<td>訪問路徑</td>
<td>
<input type="text" name="page" />
</td>
</tr>
<tr>
<td>優先級</td>
<td>
<input type="text" name="priority" class="easyui-numberbox" data-options="required:true" />
</td>
</tr>
<tr>
<td>父菜單項</td>
<td>
<input name="parentMenu.id" id="parentCombobox" class="easyui-combobox" data-options="valueField:'id',textField:'name',url:'../../menu_list.action'" />
</td>
</tr>
<tr>
<td>描述</td>
<td>
<textarea name="description" rows="4" cols="60"></textarea>
</td>
</tr>
</table>
</form>
</div>
</body>
</html>
插件:jquery.params.js
/** * jQuery.query - Query String Modification and Creation for jQuery * Written by Blair Mitchelmore (blair DOT mitchelmore AT gmail DOT com) * Licensed under the WTFPL (http://sam.zoy.org/wtfpl/). * Date: 2009/8/13 * * @author Blair Mitchelmore * @version 2.1.7 * **/ new function (settings) { // Various Settings var $separator = settings.separator || '&'; var $spaces = settings.spaces === false ? false : true; var $suffix = settings.suffix === false ? '' : '[]'; var $prefix = settings.prefix === false ? false : true; var $hash = $prefix ? settings.hash === true ? "#" : "?" : ""; var $numbers = settings.numbers === false ? false : true; jQuery.query = new function () { var is = function (o, t) { return o != undefined && o !== null && (!!t ? o.constructor == t : true); }; var parse = function (path) { var m, rx = /\[([^[]*)\]/g, match = /^([^[]+)(\[.*\])?$/.exec(path), base = match[1], tokens = []; while (m = rx.exec(match[2])) tokens.push(m[1]); return [base, tokens]; }; var set = function (target, tokens, value) { var o, token = tokens.shift(); if (typeof target != 'object') target = null; if (token === "") { if (!target) target = []; if (is(target, Array)) { target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value)); } else if (is(target, Object)) { var i = 0; while (target[i++] != null); target[--i] = tokens.length == 0 ? value : set(target[i], tokens.slice(0), value); } else { target = []; target.push(tokens.length == 0 ? value : set(null, tokens.slice(0), value)); } } else if (token && token.match(/^\s*[0-9]+\s*$/)) { var index = parseInt(token, 10); if (!target) target = []; target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value); } else if (token) { var index = token.replace(/^\s*|\s*$/g, ""); if (!target) target = {}; if (is(target, Array)) { var temp = {}; for (var i = 0; i < target.length; ++i) { temp[i] = target[i]; } target = temp; } target[index] = tokens.length == 0 ? value : set(target[index], tokens.slice(0), value); } else { return value; } return target; }; var queryObject = function (a) { var self = this; self.keys = {}; if (a.queryObject) { jQuery.each(a.get(), function (key, val) { self.SET(key, val); }); } else { jQuery.each(arguments, function () { var q = "" + this; q = q.replace(/^[?#]/, ''); // remove any leading ? || # q = q.replace(/[;&]$/, ''); // remove any trailing & || ; if ($spaces) q = q.replace(/[+]/g, ' '); // replace +'s with spaces jQuery.each(q.split(/[&;]/), function () { var key = decodeURIComponent(this.split('=')[0] || ""); var val = decodeURIComponent(this.split('=')[1] || ""); if (!key) return; if ($numbers) { if (/^[+-]?[0-9]+\.[0-9]*$/.test(val)) // simple float regex val = parseFloat(val); else if (/^[+-]?[0-9]+$/.test(val)) // simple int regex val = parseInt(val, 10); } val = (!val && val !== 0) ? true : val; if (val !== false && val !== true && typeof val != 'number') val = val; self.SET(key, val); }); }); } return self; }; queryObject.prototype = { queryObject: true, has: function (key, type) { var value = this.get(key); return is(value, type); }, GET: function (key) { if (!is(key)) return this.keys; var parsed = parse(key), base = parsed[0], tokens = parsed[1]; var target = this.keys[base]; while (target != null && tokens.length != 0) { target = target[tokens.shift()]; } return typeof target == 'number' ? target : target || ""; }, get: function (key) { var target = this.GET(key); if (is(target, Object)) return jQuery.extend(true, {}, target); else if (is(target, Array)) return target.slice(0); return target; }, SET: function (key, val) { var value = !is(val) ? null : val; var parsed = parse(key), base = parsed[0], tokens = parsed[1]; var target = this.keys[base]; this.keys[base] = set(target, tokens.slice(0), value); return this; }, set: function (key, val) { return this.copy().SET(key, val); }, REMOVE: function (key) { return this.SET(key, null).COMPACT(); }, remove: function (key) { return this.copy().REMOVE(key); }, EMPTY: function () { var self = this; jQuery.each(self.keys, function (key, value) { delete self.keys[key]; }); return self; }, load: function (url) { var hash = url.replace(/^.*?[#](.+?)(?:\?.+)?$/, "$1"); var search = url.replace(/^.*?[?](.+?)(?:#.+)?$/, "$1"); return new queryObject(url.length == search.length ? '' : search, url.length == hash.length ? '' : hash); }, empty: function () { return this.copy().EMPTY(); }, copy: function () { return new queryObject(this); }, COMPACT: function () { function build(orig) { var obj = typeof orig == "object" ? is(orig, Array) ? [] : {} : orig; if (typeof orig == 'object') { function add(o, key, value) { if (is(o, Array)) o.push(value); else o[key] = value; } jQuery.each(orig, function (key, value) { if (!is(value)) return true; add(obj, key, build(value)); }); } return obj; } this.keys = build(this.keys); return this; }, compact: function () { return this.copy().COMPACT(); }, toString: function () { var i = 0, queryString = [], chunks = [], self = this; var encode = function (str) { str = str + ""; if ($spaces) str = str.replace(/ /g, "+"); return encodeURIComponent(str); }; var addFields = function (arr, key, value) { if (!is(value) || value === false) return; var o = [encode(key)]; if (value !== true) { o.push("="); o.push(encode(value)); } arr.push(o.join("")); }; var build = function (obj, base) { var newKey = function (key) { return !base || base == "" ? [key].join("") : [base, "[", key, "]"].join(""); }; jQuery.each(obj, function (key, value) { if (typeof value == 'object') build(value, newKey(key)); else addFields(chunks, newKey(key), value); }); }; build(this.keys); if (chunks.length > 0) queryString.push($hash); queryString.push(chunks.join($separator)); return queryString.join(""); } }; return new queryObject(location.search, location.hash); }; } (jQuery.query || {}); // Pass in jQuery.query as settings object
二.父菜單下拉框的回顯
Oracle數據庫表格如下圖所示:

后台要根據拿到的id查詢menu將其回顯,難點是在pid(實體類中沒有該屬性),我們對Menu實體類進行如下改進:


完整代碼如下
package cn.itcast.bos.domain.system; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; import org.apache.struts2.json.annotations.JSON; import org.springframework.data.annotation.Transient; /** * @description:菜單 */ @Entity @Table(name = "T_MENU") public class Menu implements Serializable { private static final long serialVersionUID = -5435625580410902709L; @Id @GeneratedValue @Column(name = "C_ID") private Integer id; @Column(name = "C_NAME") private String name; // 菜單名稱 @Column(name = "C_PAGE") private String page; // 訪問路徑 @Column(name = "C_PRIORITY") private Integer priority; // 優先級 @Column(name = "C_DESCRIPTION") private String description; // 描述 @ManyToMany(mappedBy = "menus") private Set<Role> roles = new HashSet<Role>(0); @OneToMany(mappedBy = "parentMenu") private Set<Menu> childrenMenus = new HashSet<Menu>(); @ManyToOne @JoinColumn(name = "C_PID") private Menu parentMenu; private Integer pId; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPage() { return page; } public void setPage(String page) { this.page = page; } public Integer getPriority() { return priority; } public void setPriority(Integer priority) { this.priority = priority; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @JSON(serialize=false) public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } @JSON(serialize=false) public Set<Menu> getChildrenMenus() { return childrenMenus; } public void setChildrenMenus(Set<Menu> childrenMenus) { this.childrenMenus = childrenMenus; } @JSON(serialize=false) public Menu getParentMenu() { return parentMenu; } public void setParentMenu(Menu parentMenu) { this.parentMenu = parentMenu; } @Transient//阻止該屬性被持久化到數據庫成為字段 public Integer getpId() { if (parentMenu == null ) { return null; } return parentMenu.getId(); } }
Action的代碼如下:
package cn.itcast.bos.web.action.system; import java.util.List; import java.util.Map; import org.apache.shiro.SecurityUtils; import org.apache.shiro.subject.Subject; import org.apache.struts2.convention.annotation.Action; import org.apache.struts2.convention.annotation.Result; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Controller; import com.opensymphony.xwork2.ActionContext; import cn.itcast.bos.domain.system.Menu; import cn.itcast.bos.domain.system.User; import cn.itcast.bos.service.system.MenuService; import cn.itcast.bos.web.action.common.BaseAction; @Controller @Scope("prototype") public class MenuAction extends BaseAction<Menu> { //注入Service @Autowired private MenuService menuService; //查詢菜單的方法 @Action("menu_list") public String findMenu() { List<Menu> list = menuService.findMenu(); ActionContext.getContext().getValueStack().push(list); return JSON; } //保存的方法 @Action(value="menu_add",results={@Result(type=REDIRECT,location="/pages/system/menu.html")}) public String saveMenu() { menuService.save(model); return SUCCESS; } //根據用戶顯示菜單 @Action("menu_listByUser") public String findMenuByUser() { //獲取當前登錄的用戶 User user = (User) SecurityUtils.getSubject().getPrincipal(); //根據用戶查詢菜單 List<Menu> list = menuService.findByUser(user); //將集合壓入root棧頂 ActionContext.getContext().getValueStack().push(list); return JSON; } //根據菜單id查詢菜單 @Action("menu_findMenuById") public String findMenuById() { //獲取request,用於取到id Map<String,Object> request = (Map<String, Object>) ActionContext.getContext().get("request"); Integer menuId = (Integer) request.get("id"); //根據id查詢菜單,並進行壓棧 Menu menu = menuService.finMenuById(menuId); ActionContext.getContext().getValueStack().push(menu); return JSON; } }
service
package cn.itcast.bos.service.system; import java.util.List; import cn.itcast.bos.domain.system.Menu; import cn.itcast.bos.domain.system.User; public interface MenuService { void save(Menu menu); List<Menu> findMenu(); List<Menu> findByUser(User user); Menu finMenuById(Integer id); }
serviceImpl
package cn.itcast.bos.service.impl.system; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.cache.annotation.CacheEvict; import org.springframework.cache.annotation.Cacheable; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import cn.itcast.bos.dao.system.MenuRepository; import cn.itcast.bos.domain.system.Menu; import cn.itcast.bos.domain.system.User; import cn.itcast.bos.service.system.MenuService; @Service @Transactional public class MenuServiceImpl implements MenuService { //注入dao @Autowired private MenuRepository menuRepository; /** * 保存菜單 * */ @Override @CacheEvict(value="bos_menu_cache",allEntries=true) public void save(Menu menu) { if (menu.getParentMenu() != null && menu.getParentMenu().getId()==null) { menu.setParentMenu(null); } menuRepository.save(menu); } /** * 查詢菜單 * */ @Override public List<Menu> findMenu() { List<Menu> list = menuRepository.findAll(); return list; } /** * 根據不同用戶顯示不同菜單 * */ @Override @Cacheable(value="bos_menu_cache",key="#user.id") public List<Menu> findByUser(User user) { //判斷用戶是超級管理員還是普通用戶 if ("admin".equals(user.getUsername())) { return menuRepository.findByOrderByPriority(); } else{ //普通用戶 return menuRepository.findByUser(user); } } /** * 根據id你查詢菜單 * */ @Override public Menu finMenuById(Integer id) { return menuRepository.findOne(id); } }
dao層代碼
package cn.itcast.bos.dao.system; import java.util.List; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import cn.itcast.bos.domain.system.Menu; import cn.itcast.bos.domain.system.User; public interface MenuRepository extends JpaRepository<Menu, Integer> { List<Menu> findByOrderByPriority(); //jpql @Query("from Menu m inner join fetch m.roles r inner join fetch r.users u where u=? order by m.priority") List<Menu> findByUser(User user); //sql /*@Query(value="SELECT * FROM t_menu t1 INNER JOIN t_role_menu t2 " + "ON t1.c_id=t2.c_menu_id INNER JOIN t_user_role t3 " + "ON t2.c_role_id=t3.c_role_id WHERE t3.c_user_id=? ORDER BY t1.c_priority ASC" ,nativeQuery=true) List<Menu> findByUserId(Integer userId); */ }
