歡迎您光臨本站 註冊首頁

Struts2的interceptor實現許可權管理

←手機掃碼閱讀     火星人 @ 2014-03-09 , reply:0

這是以前寫過的一個利用struts2的interceptor進行許可權管理的筆記,以前是放電腦上的,今天偶然看到了,就貼出來,希望能對有需要的人有點幫助,同時自己以後需要看的時候也會更加方便點!
說明一點:這個interceptor裡面的代碼是根據我特定的項目寫的,所以請有需要的人不要盲目的照搬!
自己寫一個interceptor,該interceptor繼承interceptor介面,實現其中的intercept方法;然後在struts.xml
中進行配置,並把該interceptor置於默認的interceptor中,注意,這裡在設置默認的intercept的時候
一定要加上原來的intercept,否則原來的就不可以用了,就不能用struts2了,具體來說是這樣:
Xml代碼
<interceptors>
<interceptor name="authentication" class="com.tiantian.tiantian.web.interceptor.AuthenticationInterceptor"></interceptor>
<interceptor-stack name="myInterceptorStack">
<interceptor-ref name="authentication"></interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="myInterceptorStack"/>
Java代碼
@Override
public String intercept(ActionInvocation invoke) throws Exception {
// TODO Auto-generated method stub
HttpSession session = ServletActionContext.getRequest().getSession();
ApplicationContext context = Util.getContext(ServletActionContext.getServletContext());
PriorityService priorityService = context.getBean(PriorityService.class);
String actionName = invoke.getProxy().getActionName();
String methodName = invoke.getProxy().getMethod();
if ("execute".equals(methodName))
methodName = "index";
int index = actionName.indexOf("/");
String name = actionName.substring(0, index);
Priority priority = priorityService.find(name, methodName);
Object obj = session.getAttribute("user");
if (obj != null) {
User currentUser = (User) obj;
ModuleService moduleService = context.getBean(ModuleService.class);
Module module = moduleService.findByUrl(name "/" methodName);
if (module != null) {
SystemDiaryService sdService = context.getBean(SystemDiaryService.class);
SystemDiary diary = new SystemDiary();
diary.setOperator(currentUser);
diary.setOperateModule(module.getName());
sdService.add(diary);
}
if (priority != null) {
boolean hasPermission = currentUser.hasPermission(priority);
if (!hasPermission) {
return "forbidden";
}


}
}
//
System.out.println("name = " name "**actionName = " actionName "*methodName = " methodName);
String result = invoke.invoke();
return result;
} ModuleService moduleService = context.getBean(ModuleService.class);Module module = moduleService.findByUrl(name "/" methodName);if (module != null) { SystemDiaryService sdService = context.getBean(SystemDiaryService.class);
SystemDiary diary = new SystemDiary();
diary.setOperator(currentUser);
diary.setOperateModule(module.getName());
sdService.add(diary);
}
if (priority != null) {
boolean hasPermission = currentUser.hasPermission(priority);
if (!hasPermission) {
return "forbidden";
}
}
}
//
System.out.println("name = " name "**actionName = " actionName "*methodName = " methodName);
String result = invoke.invoke();
return result;
}();
return result;
} result; }


[火星人 ] Struts2的interceptor實現許可權管理已經有625次圍觀

http://coctec.com/docs/java/show-post-60015.html