struts2學習之旅三 權限管理和導航設計

1,權限管理的db設計和dao實現,儘可能簡單快速有效;css

db的設計以下:權限按照角色來賦給用戶;前端

角色表

權限對應每個具體的功能,有菜單級別的,有導航級別的,還有頁面級別的功能;java

權限表

 

涉及到權限的敏感操做通常都要記錄日誌,不只要記錄到log裏還要記錄到遠程的db裏,以備審計。學習的時候暫時不用,可是爲了全面考node

慮設計,這裏仍是加上;mysql

日誌表

表名 建表的sql文,這裏使用mysql數據庫,由於是學習用的,後面會嘗試用jpa去替換如今的dao,作到對db支持的靈活性
dt_role

DROP TABLE IF EXISTS `dt_role`;
CREATE TABLE `dt_role` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `roleName` varchar(20)   NOT NULL,
  `roleDesc` varchar(100)   DEFAULT NULL,
  `createDate` datetime DEFAULT NULL,
  `flag` tinyint(4) DEFAULT NULL,
  `pid` int(11) DEFAULT NULL,
  `order` int(11) DEFAULT NULL,
  `ext` varchar(120)   DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;web

dt_permission

DROP TABLE IF EXISTS `dt_permission`;
CREATE TABLE `dt_permission` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `pName` varchar(30) NOT NULL DEFAULT '' COMMENT '權限名稱',
  `pDesc` varchar(200) DEFAULT NULL COMMENT '權限描述',
  `pFunctionName` varchar(30) NOT NULL,
  `pid` int(11) DEFAULT NULL COMMENT '父id',
  `pUrl` varchar(200) DEFAULT NULL COMMENT '功能的連接',
  `pLevel` tinyint(4) DEFAULT NULL COMMENT '功能的層級',
  `order` int(11) DEFAULT NULL COMMENT '排序號',
  `ext` varchar(120) DEFAULT NULL,
  `createDate` datetime NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;sql

dt_log

DROP TABLE IF EXISTS `dt_log`;
CREATE TABLE `dt_log` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `userName` varchar(30) DEFAULT NULL COMMENT '用戶名',
  `ip` varchar(30) DEFAULT NULL COMMENT 'ip地址',
  `type` tinyint(4) DEFAULT NULL COMMENT '日誌類型',
  `content` varchar(200) DEFAULT NULL COMMENT '日誌內容',
  `ext1` varchar(120) DEFAULT NULL COMMENT '擴展字段1',
  `ext2` varchar(120) DEFAULT NULL COMMENT '擴展字段2',
  `createDate` datetime DEFAULT NULL COMMENT '建立日期',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;數據庫

向上指數據持久層,採用easydb的方式,先寫基本的dao;apache

package com.cutter.web.account.dao.achieve;

import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.util.List;

import org.apache.log4j.Logger; 
import org.pureart.persistement.database.easydb.DB; 
import org.pureart.persistement.database.easydb.IUStH; 
import org.pureart.persistement.database.easydb.ParamReadStH; 
import org.pureart.persistement.database.easydb.ReadStH;

import com.cutter.web.account.dao.entity.Role; 
import com.cutter.web.account.dao.inter.RoleDao; 
import com.cutter.web.account.util.StringUtil; 
import com.google.common.collect.ImmutableList; 
import com.google.common.collect.Lists;

public class RoleDaoAchieve implements RoleDao {

    private static final Logger log = Logger.getLogger(RoleDaoAchieve.class);

    private static final String ROLE_TABLE = " test.dt_role";

    private static final String ROLE_SELECT = " SELECT * FROM " + ROLE_TABLE;

    private static final String ROLE_GET_BY_ID = ROLE_SELECT + " WHERE id=? ;";

    private static final String ROLE_DELETE_BY_ID = " DELETE FROM " + ROLE_TABLE + " WHERE id=? ;";

    private static final String ROLE_LIST_ALL = ROLE_SELECT + " ORDER BY createDate DESC ";

    private static final String ROLE_LIST_BY_PAGE = ROLE_LIST_ALL + " limit ?,? ;";

    private static final String ROLE_ADD = " INSERT INTO " + ROLE_TABLE 
            + " (roleName,roleDesc,flag,pid,order,ext,createDate) VALUES(?,?,?,?,?,?,?);";

    private static final String ROLE_UPDATE = " update " + ROLE_TABLE 
            + " set roleName=? , roleDesc=? , flag=? , pid=? , order=? , ext=? , createDate=? where id=?";

