简介
权限系统处理登入信息:
- 通过帐号密码,获得对应的员工对象,存入session
- 从员工对象中得到该员工的权限表达式的集合,存入session.
准备工作
- 方法:得到权限表达式的集合的方法
creatEXPs(List<Role>)
- 放在PermissionUtil类中
public static Set<String> creatEXPs(List<Role> roles){
//对角色集合遍历,将每个权限表达式存入Set中
Set<String> EXPSet =new HashSet<>();
for (Role role : roles) {
for (Permission permission : role.getPermissions()) {
EXPSet.add(permission.getExpression());
}
}
return EXPSet;
}
- 方法:得到对应的员工对象
login(userName, password)
- 放在employee的dao中
public Employee login(String userName, String password) {
Session session = sessionFactory.getCurrentSession();
//进行查询
String hql="select e from Employee e where e.userName= :userName and e.password= :password";
Query query = session.createQuery(hql);
query.setParameter("userName", userName);
query.setParameter("password", password);
List<Employee> list = query.list();
//只有一个对象时候,才将其返回,其他情况都返回null
if(list.size()==1) {
return list.get(0);
}
return null;
}
处理登入信息
- Action类中的方法
@Autowired
private EmployeeService service;
//请求注入userName和password (省setter方法)
private String userName;
private String password;
//进行登入信息处理
public String login() throws Exception{
Employee employee = this.service.login(userName, password);
if(employee!=null) {
//获取该用户的权限表达式的集合
List<Role> roles = employee.getRoles();
Set<String> EXPs = PermissionUtil.creatEXPs(roles);
//将两者存入session
super.putSession("EXPS_IN_SESSION", EXPs);
super.putSession("EMPLOYEE_IN_SESSION", employee);
}
return "main";
}
- 由于是从数据库提取后存入session中,都是代理对象,不论有没有
openSessionInView
. - 在session中的代理对象,不能在jsp使用.但可以在java代码中使用
- 可以使用 对象.toString();方法 使其实例化,
- 使用
Hibernate.initialize(proxy);
方式,不能实例化内部的实例对象的属性.
登入拦截器
放行的条件:
- 处理登入信息的Action不需要拦截
- session中已经有员工对象,不用拦截
public class LoginInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = 1L;
@Override
public String intercept(ActionInvocation invocation) throws Exception {
//判断不需要拦截的条件
if(hasEmployee(invocation)||isExclude(invocation)) {
invocation.invoke();
}
return "login";
}
//注入不用连接的action集合
private List<String> excludeActions;
public void setExcludeActions(String str) {
String[] arr = str.split(",");
this.excludeActions = Arrays.asList(arr);
}
//判断是否有用户
private boolean hasEmployee(ActionInvocation invocation) {
if(ActionContext.getContext().getSession().get("EMPLOYEE_IN_SESSION")!=null) {
return true;
}
return false;
}
//判断当前action名是否需要拦截
//处理登入信息的action不需要连接
private boolean isExclude(ActionInvocation invocation) {
String actionName = invocation.getProxy().getActionName();
if(this.excludeActions.contains(actionName)) {
return true;
}
return false;
}
}
配置文件的部署
<interceptors>
<!--声明登入拦截器-->
<interceptor name="loginInterceptor" class="interceptor.LoginInterceptor">
<param name="excludeActions">login_login</param>
</interceptor>
<!--生成拦截器stack-->
<interceptor-stack name="myStack">
<interceptor-ref name="loginInterceptor"/>
<interceptor-ref name="paramsPrepareParamsStack"/>
</interceptor-stack>
</interceptors>
<!--使用拦截器-->
<default-interceptor-ref name="myStack"/>