apache shiro整合struts2+spring+mybatis简单demo
先上一段shiro中获取数据源的代码,Demo见附件
public class AuthenticationRealm extends AuthorizingRealm {
private static final Logger log = LoggerFactory.getLogger(AuthenticationRealm.class);
@Autowired
private UserMapper userMapper;
@Autowired
private RoleMapper roleMapper;
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
UsernamePasswordToken upToken = (UsernamePasswordToken) token;
String username = upToken.getUsername();
// char[] password = upToken.getPassword();
// log.debug(String.valueOf(password));
// Null username is invalid
if (username == null) {
throw new AccountException("用户名不能为空!");
}
SimpleAuthenticationInfo info = null;
try{
String password = userMapper.getPassword(username);
if (password == null) {
throw new UnknownAccountException("No account found for user [" + username + "]");
}
// if(password.length>2){
// throw new AuthenticationException("More than one user row found for user [" + username + "]. Usernames must be unique.");
// }
info = new SimpleAuthenticationInfo(username, password.toCharArray(), getName());
} catch (RuntimeException e) {
final String message = "There was a SQL error while authenticating user [" + username + "]";
throw new AuthenticationException(message, e);
}
return info;
}
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) {
if (principals == null) {
throw new AuthorizationException("PrincipalCollection method argument cannot be null.");
}
String username = (String) getAvailablePrincipal(principals);
Set<String> roleNames = getRoleNameByUserName(username);
Set<String> permissions = new HashSet<String>();
for(String roleName : roleNames){
Role role = roleMapper.getRole(roleName);
for(Permission permission :role.getPermissions()){
permissions.add(permission.getModule()+":"+permission.getPrivilege());
}