    @Override 
    public boolean update(final Role entity) {

        if (null != entity) { 
            final boolean flag = 0 < entity.getId(); 
            try { 
                return DB.insertUpdate(flag ? ROLE_UPDATE : ROLE_ADD, new IUStH() {

                    @Override 
                    public void handleInsertUpdate(PreparedStatement stmt) throws SQLException { 
                        stmt.setString(1, entity.getRoleName()); 
                        stmt.setString(2, entity.getRoleDesc()); 
                        stmt.setInt(3, entity.getFlag()); 
                        stmt.setInt(4, entity.getPid()); 
                        stmt.setInt(5, entity.getOrder()); 
                        stmt.setString(6, entity.getExt()); 
                        stmt.setDate(7, StringUtil.transforFromUtilToSqlDate(entity.getCrateDate())); 
                        if (flag) { 
                            stmt.setInt(8, entity.getId()); 
                        } 
                        stmt.executeUpdate(); 
                    } 
                }); 
            } catch (SQLException e) { 
                log.error("更新角色信息異常!"); 
                e.printStackTrace(); 
            } 
        } 
        return false; 
    }

    @Override 
    public Role get(final int id) { 
        try { 
            if (0 < id) { 
                final Role role = new Role();

                boolean getResult = DB.select(ROLE_GET_BY_ID, new ParamReadStH() {

                    @Override 
                    public void handleRead(ResultSet rs) throws SQLException {

                        if (rs.next()) { 
                            handResult(role, rs);

                        }

                    }

                    @Override 
                    public void setParams(PreparedStatement stmt) throws SQLException { 
                        stmt.setInt(1, id);

                    } 
                });

                if (getResult) { 
                    return role; 
                } 
            } 
        } catch (SQLException e) { 
            log.error("查詢單條角色信息異常!"); 
            e.printStackTrace(); 
        } 
        return null; 
    }

    @Override 
    public boolean delete(final int id) { 
        try { 
            if (0 < id) { 
                return DB.insertUpdate(ROLE_DELETE_BY_ID, new IUStH() {

                    @Override 
                    public void handleInsertUpdate(PreparedStatement stmt) throws SQLException { 
                        stmt.setInt(1, id); 
                        stmt.executeUpdate(); 
                    } 
                }); 
            } 
        } catch (SQLException e) { 
            log.error("刪除單條角色信息異常!"); 
            e.printStackTrace(); 
        } 
        return false; 
    }

    @Override 
    public boolean batchDelete(final int[] idArray) { 
        try { 
            if (null != idArray && 1 < idArray.length) { 
                return DB.insertUpdate(ROLE_DELETE_BY_ID, new IUStH() {

                    @Override 
                    public void handleInsertUpdate(PreparedStatement stmt) throws SQLException {

                        for (int i : idArray) { 
                            stmt.setInt(1, i); 
                            stmt.addBatch(); 
                        } 
                        stmt.executeBatch(); 
                    } 
                }); 
            } 
        } catch (SQLException e) { 
            log.error("批量刪除角色信息異常!"); 
            e.printStackTrace(); 
        } 
        return false; 
    }

    @Override 
    public ImmutableList<Role> listAll() {

        try { 
            final List<Role> roleList = Lists.newLinkedList();

            boolean listResult = DB.select(ROLE_LIST_ALL, new ReadStH() {

                @Override 
                public void handleRead(ResultSet rs) throws SQLException {

                    while (rs.next()) { 
                        roleList.add(handResult(new Role(), rs)); 
                    } 
                } 
            });

            if (listResult) { 
                return ImmutableList.copyOf(roleList); 
            }

        } catch (SQLException e) { 
            log.error("查詢所有角色信息異常!"); 
            e.printStackTrace(); 
        }

        return null; 
    }

    @Override 
    public ImmutableList<Role> list(final int pageSize, final int page) {

        try {

            final List<Role> roleLists = Lists.newLinkedList();

            boolean listPageResult = DB.select(ROLE_LIST_BY_PAGE, new ParamReadStH() {

                @Override 
                public void handleRead(ResultSet rs) throws SQLException {

                    while (rs.next()) { 
                        roleLists.add(handResult(new Role(), rs)); 
                    }

                }

                @Override 
                public void setParams(PreparedStatement stmt) throws SQLException { 
                    int start = pageSize * (page - 1); 
                    int end = start + pageSize;

                    stmt.setInt(1, start); 
                    stmt.setInt(2, end); 
                } 
            });

            if (listPageResult) { 
                return ImmutableList.copyOf(roleLists); 
            }

        } catch (SQLException e) { 
            log.error("分頁查詢角色信息異常!"); 
            e.printStackTrace(); 
        }

        return null;

    }

