JavaWebケース-アクセス制御

65960 ワード

一、機能紹介
各Webサイトは、アクセス権の制御に関連しています.各サイトのリソースは管理される必要があります.ユーザーは、リソースにアクセスする特定の権限を持っている場合にのみアクセスできます.そうしないと、アクセスを拒否します.
二、プロジェクト分析
私たちがウェブサイトのアクセス権の制御を実現するには、URIから着手しなければならない.サイトの各リソースは唯一のURIで記述されている.私たちは管理したいURIのために権限属性を追加し、ユーザーがリソースにアクセスするとき、まずユーザーが権限を持っているかどうかをチェックしなければならない.このプロジェクトはフィルタ技術を採用して権限ブロックを実現し、次のプロジェクトは注釈+ダイナミックエージェントを採用して権限ブロックを実現します.
ユーザーの各アクセス要求をブロックするフィルタを作成する必要があります.さらにURIに基づいて権限が必要か否かを判断する.これは比較的簡単で、重要なのは私たちがどのようにこの権限関係を説明するかであり、フィルタ技術を使用すると、データベースを使用して各権限、リソースなどを保存しなければなりません.1つのリソースには1つの権限が必要です.1つの権限は複数のロールに対応し、1つのロールは複数の権限を持ち、1つのユーザーは複数のロールを持ち、1つのロールは複数のユーザーによって参照されます.したがって、リソースと権限は一対一の関係であり、権限と役割は多対多の関係であり、役割とユーザーも多対多の関係である.したがって、データベースでは関係を保存するために6つのテーブルが必要です.
 
 、    	  、  、  、  

	     	------>		  		   
	  	    		  		   
	     			  		   
	
	  :
		String id	  
		String uri	  uri
		String description	  
		Permission permission	        
		
	  :
		String id	  
		String name	   
		String description     
		
	  :
		String id	  
		String name	   
		String description     
		Set set         
		
	  :
		String id	  
		String username	   
		String password	  
		Set 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コマンドでデータベースを初期化します.データベースの初期化情報をファイルに書き、ブラウザが初期化サーブレットにアクセスすると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();
	}

	private String id;
	private String name;
	private String description;
	private Set 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 getPermissions() {
		return permissions;
	}

	public void setPermissions(Set 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();
	}

	private String id;
	private String username;
	private String password;
	private Set 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 getRoles() {
		return roles;
	}

	public void setRoles(Set 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 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 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 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 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 findAllPermission() {
		List list = null;
		QueryRunner runer = new QueryRunner(DBUtils.getDataSource());
		String sql = "select id,name,description from permission";
		try {
			list = (List) 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 findAllResource() {
		List list = null;
		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
		String sql = "select id,uri,description from resource";
		try {
			list = (List) 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 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 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 set = new HashSet();
			set.addAll((List) runner.query(sql,
					new BeanListHandler(Permission.class), params));
			role.setPermissions(set);
			return role;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	//       
	@SuppressWarnings("unchecked")
	public List fineAllRole() {
		List list = null;
		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
		String sql = "select id,name,description from role";
		try {
			list = (List) 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 set = new HashSet();
				set.addAll((List) 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 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 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 list = (List) runner.query(sql,
					new BeanListHandler(Role.class), params);
			Set set = new HashSet();
			set.addAll(list);
			user.setRoles(set);
			return user;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	//       
	@SuppressWarnings("unchecked")
	public List findAllUser() {
		List list = null;
		QueryRunner runner = new QueryRunner(DBUtils.getDataSource());
		String sql = "select id,username,password from user";
		try {
			list = (List) 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 set = new HashSet();
				set.addAll((List) 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 set = new HashSet();
				set.addAll((List) 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 getDao(Class 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 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 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 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 permissions = new HashSet();
		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 permissions = new HashSet();
		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 fineAllRole() {
		return roleDao.fineAllRole();
	}

	//   
	public void insertUser(User user, String[] roleId) {
		Set roles = new HashSet();
		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 roles = new HashSet();
		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 findAllUser() {
		return userDao.findAllUser();
	}

	public User login(String username, String password) {
		return userDao.login(username, password);
	}

	public List getUserPermission(User user) {
		List list = new ArrayList();
		Set 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 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 = 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 = 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 = 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 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 = 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 = 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 = 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 = 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);
		}
	}
}





	
		<title/>
		
		
	

	
		






  
        
  
  
  
    

:




  
        
  
  
  
    
${p.name } 





  
        
  
  
  
     
${requestScope.role.name }
${requestScope.role.description }
${p.name }





	
		    
	

	
		
${requestScope.user.username }
${r.name }





  
        
  
  
  
     
ユーザーの
${u.username } ${r.name } の て
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 values = (Map) method
									.invoke(request, args);
							Map newValues = new HashMap();
							for (Map.Entry 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 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 {
	}
}