在这种情况下,我不确定您所说的“站点”是什么意思。
几点注意事项:
- 托管 bean 在定义它们的 Web 应用程序 (WAR) 之外永远不可用。
- FacesContext 对象实例最终由FacesServlet.service创建和处理,因此请求应该通过这个 servlet。在其他情况下尝试创建上下文可能会导致未定义的行为。
考虑到这一点,您可以创建一个这样的请求序列:
FacesServlet (mapping: /faces/*)
-> /faces/jsfPage.jsp (a JSP with JSF controls)
-> DispatchBean (calls ExternalContext.dispatch("/AnotherServlet")
-> AnotherServlet
jsfPage.jsp 包含:
<f:view>
<h:outputText value="#{dispatchBean.dispatch}" />
</f:view>
“dispatch”属性解析为 bean 方法“getDispatch”:
public String getDispatch() {
FacesContext context = FacesContext.getCurrentInstance();
try {
context.getExternalContext().dispatch("/FacesClientServlet");
} catch (IOException e) {
throw new FacesException(e);
}
return null;
}
哪个调度到这个 servlet:
public class FacesClientServlet extends javax.servlet.http.HttpServlet
implements javax.servlet.Servlet {
static final long serialVersionUID = 1L;
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
FacesContext context = FacesContext.getCurrentInstance();
ELContext elContext = context.getELContext();
ExpressionFactory expressionFactory = context.getApplication()
.getExpressionFactory();
ValueExpression expression = expressionFactory.createValueExpression(
elContext, "#{myBean.text}", Object.class);
Object value = expression.getValue(elContext);
ResponseWriter writer = context.getResponseWriter();
writer.write("" + value);
}
}
它从托管 bean“myBean”发出值:
public class MyBean {
private final String text = "Hello, World!";
public String getText() {
return text;
}
}
这一切都非常令人费解,我不会愿意做任何事情。
另一种可能会带来其后果的替代方法是创建自己的上下文,如下所示:
public class ContextServlet extends javax.servlet.http.HttpServlet implements
javax.servlet.Servlet {
static final long serialVersionUID = 1L;
private FacesContextFactory facesContextFactory;
private Lifecycle lifecycle;
@Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
LifecycleFactory lifecycleFactory = (LifecycleFactory) FactoryFinder
.getFactory(FactoryFinder.LIFECYCLE_FACTORY);
facesContextFactory = (FacesContextFactory) FactoryFinder
.getFactory(FactoryFinder.FACES_CONTEXT_FACTORY);
lifecycle = lifecycleFactory
.getLifecycle(LifecycleFactory.DEFAULT_LIFECYCLE);
}
@Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
FacesContext context = facesContextFactory.getFacesContext(
getServletContext(), request, response, lifecycle);
try {
ELContext elContext = context.getELContext();
ExpressionFactory expressionFactory = context.getApplication()
.getExpressionFactory();
ValueExpression expression = expressionFactory
.createValueExpression(elContext, "#{myBean.text}",
Object.class);
Object value = expression.getValue(elContext);
PrintWriter pw = response.getWriter();
try {
pw.write("" + value);
} finally {
pw.close();
}
} finally {
context.release();
}
}
}
同样,如果可能的话,我会避免这种方法。