    private Role handResult(final Role role, ResultSet rs) throws SQLException { 
        
        role.setId(rs.getInt("id")); 
        role.setRoleName(rs.getString("roleName")); 
        role.setRoleDesc(rs.getString("roleDesc")); 
        role.setPid(rs.getInt("pid")); 
        role.setFlag(rs.getInt("flag")); 
        role.setCrateDate(StringUtil.transforFromSqlToUtilDate(rs.getDate("createDate"))); 
        role.setExt(rs.getString("ext")); 
        role.setOrder(rs.getInt("order"));

        return role; 
    }

}
View Code

 

package com.cutter.web.account.dao.achieve;

import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.util.List;

import org.apache.log4j.Logger; 
import org.pureart.persistement.database.easydb.DB; 
import org.pureart.persistement.database.easydb.IUStH; 
import org.pureart.persistement.database.easydb.ParamReadStH; 
import org.pureart.persistement.database.easydb.ReadStH;

import com.cutter.web.account.dao.entity.Permission; 
import com.cutter.web.account.dao.inter.PermissionDao; 
import com.cutter.web.account.util.StringUtil; 
import com.google.common.collect.ImmutableList; 
import com.google.common.collect.Lists;

public class PermissionDaoAchieve implements PermissionDao {

    private static final Logger log = Logger.getLogger(PermissionDaoAchieve.class);

    private static final String PERMISSION_TABLE = " test.dt_permission ";

    private static final String PERMISSION_SELECT = " SELECT * FROM  " + PERMISSION_TABLE;

    private static final String PERMISSION_GET_BY_ID = PERMISSION_SELECT + " where id=? ;"; 
    
    private static final String PERMISSION_GET_BY_ROLEID = PERMISSION_SELECT + " where roleId=? ;";

    private static final String PERMISSION_DELETE_BY_ID = " DELETE FROM " + PERMISSION_TABLE + " WHERE id=? ;";

    private static final String PERMISSION_LIST_ALL = PERMISSION_SELECT + " ORDER BY createDate DESC ;";

    private static final String PERMISSION_LIST_BY_PAGE = PERMISSION_LIST_ALL + " LIMIT ?,? ; ";

    private static final String PERMISSION_ADD = " INSERT INTO " + PERMISSION_TABLE 
            + " (pName,pFunctionName,pid,pDesc,pUrl,pLevel,order,ext,createDate) VALUES(?,?,?,?,?,?,?,?,?,?)";

    private static final String PERMISSION_UPDATE = " UPDATE " 
            + PERMISSION_TABLE 
            + " SET pName=? , pFunctionName=? , pid=? , pDesc=? , pUrl=? , pLevel=? , order=? , ext=? , createDate=? where id=? ;";

    @Override 
    public boolean update(final Permission entity) { 
        if (null != entity) { 
            try { 
                final boolean flag = 0 < entity.getId();

                DB.insertUpdate(flag ? PERMISSION_UPDATE : PERMISSION_ADD, new IUStH() {

                    @Override 
                    public void handleInsertUpdate(PreparedStatement stmt) throws SQLException {

                        stmt.setString(1, entity.getpName()); 
                        stmt.setString(2, entity.getpFunctionName()); 
                        stmt.setInt(3, entity.getPid()); 
                        stmt.setString(4, entity.getpDesc()); 
                        stmt.setString(5, entity.getpUrl()); 
                        stmt.setInt(6, entity.getpLevel()); 
                        stmt.setInt(7, entity.getOrder()); 
                        stmt.setString(8, entity.getExt()); 
                        stmt.setDate(9, StringUtil.transforFromUtilToSqlDate(entity.getCreateDate()));

                        if (flag) { 
                            stmt.setInt(10, entity.getId()); 
                        } 
                        stmt.executeUpdate();

                    } 
                }); 
            } catch (SQLException e) { 
                log.error("更新權限信息異常!"); 
                e.printStackTrace(); 
            } 
        } 
        return false; 
    }

