• JavaWeb 案例——访问权限控制


    JavaWeb 案例——访问权限控制

     

    一、功能介绍

           每个网站都涉及到访问权限的控制。每个站点资源都需要被管理起来,用户只有具有访问某个资源的特定权限,才能够访问,否则拒绝访问。

    二、项目分析

           我们要实现网站的访问权限控制,就应该从 URI 入手,站点的每个资源都用唯一的 URI 描述,我们为想要管理起来的 URI 增加上权限属性,当用户访问资源时我们要先检查用户是否具有权限。这个项目我采用过滤器技术实现权限拦截,下一个项目我将采用注解+动态代理实现权限的拦截。

            我们需要编写一个过滤器,拦截用户的每个访问请求。再依据 URI 判断是否需要权限。这个是比较简单的,关键就是我们如何将这种权限关系描述出来,如果使用过滤器技术,我们就不得不使用数据库来将每个权限、资源等保存起来。一个资源需要一个权限,一个权限对应多个角色,一个角色可以拥有多个权限,一个用户拥有多个角色,一个角色又可以被多个用户引用。所以资源与权限是一对一关系,权限与角色是多对多关系,角色与用户也是多对多关系。因此在数据库我们需要6张表来保存关系。

     

    一、对象关系	资源、权限、角色、用户
    
    	资源   	------>		权限		一对多
    	权限	    <----->		角色		多对多
    	角色   	<----->		用户		多对多
    	
    	资源:
    		String id	编号
    		String uri	资源uri
    		String description	描述
    		Permission permission	该资源需要的权限
    		
    	权限:
    		String id	编号
    		String name	权限名
    		String description 权限描述
    		
    	角色:
    		String id	编号
    		String name	角色名
    		String description 角色描述
    		Set<Permission> set 该角色具有的权限
    		
    	用户:
    		String id	编号
    		String username	用户名
    		String password	密码
    		Set<Role> set	该用户都具有的角色
    		
    二、数据库实现
    
    create database if not exists sys_permission;
    use sys_permission;
    
    create table if not exists resource(
    	id varchar(40) primary key,
    	uri varchar(255) unique,
    	description varchar(255),
    	permission_id varchar(40),
    	constraint rPermission_id_FK foreign key(permission_id) references permission(id)
    );
    
    create table if not exists permission(
    	id varchar(40) primary key,
    	name varchar(40) unique,
    	description varchar(255)
    );
    
    create table if not exists role(
    	id varchar(40) primary key,
    	name varchar(40) unique,
    	description varchar(255)
    );
    
    create table if not exists user(
    	id varchar(40) primary key,
    	username varchar(40) not null unique,
    	password varchar(40) not null
    );
    
    create table if not exists permission_role(
    	permission_id varchar(40) not null,
    	role_id varchar(40) not null,
    	constraint permission_id_FK foreign key(permission_id) references permission(id),
    	constraint role_id_FK foreign key(role_id) references role(id),
    	constraint primary key(permission_id,role_id)
    );
    
    create table if not exists user_role(
    	user_id varchar(40) not null,
    	role_id varchar(40) not null,
    	constraint user_id_FK foreign key(user_id) references user(id),
    	constraint uRole_id_FK foreign key(role_id) references role(id),
    	constraint primary key(user_id,role_id)
    );


    三、项目新技术

           1、采用 sitemesh 框架为每个页面动态增加模版。原理:sitemesh 实际上也是一个过滤器,当用户访问一个页面时,sitemesh 将请求拦截下来,在服务器以后使用 response 写出数据的时候,实际上是写到了代理对象的缓存中,当数据读写完,sitemesh 再对数据进行包装之后再打给浏览器。

             2、采用 windows 命令初始化数据库。我们将数据库的初始化信息写在文件中,当在浏览器访问初始化 Servlet 时,将使用 windows 命令将文件中的数据导入到 mysql 中。

     

    package cn.dk.domain;
    
    public class Permission {
    
    	private String id;
    	private String name;
    	private String description;
    
    	public String getId() {
    		return id;
    	}
    
    	public void setId(String id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public String getDescription() {
    		return description;
    	}
    
    	public void setDescription(String description) {
    		this.description = description;
    	}
    
    	@Override
    	public int hashCode() {
    		final int prime = 31;
    		int result = 1;
    		result = prime * result + ((id == null) ? 0 : id.hashCode());
    		return result;
    	}
    
    	@Override
    	public boolean equals(Object obj) {
    		if (this == obj)
    			return true;
    		if (obj == null)
    			return false;
    		if (getClass() != obj.getClass())
    			return false;
    		final Permission other = (Permission) obj;
    		if (id == null) {
    			if (other.id != null)
    				return false;
    		} else if (!id.equals(other.id))
    			return false;
    		return true;
    	}
    
    }
    
    package cn.dk.domain;
    
    public class Resource {
    
    	private String id;
    	private String uri;
    	private String description;
    	private Permission permission;
    
    	public String getId() {
    		return id;
    	}
    
    	public void setId(String id) {
    		this.id = id;
    	}
    
    	public String getUri() {
    		return uri;
    	}
    
    	public void setUri(String uri) {
    		this.uri = uri;
    	}
    
    	public String getDescription() {
    		return description;
    	}
    
    	public void setDescription(String description) {
    		this.description = description;
    	}
    
    	public Permission getPermission() {
    		return permission;
    	}
    
    	public void setPermission(Permission permission) {
    		this.permission = permission;
    	}
    }
    
    package cn.dk.domain;
    
    import java.util.HashSet;
    import java.util.Set;
    
    public class Role {
    
    	public Role() {
    		super();
    		this.permissions = new HashSet<Permission>();
    	}
    
    	private String id;
    	private String name;
    	private String description;
    	private Set<Permission> permissions;
    
    	public String getId() {
    		return id;
    	}
    
    	public void setId(String id) {
    		this.id = id;
    	}
    
    	public String getName() {
    		return name;
    	}
    
    	public void setName(String name) {
    		this.name = name;
    	}
    
    	public String getDescription() {
    		return description;
    	}
    
    	public void setDescription(String description) {
    		this.description = description;
    	}
    
    	public Set<Permission> getPermissions() {
    		return permissions;
    	}
    
    	public void setPermissions(Set<Permission> permissions) {
    		this.permissions = permissions;
    	}
    }
    
    package cn.dk.domain;
    
    import java.util.HashSet;
    import java.util.Set;
    
    public class User {
    	
    	public User(){
    		super();
    		this.roles = new HashSet<Role>();
    	}
    
    	private String id;
    	private String username;
    	private String password;
    	private Set<Role> roles;
    
    	public String getId() {
    		return id;
    	}
    
    	public void setId(String id) {
    		this.id = id;
    	}
    
    	public String getUsername() {
    		return username;
    	}
    
    	public void setUsername(String username) {
    		this.username = username;
    	}
    
    	public String getPassword() {
    		return password;
    	}
    
    	public void setPassword(String password) {
    		this.password = password;
    	}
    
    	public Set<Role> getRoles() {
    		return roles;
    	}
    
    	public void setRoles(Set<Role> roles) {
    		this.roles = roles;
    	}
    }
    
    package cn.dk.dao;
    
    import java.util.List;
    
    import cn.dk.domain.Permission;
    
    public interface IPermissionDao {
    
    	// 插入新权限
    	void insertPermission(Permission permission);
    
    	// 删除权限
    	void deletePermission(String id);
    
    	// 根据id查找权限
    	Permission findPermissionById(String id);
    
    	// 查找所有权限
    	@SuppressWarnings("unchecked")
    	List<Permission> findAllPermission();
    
    }
    package cn.dk.dao;
    
    import java.util.List;
    
    import cn.dk.domain.Resource;
    
    public interface IResourceDao {
    
    	// 增加资源
    	void insertResource(Resource resource);
    
    	// 修改资源
    	void updateResource(Resource resource);
    
    	// 查找所有资源
    	@SuppressWarnings("unchecked")
    	List<Resource> findAllResource();
    
    	// 根据uri查找资源
    	Resource findResourceByURI(String uri);
    
    	// 根据id查找资源
    	Resource findResourceById(String id);
    
    	// 删除资源
    	void deleteResource(String id);
    
    }
    package cn.dk.dao;
    
    import java.util.List;
    import cn.dk.domain.Role;
    
    public interface IRoleDao {
    
    	// 新增角色
    	void insertRole(Role role);
    
    	// 更新角色
    	void updateRole(Role role);
    
    	// 删除角色
    	void deleteRole(String id);
    
    	// 根据id查找角色
    	@SuppressWarnings("unchecked")
    	Role findRoleById(String id);
    
    	// 查找所有角色
    	@SuppressWarnings("unchecked")
    	List<Role> fineAllRole();
    
    }
    package cn.dk.dao;
    
    import java.util.List;
    import cn.dk.domain.User;
    
    public interface IUserDao {
    
    	// 插入用户
    	void insertUser(User user);
    
    	// 更新用户
    	void updateUser(User user);
    
    	// 删除用户
    	void deleteUser(String id);
    
    	// 根据id查找用户
    	@SuppressWarnings("unchecked")
    	User findUserById(String id);
    
    	// 查找所有用户
    	@SuppressWarnings("unchecked")
    	List<User> findAllUser();
    	
    	User login(String username, String password);
    }
    package cn.dk.dao.impl;
    
    import java.sql.SQLException;
    import java.util.List;
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.BeanHandler;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
    import cn.dk.dao.IPermissionDao;
    import cn.dk.domain.Permission;
    import cn.dk.utils.DBUtils;
    
    public class PermissionDaoImpl implements IPermissionDao {
    
    	// 插入新权限
    	public void insertPermission(Permission permission) {
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "insert into permission (id,name,description) values(?,?,?)";
    		Object[] params = { permission.getId(), permission.getName(),
    				permission.getDescription() };
    		try {
    			runner.update(sql, params);
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	// 删除权限
    	public void deletePermission(String id) {
    		QueryRunner runer = new QueryRunner(DBUtils.getDataSource());
    		String sql = "update resource set permission_id=null where permission_id=?";
    		try {
    			runer.update(sql, id);
    			sql = "delete from permission where id=?";
    			runer.update(sql, id);
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	// 根据id查找权限
    	public Permission findPermissionById(String id) {
    		QueryRunner runer = new QueryRunner(DBUtils.getDataSource());
    		String sql = "select id,name,description from permission where id=?";
    		Object[] params = { id };
    		try {
    			return (Permission) runer.query(sql, new BeanHandler(
    					Permission.class), params);
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	// 查找所有权限
    	@SuppressWarnings("unchecked")
    	public List<Permission> findAllPermission() {
    		List<Permission> list = null;
    		QueryRunner runer = new QueryRunner(DBUtils.getDataSource());
    		String sql = "select id,name,description from permission";
    		try {
    			list = (List<Permission>) runer.query(sql, new BeanListHandler(
    					Permission.class));
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    		return list;
    	}
    }
    
    package cn.dk.dao.impl;
    
    import java.sql.SQLException;
    import java.util.List;
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.BeanHandler;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
    import cn.dk.dao.IResourceDao;
    import cn.dk.domain.Permission;
    import cn.dk.domain.Resource;
    import cn.dk.utils.DBUtils;
    
    public class ResourceDaoImpl implements IResourceDao {
    
    	// 增加资源
    	public void insertResource(Resource resource) {
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "insert into resource (id,uri,description,permission_id) values(?,?,?,?)";
    		Object[] params = { resource.getId(), resource.getUri(),
    				resource.getDescription(), resource.getPermission().getId() };
    		try {
    			runner.update(sql, params);
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	// 修改资源
    	public void updateResource(Resource resource) {
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "update resource set uri=?,description=?,permission_id=? where id=?";
    		Object[] params = { resource.getUri(), resource.getDescription(),
    				resource.getPermission().getId(), resource.getId() };
    		try {
    			runner.update(sql, params);
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	// 查找所有资源
    	@SuppressWarnings("unchecked")
    	public List<Resource> findAllResource() {
    		List<Resource> list = null;
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "select id,uri,description from resource";
    		try {
    			list = (List<Resource>) runner.query(sql, new BeanListHandler(
    					Resource.class));
    			for (Resource resource : list) {
    				sql = "select p.id,p.name,p.description from permission p,resource r where r.permission_id=p.id and r.id=?";
    				Object[] params = { resource.getId() };
    				Permission permission = (Permission) runner.query(sql,
    						new BeanHandler(Permission.class), params);
    				resource.setPermission(permission);
    			}
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    		return list;
    	}
    
    	// 根据uri查找资源
    	public Resource findResourceByURI(String uri) {
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "select id,uri,description from resource where uri=?";
    		Object[] params = { uri };
    		try {
    			Resource resource = (Resource) runner.query(sql, new BeanHandler(
    					Resource.class), params);
    			if (resource == null)
    				return null;
    			sql = "select p.id,p.name,p.description from permission p,resource r where r.permission_id=p.id and r.id=?";
    			params = new Object[] { resource.getId() };
    			Permission permission = (Permission) runner.query(sql,
    					new BeanHandler(Permission.class), params);
    			resource.setPermission(permission);
    			return resource;
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	// 根据id查找资源
    	public Resource findResourceById(String id) {
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "select id,uri,description from resource where id=?";
    		Object[] params = { id };
    		try {
    			Resource resource = (Resource) runner.query(sql, new BeanHandler(
    					Resource.class), params);
    			sql = "select p.id,p.name,p.description from permission p,resource r where r.permission_id=p.id and r.id=?";
    			params = new Object[] { resource.getId() };
    			Permission permission = (Permission) runner.query(sql,
    					new BeanHandler(Permission.class), params);
    			resource.setPermission(permission);
    			return resource;
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	// 删除资源
    	public void deleteResource(String id) {
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "delete from resource where id=?";
    		Object[] params = { id };
    		try {
    			runner.update(sql, params);
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    }
    
    package cn.dk.dao.impl;
    
    import java.sql.SQLException;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.BeanHandler;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
    import cn.dk.dao.IRoleDao;
    import cn.dk.domain.Permission;
    import cn.dk.domain.Role;
    import cn.dk.utils.DBUtils;
    
    public class RoleDaoImpl implements IRoleDao {
    
    	// 新增角色
    	public void insertRole(Role role) {
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "insert into role (id,name,description) values(?,?,?)";
    		Object[] params = { role.getId(), role.getName(), role.getDescription() };
    		try {
    			runner.update(sql, params);
    			sql = "insert into permission_role (permission_id,role_id) values(?,?)";
    			Set<Permission> set = role.getPermissions();
    			for (Permission permission : set) {
    				params = new Object[] { permission.getId(), role.getId() };
    				runner.update(sql, params);
    			}
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	// 更新角色
    	public void updateRole(Role role) {
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		Set<Permission> set = role.getPermissions();
    		String sql = "delete from permission_role where role_id=?";
    		try {
    			runner.update(sql, role.getId());
    			sql = "update role set name=?,description=? where id=?";
    			Object[] params = { role.getName(), role.getDescription(),
    					role.getId() };
    			runner.update(sql, params);
    			sql = "insert into permission_role (permission_id,role_id) values(?,?)";
    			for (Permission permission : set) {
    				params = new Object[] { permission.getId(), role.getId() };
    				runner.update(sql, params);
    			}
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	// 删除角色
    	public void deleteRole(String id) {
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "delete from permission_role where role_id=?";
    		try {
    			runner.update(sql, id);
    			sql = "delete from role where id=?";
    			runner.update(sql, id);
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	// 根据id查找角色
    	@SuppressWarnings("unchecked")
    	public Role findRoleById(String id) {
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "select id,name,description from role where id=?";
    		Object[] params = { id };
    		try {
    			Role role = (Role) runner.query(sql, new BeanHandler(Role.class),
    					params);
    			sql = "select p.id,p.name,p.description from permission p,permission_role pr where p.id=pr.permission_id and pr.role_id=?";
    			params = new Object[] { id };
    			Set<Permission> set = new HashSet<Permission>();
    			set.addAll((List<Permission>) runner.query(sql,
    					new BeanListHandler(Permission.class), params));
    			role.setPermissions(set);
    			return role;
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	// 查找所有角色
    	@SuppressWarnings("unchecked")
    	public List<Role> fineAllRole() {
    		List<Role> list = null;
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "select id,name,description from role";
    		try {
    			list = (List<Role>) runner.query(sql, new BeanListHandler(
    					Role.class));
    			sql = "select p.id,p.name,p.description from permission p,permission_role pr where p.id=pr.permission_id and pr.role_id=?";
    			for (Role role : list) {
    				Object[] params = new Object[] { role.getId() };
    				Set<Permission> set = new HashSet<Permission>();
    				set.addAll((List<Permission>) runner.query(sql,
    						new BeanListHandler(Permission.class), params));
    				role.setPermissions(set);
    			}
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    		return list;
    	}
    }
    
    package cn.dk.dao.impl;
    
    import java.sql.SQLException;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    import org.apache.commons.dbutils.QueryRunner;
    import org.apache.commons.dbutils.handlers.BeanHandler;
    import org.apache.commons.dbutils.handlers.BeanListHandler;
    import cn.dk.dao.IUserDao;
    import cn.dk.domain.Role;
    import cn.dk.domain.User;
    import cn.dk.utils.DBUtils;
    
    public class UserDaoImpl implements IUserDao {
    
    	// 插入用户
    	public void insertUser(User user) {
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "insert into user (id,username,password) values(?,?,?)";
    		Object[] params = { user.getId(), user.getUsername(),
    				user.getPassword() };
    		try {
    			runner.update(sql, params);
    			Set<Role> roles = user.getRoles();
    			sql = "insert into user_role (user_id,role_id) values(?,?)";
    			for (Role role : roles) {
    				params = new Object[] { user.getId(), role.getId() };
    				runner.update(sql, params);
    			}
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	// 更新用户
    	public void updateUser(User user) {
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "delete from user_role where user_id=?";
    		try {
    			runner.update(sql, user.getId());
    			sql = "update user set username=?,password=? where id=?";
    			Object[] params = { user.getUsername(), user.getPassword(),
    					user.getId() };
    			runner.update(sql, params);
    			sql = "insert into user_role (user_id,role_id) values(?,?)";
    			Set<Role> roles = user.getRoles();
    			for (Role role : roles) {
    				params = new Object[] { user.getId(), role.getId() };
    				runner.update(sql, params);
    			}
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	// 删除用户
    	public void deleteUser(String id) {
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "delete from user_role where user_id=?";
    		try {
    			runner.update(sql, id);
    			sql = "delete from user where id=?";
    			runner.update(sql, id);
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	// 根据id查找用户
    	@SuppressWarnings("unchecked")
    	public User findUserById(String id) {
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "select id,username,password from user where id=?";
    		Object[] params = { id };
    		try {
    			User user = (User) runner.query(sql, new BeanHandler(User.class),
    					params);
    			sql = "select r.id,r.name,r.description from role r,user_role ur where r.id=ur.role_id and ur.user_id=?";
    			params = new Object[] { id };
    			List<Role> list = (List<Role>) runner.query(sql,
    					new BeanListHandler(Role.class), params);
    			Set<Role> set = new HashSet<Role>();
    			set.addAll(list);
    			user.setRoles(set);
    			return user;
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    	}
    
    	// 查找所有用户
    	@SuppressWarnings("unchecked")
    	public List<User> findAllUser() {
    		List<User> list = null;
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "select id,username,password from user";
    		try {
    			list = (List<User>) runner.query(sql, new BeanListHandler(
    					User.class));
    			sql = "select r.id,r.name,r.description from role r,user_role ur where r.id=ur.role_id and ur.user_id=?";
    			for (User user : list) {
    				Object[] params = new Object[] { user.getId() };
    				Set<Role> set = new HashSet<Role>();
    				set.addAll((List<Role>) runner.query(sql, new BeanListHandler(
    						Role.class), params));
    				user.setRoles(set);
    			}
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    		return list;
    	}
    
    	// 用户登录
    	@SuppressWarnings("unchecked")
    	public User login(String username, String password) {
    		User user = null;
    		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
    		String sql = "select id,username,password from user where username=? and password=?";
    		Object[] params = { username, password };
    		try {
    			user = (User) runner
    					.query(sql, new BeanHandler(User.class), params);
    			if (user != null) {
    				sql = "select r.id,r.name,r.description from role r, user_role ur where r.id=ur.role_id and ur.user_id=?";
    				params = new Object[] { user.getId() };
    				Set<Role> set = new HashSet<Role>();
    				set.addAll((List<Role>) runner.query(sql, new BeanListHandler(
    						Role.class), params));
    				user.setRoles(set);
    			}
    		} catch (SQLException e) {
    			throw new RuntimeException(e);
    		}
    		return user;
    	}
    }
    
    package cn.dk.factory;
    
    import java.io.IOException;
    import java.io.InputStream;
    import java.util.Properties;
    
    public class DaoFactory {
    
    	private static DaoFactory factory = new DaoFactory();
    	private static Properties properties;
    
    	private DaoFactory() {
    		InputStream inputStream = DaoFactory.class.getClassLoader()
    				.getResourceAsStream("daoFactory.properties");
    		try {
    			properties = new Properties();
    			properties.load(inputStream);
    		} catch (IOException e) {
    			throw new ExceptionInInitializerError(e);
    		}
    	}
    
    	public static DaoFactory newInstance() {
    		return factory;
    	}
    
    	@SuppressWarnings("unchecked")
    	public <T> T getDao(Class<T> clazz) {
    		String simpleName = clazz.getSimpleName();
    		String className = properties.getProperty(simpleName);
    		try {
    			return (T) Class.forName(className).newInstance();
    		} catch (Exception e) {
    			throw new RuntimeException(e);
    		}
    	}
    }
    
    package cn.dk.service;
    
    import java.io.BufferedReader;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    
    public class InitialService {
    
    	// 系统初始化
    	public String initial() throws Exception {
    		String filePath = InitialService.class.getClassLoader().getResource(
    				"init.sql").getPath();
    		filePath = filePath.substring(1);
    		String command = "cmd /c mysql -uroot -proot<" + filePath;
    		Process process = Runtime.getRuntime().exec(command);
    		InputStream errorStream = process.getErrorStream();
    		BufferedReader br = new BufferedReader(new InputStreamReader(
    				errorStream));
    		char[] chars = new char[1024];
    		int len = 0;
    		StringBuffer sb = new StringBuffer();
    		while ((len = br.read(chars)) != -1) {
    			sb.append(chars, 0, len);
    		}
    		if (sb.length() > 0)
    			return sb.insert(0, "初始化失败,原因:").toString();
    		else
    			return "初始化成功";
    	}
    }
    
    package cn.dk.service;
    
    import java.util.ArrayList;
    import java.util.HashSet;
    import java.util.List;
    import java.util.Set;
    import java.util.UUID;
    import cn.dk.dao.IPermissionDao;
    import cn.dk.dao.IResourceDao;
    import cn.dk.dao.IRoleDao;
    import cn.dk.dao.IUserDao;
    import cn.dk.domain.Permission;
    import cn.dk.domain.Resource;
    import cn.dk.domain.Role;
    import cn.dk.domain.User;
    import cn.dk.factory.DaoFactory;
    
    public class Service {
    
    	private DaoFactory factory = DaoFactory.newInstance();
    	private IPermissionDao permissionDao = factory.getDao(IPermissionDao.class);
    	private IResourceDao resourceDao = factory.getDao(IResourceDao.class);
    	private IRoleDao roleDao = factory.getDao(IRoleDao.class);
    	private IUserDao userDao = factory.getDao(IUserDao.class);
    
    	// 权限
    	public void insertPermission(Permission permission) {
    		permission.setId(UUID.randomUUID().toString());
    		permissionDao.insertPermission(permission);
    	}
    
    	public void deletePermission(String id) {
    		permissionDao.deletePermission(id);
    	}
    
    	public Permission findPermissionById(String id) {
    		return permissionDao.findPermissionById(id);
    	}
    
    	public List<Permission> findAllPermission() {
    		return permissionDao.findAllPermission();
    	}
    
    	// 资源
    	public void insertResource(Resource resource, String permissionId) {
    		Permission permission = findPermissionById(permissionId);
    		resource.setPermission(permission);
    		resource.setId(UUID.randomUUID().toString());
    		resourceDao.insertResource(resource);
    	}
    
    	public void updateResource(Resource resource, String permissionId) {
    		Permission permission = findPermissionById(permissionId);
    		resource.setPermission(permission);
    		resourceDao.updateResource(resource);
    	}
    
    	public List<Resource> findAllResource() {
    		return resourceDao.findAllResource();
    	}
    
    	public Resource findResourceByURI(String uri) {
    		return resourceDao.findResourceByURI(uri);
    	}
    
    	public Resource findResourceById(String id) {
    		return resourceDao.findResourceById(id);
    	}
    
    	public void deleteResource(String id) {
    		resourceDao.deleteResource(id);
    	}
    
    	// 角色
    	public void insertRole(Role role, String[] permissionId) {
    		Set<Permission> permissions = new HashSet<Permission>();
    		for (int i = 0; permissionId != null && i < permissionId.length; i++) {
    			Permission permission = findPermissionById(permissionId[i]);
    			permissions.add(permission);
    		}
    		role.setPermissions(permissions);
    		role.setId(UUID.randomUUID().toString());
    		roleDao.insertRole(role);
    	}
    
    	public void updateRole(Role role, String[] permissionId) {
    		Set<Permission> permissions = new HashSet<Permission>();
    		for (int i = 0; permissionId != null && i < permissionId.length; i++) {
    			Permission permission = findPermissionById(permissionId[i]);
    			permissions.add(permission);
    		}
    		role.setPermissions(permissions);
    		roleDao.updateRole(role);
    	}
    
    	public void deleteRole(String id) {
    		roleDao.deleteRole(id);
    	}
    
    	public Role findRoleById(String id) {
    		return roleDao.findRoleById(id);
    	}
    
    	public List<Role> fineAllRole() {
    		return roleDao.fineAllRole();
    	}
    
    	// 用户
    	public void insertUser(User user, String[] roleId) {
    		Set<Role> roles = new HashSet<Role>();
    		for (int i = 0; roleId != null && i < roleId.length; i++) {
    			Role role = roleDao.findRoleById(roleId[i]);
    			roles.add(role);
    		}
    		user.setRoles(roles);
    		user.setId(UUID.randomUUID().toString());
    		userDao.insertUser(user);
    	}
    
    	public void updateUser(User user, String[] roleId) {
    		user.setUsername(findUserById(user.getId()).getUsername());
    		user.setPassword(findUserById(user.getId()).getPassword());
    		Set<Role> roles = new HashSet<Role>();
    		for (int i = 0; roleId != null && i < roleId.length; i++) {
    			Role role = roleDao.findRoleById(roleId[i]);
    			roles.add(role);
    		}
    		user.setRoles(roles);
    		userDao.updateUser(user);
    	}
    
    	public void deleteUser(String id) {
    		userDao.deleteUser(id);
    	}
    
    	public User findUserById(String id) {
    		return userDao.findUserById(id);
    	}
    
    	public List<User> findAllUser() {
    		return userDao.findAllUser();
    	}
    
    	public User login(String username, String password) {
    		return userDao.login(username, password);
    	}
    
    	public List<Permission> getUserPermission(User user) {
    		List<Permission> list = new ArrayList<Permission>();
    		Set<Role> roles = user.getRoles();
    		for (Role role : roles) {
    			list.addAll(findRoleById(role.getId()).getPermissions());
    		}
    		return list;
    	}
    }
    
    package cn.dk.utils;
    
    import java.util.Map;
    import org.apache.commons.beanutils.BeanUtils;
    
    public class CopyBean {
    
    	public static void Copy(Object bean, Map<String, String> properties){
    		try {
    			BeanUtils.populate(bean, properties);
    		} catch (Exception e) {
    			throw new RuntimeException(e);
    		}
    	}
    }
    
    package cn.dk.utils;
    
    import com.mchange.v2.c3p0.ComboPooledDataSource;
    
    public class DBUtils {
    
    	private static ComboPooledDataSource source;
    
    	static {
    		source = new ComboPooledDataSource("mysql");
    	}
    
    	public static ComboPooledDataSource getDataSource() {
    		return source;
    	}
    }
    
    package cn.dk.web.manager;
    
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    @SuppressWarnings("serial")
    public class ManagerServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		request.getRequestDispatcher("/WEB-INF/manager/manager.jsp").forward(
    				request, response);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    }
    
    package cn.dk.web.manager;
    
    import java.io.IOException;
    import java.util.List;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import cn.dk.domain.Permission;
    import cn.dk.service.Service;
    import cn.dk.utils.CopyBean;
    
    @SuppressWarnings("serial")
    public class PermissionServlet extends HttpServlet {
    
    	private Service service = new Service();
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		String method = request.getParameter("method");
    		if (method.equals("showAllpermissoin"))
    			showAllpermissoin(request, response);
    		else if (method.equals("showInsertPermission"))
    			showInsertPermission(request, response);
    		else if (method.equals("insertPsermission"))
    			insertPsermission(request, response);
    		else if (method.equals("deletePermission"))
    			deletePermission(request, response);
    	}
    
    	private void deletePermission(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		String permissionId = request.getParameter("id");
    		try {
    			service.deletePermission(permissionId);
    			request.setAttribute("message", "删除权限成功");
    		} catch (RuntimeException e) {
    			request.setAttribute("message", "删除权限失败");
    		}
    		request.getRequestDispatcher("/WEB-INF/message/message.jsp").forward(
    				request, response);
    	}
    
    	@SuppressWarnings("unchecked")
    	private void insertPsermission(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		Permission permission = new Permission();
    		try {
    			CopyBean.Copy(permission, request.getParameterMap());
    			service.insertPermission(permission);
    			request.setAttribute("message", "添加权限成功");
    		} catch (RuntimeException e) {
    			request.setAttribute("message", "添加权限失败");
    		}
    		request.getRequestDispatcher("/WEB-INF/message/message.jsp").forward(
    				request, response);
    	}
    
    	private void showInsertPermission(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		request.getRequestDispatcher("/WEB-INF/manager/addPermission.jsp")
    				.forward(request, response);
    	}
    
    	private void showAllpermissoin(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		List<Permission> permission = service.findAllPermission();
    		request.setAttribute("permission", permission);
    		request.getRequestDispatcher("/WEB-INF/manager/permissionlist.jsp")
    				.forward(request, response);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    package cn.dk.web.manager;
    
    import java.io.IOException;
    import java.util.List;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import cn.dk.domain.Permission;
    import cn.dk.domain.Resource;
    import cn.dk.service.Service;
    import cn.dk.utils.CopyBean;
    
    @SuppressWarnings("serial")
    public class ResourceServlet extends HttpServlet {
    
    	private Service service = new Service();
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		String method = request.getParameter("method");
    		if (method.equals("showAllresource"))
    			showAllresource(request, response);
    		else if (method.equals("showInsertResource"))
    			showInsertResource(request, response);
    		else if (method.equals("insertResource"))
    			insertResource(request, response);
    		else if (method.equals("showUpdateResource"))
    			showUpdateResource(request, response);
    		else if (method.equals("updateResource"))
    			updateResource(request, response);
    		else if (method.equals("deleteResource"))
    			deleteResource(request, response);
    	}
    
    	private void deleteResource(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		String id = request.getParameter("id");
    		try {
    			service.deleteResource(id);
    			request.setAttribute("message", "删除资源成功");
    		} catch (RuntimeException e) {
    			request.setAttribute("message", "删除资源失败");
    		}
    		request.getRequestDispatcher("/WEB-INF/message/message.jsp").forward(
    				request, response);
    	}
    
    	@SuppressWarnings("unchecked")
    	private void updateResource(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		Resource resource = new Resource();
    		try {
    			CopyBean.Copy(resource, request.getParameterMap());
    			String permissionId = request.getParameter("pid");
    			service.updateResource(resource, permissionId);
    			request.setAttribute("message", "修改资源成功");
    		} catch (RuntimeException e) {
    			request.setAttribute("message", "修改资源失败,原因:" + e.getMessage());
    		}
    		request.getRequestDispatcher("/WEB-INF/message/message.jsp").forward(
    				request, response);
    	}
    
    	private void showUpdateResource(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		List<Permission> permission = service.findAllPermission();
    		String resourceId = request.getParameter("id");
    		Resource resource = service.findResourceById(resourceId);
    		request.setAttribute("permission", permission);
    		request.setAttribute("resource", resource);
    		request.getRequestDispatcher("/WEB-INF/manager/updateResource.jsp")
    				.forward(request, response);
    	}
    
    	@SuppressWarnings("unchecked")
    	private void insertResource(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		try {
    			Resource resource = new Resource();
    			CopyBean.Copy(resource, request.getParameterMap());
    			String permissionId = request.getParameter("pid");
    			service.insertResource(resource, permissionId);
    			request.setAttribute("message", "添加资源成功");
    		} catch (RuntimeException e) {
    			request.setAttribute("message", "添加资源失败");
    		}
    		request.getRequestDispatcher("/WEB-INF/message/message.jsp").forward(
    				request, response);
    	}
    
    	private void showInsertResource(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		List<Permission> permission = service.findAllPermission();
    		request.setAttribute("permission", permission);
    		request.getRequestDispatcher("/WEB-INF/manager/addResource.jsp")
    				.forward(request, response);
    	}
    
    	private void showAllresource(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		List<Resource> resources = service.findAllResource();
    		request.setAttribute("resources", resources);
    		request.getRequestDispatcher("/WEB-INF/manager/resourcelist.jsp")
    				.forward(request, response);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    package cn.dk.web.manager;
    
    import java.io.IOException;
    import java.util.List;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import cn.dk.domain.Permission;
    import cn.dk.domain.Role;
    import cn.dk.service.Service;
    import cn.dk.utils.CopyBean;
    
    @SuppressWarnings("serial")
    public class RoleServlet extends HttpServlet {
    
    	private Service service = new Service();
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		String method = request.getParameter("method");
    		if (method.equals("showAllRole"))
    			showAllRole(request, response);
    		else if (method.equals("showInsertRole"))
    			showInsertRole(request, response);
    		else if (method.equals("insertRole"))
    			insertRole(request, response);
    		else if (method.equals("showUpdateRole"))
    			showUpdateRole(request, response);
    		else if (method.equals("updateRole"))
    			updateRole(request, response);
    		else if (method.equals("deleteRole"))
    			deleteRole(request, response);
    	}
    
    	private void deleteRole(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		String roleId = request.getParameter("id");
    		try {
    			service.deleteRole(roleId);
    			request.setAttribute("message", "删除角色成功");
    		} catch (RuntimeException e) {
    			request.setAttribute("message", "删除角色失败,原因:" + e.getMessage());
    		}
    		request.getRequestDispatcher("/WEB-INF/message/message.jsp").forward(
    				request, response);
    	}
    
    	@SuppressWarnings("unchecked")
    	private void updateRole(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		Role role = new Role();
    		try {
    			CopyBean.Copy(role, request.getParameterMap());
    			String[] permissionId = request.getParameterValues("pid");
    			service.updateRole(role, permissionId);
    			request.setAttribute("message", "修改角色成功");
    		} catch (RuntimeException e) {
    			request.setAttribute("message", "修改角色失败,原因:" + e.getMessage());
    		}
    		request.getRequestDispatcher("/WEB-INF/message/message.jsp").forward(
    				request, response);
    	}
    
    	private void showUpdateRole(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		String roleId = request.getParameter("id");
    		Role role = service.findRoleById(roleId);
    		List<Permission> permission = service.findAllPermission();
    		request.setAttribute("role", role);
    		request.setAttribute("permission", permission);
    		request.getRequestDispatcher("/WEB-INF/manager/updateRole.jsp")
    				.forward(request, response);
    	}
    
    	@SuppressWarnings("unchecked")
    	private void insertRole(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		Role role = new Role();
    		try {
    			CopyBean.Copy(role, request.getParameterMap());
    			service.insertRole(role, null);
    			request.setAttribute("message", "添加角色成功");
    		} catch (RuntimeException e) {
    			request.setAttribute("message", "添加角色失败,原因:" + e.getMessage());
    		}
    		request.getRequestDispatcher("/WEB-INF/message/message.jsp").forward(
    				request, response);
    	}
    
    	private void showInsertRole(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		request.getRequestDispatcher("/WEB-INF/manager/addRole.jsp").forward(
    				request, response);
    	}
    
    	private void showAllRole(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		List<Role> role = service.fineAllRole();
    		request.setAttribute("role", role);
    		request.getRequestDispatcher("/WEB-INF/manager/rolelist.jsp").forward(
    				request, response);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    }
    
    package cn.dk.web.manager;
    
    import java.io.IOException;
    import java.util.List;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import cn.dk.domain.Role;
    import cn.dk.domain.User;
    import cn.dk.service.Service;
    import cn.dk.utils.CopyBean;
    
    @SuppressWarnings("serial")
    public class UserServlet extends HttpServlet {
    
    	private Service service = new Service();
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		String method = request.getParameter("method");
    		if (method.equals("showAllUser"))
    			showAllUser(request, response);
    		else if (method.equals("showInsertUser"))
    			showInsertUser(request, response);
    		else if (method.equals("addUser"))
    			addUser(request, response);
    		else if (method.equals("showUpdateUser"))
    			showUpdateUser(request, response);
    		else if (method.equals("updateUser"))
    			updateUser(request, response);
    		else if (method.equals("deleteUser"))
    			deleteUser(request, response);
    	}
    
    	private void deleteUser(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		String userId = request.getParameter("id");
    		try {
    			service.deleteUser(userId);
    			request.setAttribute("message", "删除用户成功");
    		} catch (RuntimeException e) {
    			request.setAttribute("message", "删除用户失败");
    		}
    		request.getRequestDispatcher("/WEB-INF/message/message.jsp").forward(
    				request, response);
    	}
    
    	@SuppressWarnings("unchecked")
    	private void updateUser(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		User user = new User();
    		try {
    			CopyBean.Copy(user, request.getParameterMap());
    			String[] roleId = request.getParameterValues("rid");
    			service.updateUser(user, roleId);
    			request.setAttribute("message", "修改用户成功");
    		} catch (RuntimeException e) {
    			request.setAttribute("message", "修改用户失败,原因:" + e.getMessage());
    		}
    		request.getRequestDispatcher("/WEB-INF/message/message.jsp").forward(
    				request, response);
    	}
    
    	private void showUpdateUser(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		String userId = request.getParameter("id");
    		User user = service.findUserById(userId);
    		List<Role> role = service.fineAllRole();
    		request.setAttribute("user", user);
    		request.setAttribute("role", role);
    		request.getRequestDispatcher("/WEB-INF/manager/updateUser.jsp")
    				.forward(request, response);
    	}
    
    	@SuppressWarnings("unchecked")
    	private void addUser(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		User user = new User();
    		try {
    			CopyBean.Copy(user, request.getParameterMap());
    			service.insertUser(user, null);
    			request.setAttribute("message", "添加用户成功");
    		} catch (RuntimeException e) {
    			request.setAttribute("message", "添加用户失败,原因:" + e.getMessage());
    		}
    		request.getRequestDispatcher("/WEB-INF/message/message.jsp").forward(
    				request, response);
    	}
    
    	private void showInsertUser(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		request.getRequestDispatcher("/WEB-INF/manager/addUser.jsp").forward(
    				request, response);
    	}
    
    	private void showAllUser(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    		List<User> user = service.findAllUser();
    		request.setAttribute("user", user);
    		request.getRequestDispatcher("/WEB-INF/manager/userlist.jsp").forward(
    				request, response);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    
    }
    
    package cn.dk.web;
    
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import cn.dk.service.InitialService;
    
    @SuppressWarnings("serial")
    public class InitialServlet extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		InitialService iniService = new InitialService();
    		String message = null;
    		try {
    			message = iniService.initial();
    			request.setAttribute("message", message);
    		} catch (Exception e) {
    			request.setAttribute("message", message);
    		}
    		request.getRequestDispatcher("/WEB-INF/message/message.jsp").forward(
    				request, response);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		doGet(request, response);
    	}
    }
    
    package cn.dk.web;
    
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import cn.dk.domain.User;
    import cn.dk.service.Service;
    
    @SuppressWarnings("serial")
    public class Welcome extends HttpServlet {
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		request.getRequestDispatcher("/login/login.jsp").forward(request,
    				response);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response)
    			throws ServletException, IOException {
    		Service service = new Service();
    		String username = request.getParameter("username");
    		String password = request.getParameter("password");
    		User user = service.login(username, password);
    		if (user != null) {
    			request.getSession().setAttribute("user", user);
    			response.sendRedirect(request.getContextPath() + "/index.jsp");
    		} else {
    			request.setAttribute("message", "用户名密码错误");
    			request.getRequestDispatcher("/WEB-INF/message/message.jsp")
    					.forward(request, response);
    		}
    	}
    }
    
    <%@ page language="java" pageEncoding="UTF-8"%>
    <%@taglib uri="http://www.opensymphony.com/sitemesh/decorator" prefix="sitemesh-decorator"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    	<head>
    		<title><sitemesh-decorator:title /></title>
    		
    		<style type="text/css">
    	   		body{
    	   			margin: 0px;
    	   			padding: 0px;
    	   			text-align: center;
    	   		}
    	   		#container{
    	   				 980px;
    	   				border: 1px solid gray;
    	   		}
    	   		#top{
    	   			border-bottom: 1px solid gray;
    	   		}
    	   		#left{
    	   			float: left;
    	   			 150px;
    	   			border-right: 1px solid gray;
    	   		}
    	   		#main{
    	   			float: left;
    	   			padding: 40px 0px 0px 40px;
    	   		}
      		 </style>
    	</head>
    
    	<body>
    		<br/><br/><br/>
    		<div id="container">
    	    	<div id="top">
    	    		<h2>中浩集团网站后台管理系统</h2>
    	    	</div>
    	    	<div id="left">
    	    		<br/><br/><br/>
    	    		<a href="${pageContext.request.contextPath }/servlet/manager/ResourceServlet?method=showAllresource">资源管理</a><br/><br/><br/>
    	    		<a href="${pageContext.request.contextPath }/servlet/manager/PermissionServlet?method=showAllpermissoin">权限管理</a><br/><br/><br/>
    	    		<a href="${pageContext.request.contextPath }/servlet/manager/RoleServlet?method=showAllRole">角色管理</a><br/><br/><br/>
    	    		<a href="${pageContext.request.contextPath }/servlet/manager/UserServlet?method=showAllUser">用户管理</a><br/><br/><br/>
    	    	</div>
    	    	<div id="main">
    	    		<sitemesh-decorator:body></sitemesh-decorator:body>
    	    	</div>
        	</div>
    	</body>
    </html>
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>登录页面</title>
      </head>
      
      <body>
        <form action="${pageContext.request.contextPath }/Welcome" method="post">
        	用户名:<input type="text" name="username"><br>
        	密码:<input type="password" name="password"><br>
        	<input type="submit" value="登录">
        </form>
      </body>
    </html>
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>添加权限</title>
      </head>
      
      <body>
        <form action="${pageContext.request.contextPath }/servlet/manager/PermissionServlet?method=insertPsermission" method="post">
        <table>
        	<tr>
        		<td>权限名称</td>
        		<td>
        			<input type="text" name="name">
        		</td>
        	</tr>
        	
        	<tr>
        		<td>权限描述</td>
        		<td>
        			<textarea rows="3" cols="50" name="description"></textarea>
        		</td>
        	</tr>
        	
        	<tr>
        		<td></td>
        		<td>
        			<input type="submit" value="添加权限">
        		</td>
        	</tr>
        </table>
        </form>
      </body>
    </html>
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>添加资额</title>
      </head>
      
      <body>
        <form action="${pageContext.request.contextPath }/servlet/manager/ResourceServlet?method=insertResource" method="post">
        <table>
        	<tr>
        		<td>资源uri</td>
        		<td>
        			<input type="text" name="uri">
        		</td>
        	</tr>
        	<tr>
        		<td>资源描述</td>
        		<td>
        			<textarea rows="3" cols="50" name="description"></textarea>
        		</td>
        	</tr>
        	<tr>
        		<td>资源控制权限</td>
        		<td>
        			<c:forEach var="p" items="${requestScope.permission}">
    					<input type="radio" name="pid" value="${p.id }">${p.name }  
        			</c:forEach>
        		</td>
        	</tr>
        	<tr>
        		<td></td>
        		<td>
        			<input type="submit" value="添加资源">
        		</td>
        	</tr>
        </table>
        </form>
      </body>
    </html>
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>添加角色</title>
      </head>
      
      <body>
        <form action="${pageContext.request.contextPath }/servlet/manager/RoleServlet?method=insertRole" method="post">
        <table>
        	<tr>
        		<td>角色名称</td>
        		<td>
        			<input type="text" name="name">
        		</td>
        	</tr>
        	<tr>
        		<td>角色描述</td>
        		<td>
        			<textarea rows="3" cols="50" name="description"></textarea>
        		</td>
        	</tr>
        	<tr>
        		<td></td>
        		<td>
        			<input type="submit" value="添加角色">
        		</td>
        	</tr>
        </table>
        </form>
      </body>
    </html>
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>添加用户</title>
      </head>
      
      <body>
         <form action="${pageContext.request.contextPath }/servlet/manager/UserServlet?method=addUser" method="post">
        <table>
        	<tr>
        		<td>用户名称</td>
        		<td>
        			<input type="text" name="username">
        		</td>
        	</tr>
        	<tr>
        		<td>用户密码</td>
        		<td>
        			<input type="password" name="password">
        		</td>
        	</tr>
        	<tr>
        		<td></td>
        		<td>
        			<input type="submit" value="添加用户">
        		</td>
        	</tr>
        </table>
        </form>
      </body>
    </html>
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>权限列表</title>
      </head>
      
      <body>
         <table width="90%">
        	<tr>
        		<td align="right">
        			<a href="${pageContext.request.contextPath }/servlet/manager/PermissionServlet?method=showInsertPermission">添加权限</a>
        		</td>
        	</tr>
        </table>
        
        <table frame="border" width="90%">
        	<tr>
        		<td>权限名称</td>
        		<td>权限描述</td>
        		<td>操作</td>
        	</tr>
        	
        	<c:forEach var="p" items="${requestScope.permission}">
        		<tr>
    	    		<td>${p.name }</td>
    	    		<td>${p.description }</td>
    	    		<td>
    	    			<a href="${pageContext.request.contextPath }/servlet/manager/PermissionServlet?method=deletePermission&id=${p.id }">删除</a>
    	    		</td>
        		</tr>
        	</c:forEach>
        
        </table>
      </body>
    </html>
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>资源管理</title>
      </head>
      
      <body>
         <table width="90%">
        	<tr>
        		<td align="right">
        			<a href="${pageContext.request.contextPath }/servlet/manager/ResourceServlet?method=showInsertResource">添加资源</a>
        		</td>
        	</tr>
        </table>
        <table frame="border" width="90%">
        	<tr>
        		<td>资源URI</td>
        		<td>资源描述</td>
        		<td>管理资源的权限</td>
        		<td>操作</td>
        	</tr>
        	<c:forEach var="resource" items="${requestScope.resources}">
        		<tr>
    	    		<td>${resource.uri }</td>
    	    		<td>${resource.description }</td>
    	    		<td>${resource.permission.name }</td>
    	    		<td>
    	    			<a href="${pageContext.request.contextPath }/servlet/manager/ResourceServlet?method=showUpdateResource&id=${resource.id }">分配权限</a>
    	    			<a href="${pageContext.request.contextPath }/servlet/manager/ResourceServlet?method=deleteResource&id=${resource.id }">删除</a>
    	    		</td>
        		</tr>
        	</c:forEach>
        </table>
      </body>
    </html>
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>My JSP 'rolelist.jsp' starting page</title>
      </head>
      
      <body>
          <table width="90%">
        	<tr>
        		<td align="right">
        			<a href="${pageContext.request.contextPath }/servlet/manager/RoleServlet?method=showInsertRole">添加角色</a>
        		</td>
        	</tr>
        </table>
        
        <table frame="border" width="90%">
        	<tr>
        		<td>角色名称</td>
        		<td>角色描述</td>
        		<td>角色拥有的权限</td>
        		<td>操作</td>
        	</tr>
        	<c:forEach var="r" items="${role}">
        		<tr>
    	    		<td>${r.name }</td>
    	    		<td>${r.description }</td>
    	    		<td>
    	    			<c:forEach var="p" items="${r.permissions}">
    	    				${p.name }
    	    			</c:forEach>
    	    		</td>
    	    		<td>
    	    			<a href="${pageContext.request.contextPath }/servlet/manager/RoleServlet?method=showUpdateRole&id=${r.id }">分配权限</a>
    	    			<a href="${pageContext.request.contextPath }/servlet/manager/RoleServlet?method=deleteRole&id=${r.id }">删除</a>
    	    		</td>
        		</tr>
        	</c:forEach>
        
        </table>
      </body>
    </html>
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>分配权限</title>
      </head>
      
      <body>
        <form action="${pageContext.request.contextPath }/servlet/manager/ResourceServlet?method=updateResource" method="post">
        <table>
        	<tr>
        		<td>资源uri</td>
        		<td>
        			<input type="text" name="uri" value="${requestScope.resource.uri }">
        		</td>
        	</tr>
        	<tr>
        		<td>资源描述</td>
        		<td>
        			<textarea rows="3" cols="50" name="description">${requestScope.resource.description }</textarea>
        		</td>
        	</tr>
        	<tr>
        		<td>资源控制权限</td>
        		<td>
        			<c:forEach var="p" items="${requestScope.permission}">
    					<input type="radio" name="pid" value="${p.id }" ${p.id==requestScope.resource.permission.id?'checked':'' }>${p.name } 
        			</c:forEach>
        		</td>
        	</tr>
        	<tr>
        		<td><input type="hidden" value="${requestScope.resource.id }" name="id"></td>
        		<td>
        			<input type="submit" value="添加资源">
        		</td>
        	</tr>
        </table>
        </form>
      </body>
    </html>
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>分配权限</title>
      </head>
      
      <body>
         <form action="${pageContext.request.contextPath }/servlet/manager/RoleServlet?method=updateRole" method="post">
        <input type="hidden" name="id" value="${requestScope.role.id }">
        <input type="hidden" name="name" value="${requestScope.role.name }">
        <input type="hidden" name="description" value="${requestScope.role.description }">
        <table frame="border" width="80%">
        	<tr>
        		<td>角色名称</td>
        		<td>${requestScope.role.name }</td>
        	</tr>
        	
        	<tr>
        		<td>角色描述</td>
        		<td>${requestScope.role.description }</td>
        	</tr>
        	
        	<tr>
        		<td>拥有的权限</td>
        		<td>
        			<c:forEach var="p" items="${requestScope.permission}">
        				<c:forEach var="rp" items="${requestScope.role.permissions}">
        					<c:if test="${p.id==rp.id}"><c:set var="choice" value="true" /></c:if>
        				</c:forEach>
        				<input type="checkbox" value="${p.id }" name="pid" ${choice=='true'?'checked':'' } />${p.name }
        				<c:remove var="choice" />
        			</c:forEach>
        		</td>
        	</tr>
        	<tr>
        		<td></td>
        		<td><input type="submit" value="更新角色"></td>
        	</tr>
        </table>
        </form>
      </body>
    </html>
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
    	<head>
    		<title>分配角色</title>
    	</head>
    
    	<body>
    		<form action="${pageContext.request.contextPath }/servlet/manager/UserServlet?method=updateUser" method="post">
    			<input type="hidden" name="id" value="${requestScope.user.id }" >
    			<table frame="border" width="80%">
    				<tr>
    					<td>用户名称</td>
    					<td>${requestScope.user.username }</td>
    				</tr>
    				<tr>
    					<td>角色信息</td>
    					<td>
    						<c:forEach var="r" items="${requestScope.role}">
    							<c:forEach var="ur" items="${requestScope.user.roles}">
    								<c:if test="${r.id==ur.id}"><c:set var="choice" value="true" /></c:if>
    							</c:forEach>
    							<input type="checkbox" value="${r.id }" name="rid" ${choice=='true'?'checked':'' } />${r.name }
    							<c:remove var="choice" />
    						</c:forEach>
    					</td>
    				</tr>
    				<tr>
    					<td></td>
    					<td><input type="submit" value="更新用户"></td>
    				</tr>
    			</table>
    		</form>
    	</body>
    </html>
    
    <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
    <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
    <html>
      <head>
        <title>用户列表</title>
      </head>
      
      <body>
         <table width="90%">
        	<tr>
        		<td align="right">
        			<a href="${pageContext.request.contextPath }/servlet/manager/UserServlet?method=showInsertUser">添加用户</a>
        		</td>
        	</tr>
        </table>
        
        <table frame="border" width="90%">
        	<tr>
        		<td>用户名称</td>
        		<td>用户拥有的角色</td>
        		<td>操作</td>
        	</tr>
        	<c:forEach var="u" items="${requestScope.user}">
        		<tr>
    	    		<td>${u.username }</td>
    	    		<td>
    	    			<c:forEach var="r" items="${u.roles}">
    	    				${r.name }
    	    			</c:forEach>
    	    		</td>
    	    		<td>
    	    			<a href="${pageContext.request.contextPath }/servlet/manager/UserServlet?method=showUpdateUser&id=${u.id }">分配角色</a>
    	    			<a href="${pageContext.request.contextPath }/servlet/manager/UserServlet?method=deleteUser&id=${u.id }">删除</a>
    	    		</td>
        		</tr>
        	</c:forEach>
        </table>
      </body>
    </html>
    
    package cn.dk.filter;
    
    import java.io.IOException;
    import java.lang.reflect.InvocationHandler;
    import java.lang.reflect.Method;
    import java.lang.reflect.Proxy;
    import java.util.HashMap;
    import java.util.Map;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    public class CharacterFilter implements Filter {
    
    	public void destroy() {
    	}
    
    	public void doFilter(ServletRequest r, ServletResponse re, FilterChain chain)
    			throws IOException, ServletException {
    		final HttpServletRequest request = (HttpServletRequest) r;
    		HttpServletResponse response = (HttpServletResponse) re;
    		response.setCharacterEncoding("utf-8");
    		chain.doFilter((ServletRequest) Proxy.newProxyInstance(
    				CharacterFilter.class.getClassLoader(), request.getClass()
    						.getInterfaces(), new InvocationHandler() {
    					@SuppressWarnings("unchecked")
    					public Object invoke(Object proxy, Method method,
    							Object[] args) throws Throwable {
    						if (method.getName().equals("getParameter")) {
    							String value = (String) method
    									.invoke(request, args);
    							String newValue = new String(value
    									.getBytes("iso8859-1"), "utf-8");
    							return newValue;
    						} else if (method.getName().equals("getParameterMap")) {
    							Map<String, String[]> values = (Map<String, String[]>) method
    									.invoke(request, args);
    							Map<String, String[]> newValues = new HashMap<String, String[]>();
    							for (Map.Entry<String, String[]> entry : values
    									.entrySet()) {
    								String[] value = entry.getValue();
    								String[] newValue = new String[value.length];
    								for (int i = 0; i < value.length; i++) {
    									newValue[i] = new String(value[i]
    											.getBytes("iso8859-1"), "utf-8");
    								}
    								newValues.put(entry.getKey(), newValue);
    							}
    							return newValues;
    						} else if (method.getName()
    								.equals("getParameterValues")) {
    							String[] values = (String[]) method.invoke(request,
    									args);
    							if (values == null)
    								return null;
    							String[] newValues = new String[values.length];
    							for (int i = 0; i < values.length; i++) {
    								newValues[i] = new String(values[i]
    										.getBytes("iso8859-1"), "utf-8");
    							}
    							return newValues;
    						}
    						return method.invoke(request, args);
    					}
    				}), response);
    	}
    
    	public void init(FilterConfig filterConfig) throws ServletException {
    	}
    }
    
    package cn.dk.filter;
    
    import java.io.IOException;
    import java.util.List;
    import javax.servlet.Filter;
    import javax.servlet.FilterChain;
    import javax.servlet.FilterConfig;
    import javax.servlet.ServletException;
    import javax.servlet.ServletRequest;
    import javax.servlet.ServletResponse;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import cn.dk.domain.Permission;
    import cn.dk.domain.Resource;
    import cn.dk.domain.User;
    import cn.dk.service.Service;
    
    public class PermissionFilter implements Filter {
    
    	public void destroy() {
    	}
    
    	public void doFilter(ServletRequest r, ServletResponse re, FilterChain chain)
    			throws IOException, ServletException {
    
    		HttpServletRequest request = (HttpServletRequest) r;
    		HttpServletResponse response = (HttpServletResponse) re;
    		Service service = new Service();
    
    		// 判断要访问的资源是否需要权限
    		String requestURI = request.getRequestURI();
    		requestURI = requestURI.substring(1);
    		Resource resource = service.findResourceByURI(requestURI);
    		// 如果不需要权限放行
    		if (resource == null) {
    			chain.doFilter(request, response);
    			return;
    		}
    		Permission permission = resource.getPermission();
    		// 如果需要权限验证用户是否登陆
    		Object attribute = request.getSession().getAttribute("user");
    		// 如果没有登录则跳转登录页面
    		if (attribute == null) {
    			request.getRequestDispatcher("/login/login.jsp").forward(request,
    					response);
    			return;
    		}
    		// 如果已经登录获取用户权限
    		User user = (User) attribute;
    		List<Permission> userPermission = service.getUserPermission(user);
    		// 如果有权访问则放行
    		if (userPermission.contains(permission)) {
    			chain.doFilter(request, response);
    			return;
    		}
    		// 如果没权访问则跳转消息显示页面
    		request.setAttribute("message", "对不起您没有权限");
    		request.getRequestDispatcher("/WEB-INF/message/message.jsp").forward(
    				request, response);
    	}
    
    	public void init(FilterConfig filterConfig) throws ServletException {
    	}
    }
    






  • 相关阅读:
    升级到`Google-Mobile-Ads-SDK(->7.68)`,导出Unity工程产生的几个BUG以及解决办法
    unity中Asset Store下载的资源保存位置
    Maven打包报错 No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
    C# ISharpZipLib 压缩/解压缩zip文件
    jarsigner.exe 命令行出现乱码的解决办法
    SwiftUI 结构体自动生成可编辑界面
    .Net Mvc ActionFilterAttribute的OnActionExecuted中获取请求参数信息
    .netcore Attribute特性使用 TypeFilter传参
    vue router.app.$store undefined
    js 判断点击是否是某个div下的dom
  • 原文地址:https://www.cnblogs.com/cn-chy-com/p/7900488.html
Copyright © 2020-2023  润新知