首先登陆位置:
public void login()
{
String loginAccount = ((String[])ActionContext.getContext().getParameters().get("loginAccount"))[0];
User user = userService.getByAccount(loginAccount);
ActionContext.getContext().getSession().put("login_user",user);
Role role = user.getRole();
List<Right> rights = rightService.getRightFunctionByRole(role.getRoleId());
Map<String,String> rightMap = new HashMap<String,String>();
for(Right right : rights)
{
rightMap.put(right.getFunction(), right.getFunction());
}
ActionContext.getContext().getSession().put("rightMap", rightMap);
try
{
if(user.getRole().getRoleName().indexOf("管理员") >= 0)
{
getResponse().getWriter().write("0");
}
else
{
getResponse().getWriter().write("7");
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
设置getRightsByRole方法(如果LAZY设置成 lazy="true")
public List<Right> getRightsByRole(int roleId)
{
QueryHelper queryHelper = new QueryHelper(Role.class, "r");
queryHelper.addCondition("roleId = ?", roleId);
queryHelper.addOrderProperty("roleId", true);
List<Object> parameters = queryHelper.getParameters();
Query listQuery = getSession().createQuery(queryHelper.getListQueryHql());
for(int i =0; i<parameters.size();i++)
{
listQuery.setParameter(i, parameters.get(i));
}
List<Role> roleList = listQuery.list();
List<Right> rightList = new ArrayList<Right>();
if(0 != roleList.get(0).getRights().size())
{
for(Right right : roleList.get(0).getRights())
{
rightList.add(right);
}
return rightList;
}
return null;
}
设置过滤器
public class MyInterceptot extends AbstractInterceptor
{
private static final long serialVersionUID = 6645338921893814285L;
@SuppressWarnings("unchecked")
@Override
public String intercept(ActionInvocation invocation) throws Exception
{
ActionContext actionContext = invocation.getInvocationContext();
ServletContext context = (ServletContext) actionContext.get(StrutsStatics.SERVLET_CONTEXT);
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
UserService userService = (UserService)ctx.getBean("userServiceImpl");
String functionName = actionContext.getName();//获取访问的action及方法名
Map<String, Object> session = actionContext.getSession();
User user = (User) session.get("login_user");
System.out.println("访问路径:" + functionName);
Map<String, String> rightMap = (Map<String, String>)session.get("rightMap");
if(null != user)
{
if(null != rightMap.get(functionName) || "admin".equals(user.getLoginAccount()))
{
return invocation.invoke();
}
else
{
return "no_right";
}
}
else
{
return Action.LOGIN;
}
}
}