    @Override 
    public Permission get(final int id) {

        if (0 < id) { 
            final Permission permission = new Permission(); 
            try { 
                boolean getResult = DB.select(PERMISSION_GET_BY_ID, new ParamReadStH() {

                    @Override 
                    public void handleRead(ResultSet rs) throws SQLException { 
                        if (rs.next()) { 
                            handResult(permission, rs); 
                        }

                    }

                    @Override 
                    public void setParams(PreparedStatement stmt) throws SQLException { 
                        stmt.setInt(1, id);

                    } 
                });

                if (getResult) { 
                    return permission; 
                } 
            } catch (SQLException e) { 
                log.error("查詢單條的權限信息異常!"); 
                e.printStackTrace(); 
            } 
        }

        return null; 
    }

    @Override 
    public boolean delete(final int id) { 
        if (0 < id) { 
            try { 
                return DB.insertUpdate(PERMISSION_DELETE_BY_ID, new IUStH() {

                    @Override 
                    public void handleInsertUpdate(PreparedStatement stmt) throws SQLException { 
                        stmt.setInt(1, id); 
                        stmt.executeUpdate(); 
                    } 
                }); 
            } catch (SQLException e) { 
                log.error("刪除單條的權限信息異常!"); 
                e.printStackTrace(); 
            } 
        }

        return false; 
    }

    @Override 
    public boolean batchDelete(final int[] idArray) { 
        if (null != idArray && 1 < idArray.length) { 
            try { 
                return DB.insertUpdate(PERMISSION_DELETE_BY_ID, new IUStH() {

                    @Override 
                    public void handleInsertUpdate(PreparedStatement stmt) throws SQLException { 
                        for (int i : idArray) { 
                            stmt.setInt(1, i); 
                            stmt.addBatch(); 
                        } 
                        stmt.executeBatch(); 
                    } 
                }); 
            } catch (SQLException e) { 
                log.error("批量刪除權限信息異常!"); 
                e.printStackTrace(); 
            } 
        }

        return false; 
    }

    @Override 
    public ImmutableList<Permission> listAll() {

        final List<Permission> permissionList = Lists.newLinkedList();

        boolean listResult; 
        try { 
            listResult = DB.select(PERMISSION_LIST_ALL, new ReadStH() {

                @Override 
                public void handleRead(ResultSet rs) throws SQLException { 
                    while (rs.next()) { 
                        permissionList.add(handResult(new Permission(), rs)); 
                    }

                } 
            }); 
            if (listResult) { 
                return ImmutableList.copyOf(permissionList); 
            }

        } catch (SQLException e) { 
            log.error("查詢全部的權限信息異常!"); 
            e.printStackTrace(); 
        }

        return null; 
    }

    @Override 
    public ImmutableList<Permission> list(final int pageSize, final int page) { 
        final List<Permission> permissionList = Lists.newLinkedList();

        boolean listResult; 
        try { 
            listResult = DB.select(PERMISSION_LIST_ALL, new ParamReadStH() { 
                @Override 
                public void handleRead(ResultSet rs) throws SQLException { 
                    while (rs.next()) { 
                        permissionList.add(handResult(new Permission(), rs)); 
                    }

                }

                @Override 
                public void setParams(PreparedStatement stmt) throws SQLException { 
                    int start = pageSize * (page - 1); 
                    int end = start + pageSize;

                    stmt.setInt(1, start); 
                    stmt.setInt(2, end);

                } 
            }); 
            if (listResult) { 
                return ImmutableList.copyOf(permissionList); 
            }

        } catch (SQLException e) { 
            log.error("分頁查詢權限信息異常!"); 
            e.printStackTrace(); 
        }

        return null; 
    }

    private Permission handResult(final Permission permission, ResultSet rs) throws SQLException { 
        permission.setId(rs.getInt("id")); 
        permission.setpName(rs.getString("pName")); 
        permission.setpDesc(rs.getString("pDesc")); 
        permission.setOrder(rs.getInt("order")); 
        permission.setCreateDate(StringUtil.transforFromSqlToUtilDate(rs.getDate("createDate"))); 
        permission.setpFunctionName(rs.getString("pFunctionName")); 
        permission.setExt(rs.getString("ext")); 
        permission.setPid(rs.getInt("pid")); 
        permission.setpLevel(rs.getInt("pLevel")); 
        permission.setpUrl(rs.getString("pUrl"));

        return permission; 
    }

