为什么请求属性不从操作传播到 portlet 中的呈现?

Why are request attributes not propagated from action to render in portlet?

当我遇到以下概念时,我正在查看一些 Portlet 教程:

Due to the separated action and rendering model, the action request attributes will not be available in any of the view components that are included in the render phase (JSP, Servlet etc)

上述代码如下:

public class DateTimePortlet extends GenericPortlet {

public void doView(RenderRequest req, RenderResponse res) throws IOException, PortletException {        
    Object actionAttribute = req.getAttribute("datetime");
    res.getWriter().println("Date Time:" + (actionAttribute != null ? actionAttribute :"Unavailable"));
    res.getWriter().close();
}

public void processAction(ActionRequest req, ActionResponse res) throws PortletException {
    req.setAttribute("datetime",new Date());
}        
}

实际上我不明白为什么会发生这种情况.... render 方法不是总是在 action 方法之后调用吗? ....所以他们 运行 在同一范围内?

请求的属性只涉及请求本身。如果你想从Action Phase传递信息到Render Phase,你可以多次调用这个方法:

actionResponse.setRenderParameter("parameter-key","value");

在RenderPhase之后你可以得到信息:

renderRequest.getParameter("parameter-key");

还有其他方法可以做到这一点,例如使用请求会话或使用 Liferay Portlet 首选项。例如:

actionRequest.getPortletSession().setAttribute("session-key",value);
actionRequest.getPreferences().setValue("preferences-key","value");

及之后:

renderRequest.getPortletSession().getAttribute("session-key");
renderRequest.getPreferences().getValue("preferences-key","default-value");