关于Spring Portlet开发中的HandlerInterceptor


在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上。

  • 1
  • 2
  • 下一页

相关内容