    @Override 
    public ImmutableList<Permission> getPermissionsByRoleId(final int roleId) { 
        if (0 < roleId) { 
            final List<Permission> permissions = Lists.newLinkedList(); 
            try { 
                boolean getResult = DB.select(PERMISSION_GET_BY_ROLEID, new ParamReadStH() {

                    @Override 
                    public void handleRead(ResultSet rs) throws SQLException { 
                        while (rs.next()) { 
                            permissions.add(handResult(new Permission(), rs)); 
                        }

                    }

                    @Override 
                    public void setParams(PreparedStatement stmt) throws SQLException { 
                        stmt.setInt(1, roleId);

                    } 
                });

                if (getResult) { 
                    return ImmutableList.copyOf(permissions); 
                } 
            } catch (SQLException e) { 
                log.error("根據角色查詢權限信息異常!"); 
                e.printStackTrace(); 
            } 
        }

        return null; 
    }

}
View Code

 

package com.cutter.web.account.dao.achieve;

import java.sql.PreparedStatement; 
import java.sql.ResultSet; 
import java.sql.SQLException; 
import java.util.List;

import org.apache.log4j.Logger; 
import org.apache.tiles.jsp.taglib.InsertAttributeTag; 
import org.pureart.persistement.database.easydb.DB; 
import org.pureart.persistement.database.easydb.IUStH; 
import org.pureart.persistement.database.easydb.ParamReadStH; 
import org.pureart.persistement.database.easydb.ReadStH;

import com.cutter.web.account.dao.entity.Log; 
import com.cutter.web.account.dao.inter.LogDao; 
import com.cutter.web.account.util.StringUtil; 
import com.google.common.collect.ImmutableList; 
import com.google.common.collect.Lists;

public class LogDaoAchieve implements LogDao {

    private static final Logger log = Logger.getLogger(LogDaoAchieve.class);

    private static final String LOG_TABLE = " test.dt_log ";

    private static final String LOG_SELECT = " SELECT * FROM " + LOG_TABLE;

    private static final String LOG_GET_BY_ID = LOG_SELECT + " WHERE id=? ;";

    private static final String LOG_DELETE_BY_ID = " DELETE FROM " + LOG_TABLE + " WHERE id=? ;";

    private static final String LOG_LIST_ALL = LOG_SELECT + " ORDER BY createDate DESC ;";

    private static final String LOG_LIST_ALL_BY_PAGE = LOG_SELECT + " ORDER BY createDate DESC limit ?,? ;";

    private static final String LOG_LIST_ALL_BY_TYPE = LOG_SELECT + " WHERE type=? ;";

    private static final String LOG_ADD = " INSERT INTO " + LOG_TABLE 
            + " (userName,ip,type,content,createDate,ext1,ext2) VALUES(?,?,?,?,?,?,?) ;";

    private static final String LOG_UPDATE = " UPDATE " + LOG_TABLE 
            + " SET userName=? , ip=? , type=? , content=? , createDate=? , ext1=? , ext2=? WHERE id=? ;";

    @Override 
    public boolean update(final Log entity) {

        if (null != entity) { 
            try { 
                final boolean flag = 0 < entity.getId();

                return DB.insertUpdate(flag ? LOG_UPDATE : LOG_ADD, new IUStH() {

                    @Override 
                    public void handleInsertUpdate(PreparedStatement stmt) throws SQLException { 
                        stmt.setString(1, entity.getUserName()); 
                        stmt.setString(2, entity.getIp()); 
                        stmt.setInt(3, entity.getType()); 
                        stmt.setString(4, entity.getContent()); 
                        stmt.setDate(5, StringUtil.transforFromUtilToSqlDate(entity.getCreateDate())); 
                        stmt.setString(6, entity.getExt1()); 
                        stmt.setString(7, entity.getExt2()); 
                        if (flag) { 
                            stmt.setInt(8, entity.getId()); 
                        } 
                        stmt.executeUpdate();

                    } 
                });

            } catch (SQLException e) { 
                log.error("更新用戶日誌異常!"); 
                e.printStackTrace(); 
            } 
        }

        return false; 
    }

    @Override 
    public Log get(final int id) { 
        try { 
            final Log log = new Log(); 
            boolean selectResult = DB.select(LOG_GET_BY_ID, new ParamReadStH() {

                @Override 
                public void handleRead(ResultSet rs) throws SQLException { 
                    if (rs.next()) { 
                        handleResult(log, rs); 
                    } 
                }

                @Override 
                public void setParams(PreparedStatement stmt) throws SQLException { 
                    stmt.setInt(1, id); 
                } 
            });

            if (selectResult) { 
                return log; 
            }

        } catch (SQLException e) { 
            log.error("查詢單條的日誌信息異常!"); 
            e.printStackTrace(); 
        }

        return null; 
    }

