在Spring Portlet開發中,我們可以用HandlerInterceptor 來實現對於portlet的攔截,主要的需求場景比如授權處理。它可以讓我們來自定義處理器執行鏈。
其實很類似Web開發中的Filter,但是不同的在於Filter是Servlet范疇的概念,它可以用來操作ServletRequest 和ServletResponse,並且配置在web.xml中,而Portlet HandlerInterceptor是Portlet范疇的概念,它可以用來操作PortletRequest和PortletResponse,並且配置在Spring應用上下文中。
在HandlerInterceptor中定義了若干主要方法:具體參見
為了讓我們的應用使用HandlerInterceptor,一個常見的設計模式是使用Adaptor模式,讓我們的自定義HandlerInterceptor類繼承自HandlerInterceptorAdaptor類,然後進行覆寫。 下面是個例子.
例子:
a.需求,我們需要在Portlet的任何頁面上都可以用到當前登錄的用戶的用戶名和所屬權限,那麼我們的可以開發一個HandlerInterceptor:
- /**
- *
- * This handler interceptor will intercept the request before/after the flow.
- * Since it is configured in envprovisioning-config.xml ,so it will intercept request to envprovision flow
- * We can have some pre/post handling work such as initialize the variables
- *@author cwang58
- *@created date: Feb 5, 2013
- */
- publicclass EnvProvisionHandlerInterceptor extends HandlerInterceptorAdapter {
- privatestaticfinal SimpleLogger LOGGER = new SimpleLogger(EnvProvisionHandlerInterceptor.class);
- /**
- * This method will pre handle before rendering the first page in the flow
- * Here it get the current logined user information from the ThemeDisplay
- * Then get the role that this user belongs to ,we make sure whether this user belongs to AER Admin-AERAdmin
- * if user belongs to this ,then set isAdministrator attribute to request scope so that it can be used in every page of this flow.
- */
- @Override
- publicboolean preHandleRender(RenderRequest request,
- RenderResponse response, Object handler) {
- User user = EnvProUtil.getUserObj(request);
- if(user == null){
- returnfalse;
- }
- String userName= user.getScreenName();
- LOGGER.debug("Login user name:"+userName);
- boolean isAdministrator = false;
- try{
- List<Role> roles = user.getRoles();
- for(int i= 0;i<roles.size();i++) {
- Role role =roles.get(i);
- if("AER Admin-AERAdmin".equals(role.getName()) || "Administrator".equals(role.getName())){
- isAdministrator=true;
- LOGGER.debug("Login user has role:"+role.getName());
- break;
- }
- }
- request.setAttribute("userId", userName);
- request.setAttribute("isAdministrator", isAdministrator);
- returntrue;
- }catch(SystemException ex){
- LOGGER.error("SystemException occurs when get current user role",ex);
- returnfalse;
- }
- }
- }
比如以上的例子中,我們從ThemeDisplay中獲取當前用戶的權限和用戶名,然後把它設置到RenderRequest的request scope上。