jsf 的 HttpServletRequest
我有一个 jsp 站点,我在其中使用 request.getAttribute 获取属性。 我正在寻找一种在jsf中获取该属性的方法(在同一个tomcat中运行)。这是我在互联网上找到的:
HttpServletRequest requestObj = (HttpServletRequest)
FacesContext.getCurrentInstance().getExternalContext().getRequest();
String value = (String) requestObj.getAttribute("property");
但结果(值)保持为空。
它在第一种情况下有效但在第二种情况下无效的可能原因是什么?
i have a jsp site where i get an attribute using request.getAttribute.
i'm looking for a way to get that attribute in jsf (running in the same tomcat). this is what i found on the internet:
HttpServletRequest requestObj = (HttpServletRequest)
FacesContext.getCurrentInstance().getExternalContext().getRequest();
String value = (String) requestObj.getAttribute("property");
but the result (value) stays null.
what could possible reasons be that it works in the first case but not in the second?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果该属性不再存在,那么它只是涉及一个完全不同的请求。也许您已经发送了重定向,或者网络浏览器发送了新请求等。由于您没有详细说明问题中的功能要求,因此很难给出问题的真正答案。您刚刚发布了一些代码片段并说“为什么这不起作用?”。
无论如何,请求属性只要请求/响应本身就存在,并且它们不会保留在后续请求中。为此,您宁愿将其存储为会话属性,或者在重定向时作为请求参数传递。或者,当您已经使用 JSF 2.0 时,将其存储为视图作用域 bean 的属性也应该适用于随后从同一视图访问该 bean 的情况。
要了解有关 HTTP servlet 请求/响应生命周期的更多信息,我建议您自行阅读 这个答案。
与具体问题无关:每当您需要从 JSF 底层提取原始 Servlet API 时,那么您真的应该休息一下,三思而后行,看看您是否真的以正确的方式做事(阅读:无需回退到原始
javax.servlet
API)。例如,它不应该是一个完全值得的 JSF 托管 bean 吗?无论如何,请求属性也可以通过
ExternalContext#getRequestMap()
。无需使用原始 Servlet API。
If the attribute is not there anymore, then it simply concerns a completely different request. Probably you have sent a redirect, or the webbrowser has sent a new request, etc. The real answer to your problem is hard to give since you didn't elaborate anything about the functional requirement in your question. You just posted some code snippet and said "why doesn't this work?".
At any way, the request attributes live as long as the request/response itself and they are not retained in subsequent requests. For that you'd rather like to store it as a session attribute instead, or to pass as a request parameter in case of a redirect. Or, when you're already on JSF 2.0, storing it as a property of a view scoped bean should also do for the case the bean is to be accessed from the same view subsequently.
To learn more about the lifecycle of the HTTP servlet request/response, I'd suggest to get yourself through this answer.
Unrelated to the concrete problem: whenever you need to haul the raw Servlet API from under the JSF covers, then you should really take a break and think twice if you're really doing things the right way (read: without the need to fall back to the raw
javax.servlet
API). Shouldn't it better be a fullworthy JSF managed bean, for example?At any way, request attributes are also accessible by
ExternalContext#getRequestMap()
.No need to utilize the raw Servlet API.