    @Override 
    public boolean delete(final int id) {

        try { 
            if (0 < id) { 
                return DB.insertUpdate(LOG_DELETE_BY_ID, new IUStH() {

                    @Override 
                    public void handleInsertUpdate(PreparedStatement stmt) throws SQLException { 
                        stmt.setInt(1, id); 
                        stmt.executeUpdate(); 
                    } 
                }); 
            } 
        } catch (SQLException e) { 
            log.error("刪除用戶日誌異常!"); 
            e.printStackTrace(); 
        } 
        return false; 
    }

    @Override 
    public boolean batchDelete(final int[] idArray) {

        try { 
            if (null != idArray && 1 <= idArray.length) { 
                return DB.insertUpdate(LOG_DELETE_BY_ID, new IUStH() {

                    @Override 
                    public void handleInsertUpdate(PreparedStatement stmt) throws SQLException {

                        for (int i : idArray) { 
                            stmt.setInt(1, i); 
                            stmt.addBatch(); 
                        } 
                        stmt.executeBatch();

                    } 
                }); 
            } 
        } catch (SQLException e) { 
            log.error("批量刪除日誌異常!"); 
            e.printStackTrace(); 
        }

        return false; 
    }

    @Override 
    public ImmutableList<Log> listAll() { 
        final List<Log> logList = Lists.newLinkedList(); 
        try { 
            final boolean listResult = DB.select(LOG_LIST_ALL, new ReadStH() {

                @Override 
                public void handleRead(ResultSet rs) throws SQLException { 
                    while (rs.next()) { 
                        logList.add(handleResult(new Log(), rs)); 
                    } 
                } 
            });

            if (listResult) { 
                return ImmutableList.copyOf(logList); 
            }

        } catch (SQLException e) { 
            log.error("查詢全部的日誌異常!"); 
            e.printStackTrace(); 
        }

        return null; 
    }

    @Override 
    public ImmutableList<Log> list(final int pageSize, final int page) { 
        try { 
            if (0 < page && 0 < pageSize) { 
                final List<Log> logList = Lists.newLinkedList(); 
                final boolean listResult = DB.select(LOG_LIST_ALL_BY_PAGE, new ParamReadStH() {

                    @Override 
                    public void handleRead(ResultSet rs) throws SQLException { 
                        while (rs.next()) { 
                            logList.add(handleResult(new Log(), rs)); 
                        } 
                    }

                    @Override 
                    public void setParams(PreparedStatement stmt) throws SQLException { 
                        int start = pageSize * (page - 1); 
                        int end = start + pageSize; 
                        stmt.setInt(1, start); 
                        stmt.setInt(2, end); 
                    } 
                });

                if (listResult) { 
                    return ImmutableList.copyOf(logList); 
                }

            }

        } catch (SQLException e) { 
            log.error("分頁查詢日誌異常!"); 
            e.printStackTrace(); 
        }

        return null; 
    }

    @Override 
    public ImmutableList<Log> getLogByType(final int typeId) { 
        final List<Log> logList = Lists.newLinkedList(); 
        try { 
            final boolean listResult = DB.select(LOG_LIST_ALL, new ParamReadStH() {

                @Override 
                public void handleRead(ResultSet rs) throws SQLException { 
                    while (rs.next()) { 
                        logList.add(handleResult(new Log(), rs)); 
                    } 
                }

                @Override 
                public void setParams(PreparedStatement stmt) throws SQLException { 
                    stmt.setInt(1, typeId);

                } 
            });

            if (listResult) { 
                return ImmutableList.copyOf(logList); 
            }

        } catch (SQLException e) { 
            log.error("根據類型id查詢日誌異常!"); 
            e.printStackTrace(); 
        }

        return null; 
    }

    private Log handleResult(final Log log, ResultSet rs) throws SQLException {

        log.setId(rs.getInt("id")); 
        log.setUserName(rs.getString("userName")); 
        log.setIp(rs.getString("ip")); 
        log.setContent(rs.getString("content")); 
        log.setCreateDate(StringUtil.transforFromSqlToUtilDate(rs.getDate("createDate"))); 
        log.setType(rs.getInt("type")); 
        log.setExt1(rs.getString("ext1")); 
        log.setExt2(rs.getString("ext2"));

        return log; 
    }

}
View Code

 

開玩笑 這麼枯燥重複的代碼我硬是耐着性子花了一個半小時碼完,真的服了本身,必須儘快找個簡單易用的jpa框架來解放一下本身。tomcat

 

