歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 關於Spring Portlet開發中的HandlerInterceptor

關於Spring Portlet開發中的HandlerInterceptor

日期:2017/3/1 9:59:55   编辑:Linux編程

在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:

  1. /**
  2. *
  3. * This handler interceptor will intercept the request before/after the flow.
  4. * Since it is configured in envprovisioning-config.xml ,so it will intercept request to envprovision flow
  5. * We can have some pre/post handling work such as initialize the variables
  6. *@author cwang58
  7. *@created date: Feb 5, 2013
  8. */
  9. publicclass EnvProvisionHandlerInterceptor extends HandlerInterceptorAdapter {
  10. privatestaticfinal SimpleLogger LOGGER = new SimpleLogger(EnvProvisionHandlerInterceptor.class);
  11. /**
  12. * This method will pre handle before rendering the first page in the flow
  13. * Here it get the current logined user information from the ThemeDisplay
  14. * Then get the role that this user belongs to ,we make sure whether this user belongs to AER Admin-AERAdmin
  15. * if user belongs to this ,then set isAdministrator attribute to request scope so that it can be used in every page of this flow.
  16. */
  17. @Override
  18. publicboolean preHandleRender(RenderRequest request,
  19. RenderResponse response, Object handler) {
  20. User user = EnvProUtil.getUserObj(request);
  21. if(user == null){
  22. returnfalse;
  23. }
  24. String userName= user.getScreenName();
  25. LOGGER.debug("Login user name:"+userName);
  26. boolean isAdministrator = false;
  27. try{
  28. List<Role> roles = user.getRoles();
  29. for(int i= 0;i<roles.size();i++) {
  30. Role role =roles.get(i);
  31. if("AER Admin-AERAdmin".equals(role.getName()) || "Administrator".equals(role.getName())){
  32. isAdministrator=true;
  33. LOGGER.debug("Login user has role:"+role.getName());
  34. break;
  35. }
  36. }
  37. request.setAttribute("userId", userName);
  38. request.setAttribute("isAdministrator", isAdministrator);
  39. returntrue;
  40. }catch(SystemException ex){
  41. LOGGER.error("SystemException occurs when get current user role",ex);
  42. returnfalse;
  43. }
  44. }
  45. }

比如以上的例子中,我們從ThemeDisplay中獲取當前用戶的權限和用戶名,然後把它設置到RenderRequest的request scope上。

Copyright © Linux教程網 All Rights Reserved