2,界面設計和導航

作出來的界面先照個面;

導航效果圖

 

主要是在跳轉到主頁的時候,給出右側導航欄的數據,而後使用tiles佈局,實現頁面的導航,基本完成了任務;下面貼出要點;

要點 說明
導航數據提取,初始化導航欄的時候先初始化菜單級別的權限,而後是導航級別的;到頁面的時候設置一個攔截器,若是用戶有權限,顯示並導航,沒有則攔截並隱藏;

private  List<PermissionTreeNode>  handlePermission(ImmutableList<PermissionEntity> permissions)
   {
      
       if(null!=permissions&&!permissions.isEmpty())
       {
           List<PermissionTreeNode> tree=Lists.newLinkedList();
           //1,篩選出菜單項
          Collection<PermissionEntity> menuCollection= Collections2.filter(permissions, new Predicate<PermissionEntity>() {

               @Override
               public boolean apply(PermissionEntity input) {
                   return input.getpLevel()==1;
               }
           });
         
          if(null!=menuCollection&&!menuCollection.isEmpty())
          {
              //2,組裝成樹型結構
              for (final PermissionEntity menuItem : menuCollection) {
               PermissionTreeNode node=new PermissionTreeNode();
               node.setPid(menuItem.getId());
               node.setpName(menuItem.getpName());
               node.setChildren(Collections2.filter(permissions, new Predicate<PermissionEntity>() {

                   @Override
                   public boolean apply(PermissionEntity input) {
                       return input.getPid()==menuItem.getId()&&input.getpLevel()==2;
                   }
               }));
               tree.add(node);
           }
              return tree;
          }
         
       }
      
       return null;
   }

導航數據的構造,這裏使用的是方法取得屬性,使用成員變量名取不到,不知道是爲何,下次搞清楚了再貼出來;

<div style="background-color:gray;text-align: center;">
    <h1>導航</h1>

    <hr>
    <s:iterator id="item" value="#session.permission" var="item">
        <div>
            <span><s:property value="#item.getpName()" /> </span>
            <s:iterator var="navItem" value="#item.getChildren()">
                <br><a href="<%=contextPath%><s:property value="#navItem.getpUrl()" /> ">
                    <s:property value="#navItem.getpName()" /> </a>
            </s:iterator>
        </div>

    </s:iterator>
</div>

tiles組件配置,這裏搞了一個title,算是人性化一點;

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE tiles-definitions PUBLIC "-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN" "http://tiles.apache.org/dtds/tiles-config_2_0.dtd">
<tiles-definitions>
    <definition name="adminHomePage" extends="adminDefaultLayout">
        <put-attribute name="titleKey" value="cutter哥哥後臺管理主頁"/>   
        <put-attribute name="content" value="/manager/index.jsp" />
    </definition>
    <definition name="listUserPage" extends="adminDefaultLayout">
        <put-attribute name="titleKey" value="查詢用戶"/>
        <put-attribute name="content" value="/manager/user/userList.jsp" />
    </definition>
    <definition name="addUserPage" extends="adminDefaultLayout">
        <put-attribute name="titleKey" value="增長用戶"/>
        <put-attribute name="content" value="/manager/user/addList.jsp" />
    </definition>
    <definition name="editUserPage" extends="adminDefaultLayout">
        <put-attribute name="titleKey" value="編輯用戶"/>
        <put-attribute name="content" value="/manager/user/editList.jsp" />
    </definition>
</tiles-definitions>

優化了一下佈局,做爲後臺開發人員,前端的佈局和樣式實在是有待增強,見諒;

<style type="text/css">
body {
    text-decoration: none;
    width: 100%;
    height: 100%;
    text-align: center;
}

.head {
    width: 100%;
    height: 50px;
    background-color: green;
}

.bottom {
    width: 100%;
    height: 30px;
    background-color: green;
}

.leftBox {
    width: 100px;
    height: 600px;
    background-color: green;
    clear:both;
    float: left;
}

.content {
    width: 90%;
    height: 600px;
    clear: right;
    margin-left: 100px;
    margin-top: 50px;
}
</style>

 

3,struts2的流程原理跟蹤

要開發高效耐用的站點,並在站點出現問題的時候及時的補救,瞭解站點的啓動和運行過程是頗有必要的,如今手上的這個小demo規模很小,

我忍不住想要知道它究竟是怎麼啓動和運行的,struts2這個萬能代理到底起到一個神馬做用;結合開始自學的那個圖,來跟蹤站點的啓動和

運行過程;

 

站點的啓動過程,tomcat啓動以後,開始部署站,好比說要部署個人小站,首先它會找到WEB-INF,把下面的jar包先加載完,以後是通常的java代碼,

Jsp轉換以後的java代碼,靜態資源等(這是個猜測,以後我會去看看tomcat的核心代碼,看看它的運行機制究竟是不是這樣的?)

看tomcat的啓動日誌可見一斑;

tomcat的啓動日誌部分

 

站點啓動過程:我的經過源碼分析;

站點的啓動

 

tiles的啓動細節分析:

要點 代碼分析
tiles的啓動過程

1,首先,獲得ServletContext對象;經過tomcat的啓動事件獲得;

2,獲得tiler容器,經過ServletContext構造;
若是ServletContext不含有key爲TilesContainerFactory.CONTEXT_FACTORY_INIT_PARAM(
public static final String CONTEXT_FACTORY_INIT_PARAM =
        "org.apache.tiles.context.TilesContextFactory";)的配置,裝飾一個;
  if(context.getInitParameter(TilesContainerFactory.CONTEXT_FACTORY_INIT_PARAM) == null) {
            context = decorate(context);
        }
        else {
            if (LOG.isWarnEnabled()) {
            LOG.warn("Tiles container factory is explicitly set.  Not injecting struts configuration.");
            }
        }
        return super.createContainer(context);

裝飾過程以下:
protected ServletContext decorate(ServletContext context) {
        return new ConfiguredServletContext(context, INIT);
    }
直接使用現有的ServletContext和一個空的map實例化一個,做爲ServletContext;
而後調用父類的工廠,建立一個容器;建立過程以下:
public TilesContainer createTilesContainer(Object context)
        throws TilesException {
        BasicTilesContainer container = new BasicTilesContainer();
        initializeContainer(context, container);
        return container;
    }
先建立一個基本的tiles容器,而後使用ServletContext初始化;

一切準備工做作好以後會打出一個log:Initializing Tiles2 container. . .

而後會初始化定義的配置文件,一個一個的加載到內存;
DEBUG - Adding resource 'jndi:/localhost/sq/WEB-INF/tiles/tiles.xml' to definitions factory.
DEBUG - Adding resource 'jndi:/localhost/sq/WEB-INF/tiles/tiles-adminUser.xml' to definitions factory.
獲得一個讀取配置文件的對象:
DEBUG - register('-//Apache Software Foundation//DTD Tiles Configuration 2.0//EN', 'jar:file:/E:/evn/tomcat7-32or64/webapps/sq/WEB-INF/lib/tiles-cor
最後讀取配置文件,找到tiles屬性對應的文件,最後是初始化好定義的tiles組件;

BUG -   Popping body text ''
DEBUG - endDocument()
DEBUG - Resolve definition for child name='addUserPage' extends='adminDefaultLayout'.
DEBUG - Resolve definition for child name='adminHomePage' extends='adminDefaultLayout'.
DEBUG - Resolve definition for child name='editUserPage' extends='adminDefaultLayout'.
DEBUG - Resolve definition for child name='listUserPage' extends='adminDefaultLayout'.

最後把tiles容器發不到服務器的上下文;

struts2的過濾器的啓動過程

struts2的初始化過程:
public void init(FilterConfig filterConfig) throws ServletException {
        InitOperations init = new InitOperations();
        try {
            FilterHostConfig config = new FilterHostConfig(filterConfig);
            init.initLogging(config);
           Dispatcher dispatcher = init.initDispatcher(config);
            init.initStaticContentLoader(config, dispatcher);

            prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher);
            execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher);
            this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);

            postInit(dispatcher, filterConfig);
        } finally {
            init.cleanup();
        }
    }

首先獲得過濾器的配置文件,接着初始化日誌,
而後加載struts的配置文件到內存,完成url和Action的映射(紅色部分);

快下班了明天再分析紅色的那部分代碼;

最後是把控制權交還給tomcat的線程,完成tomcat的啓動;

站點的運行過程放到下一節來講,晚上還有籃球賽,血戰研發1,加油·············

4,小結

按照通常的後臺的需求,模擬完成了兩個功能,導航設計和權限管理,而後跟蹤了一遍站點的啓動和運行過程,加深了對struts2的理解;最後

奉上一個搞笑的圖片,但願每天開心,保持好的心態;

搞笑圖片2

相關文章
相關標籤/搜索