问题描述
我已经使用JSF和PrimeFaces实现了一个登录表单。
我在PrimeFaces展示网站上使用了。
I have implemented a login form using JSF and PrimeFaces.I used this example in the PrimeFaces showcase website.
我有一个Facelets页面来显示dataTable。现在我需要将上面的登录表单与此表页面集成。所以我在LoginBean.java中添加了几行来处理会话属性。
I have a Facelets page to show a dataTable. Now I need to integrate the above login form with this table page. So I added few lines in to LoginBean.java to handle session attribute.
if (username.equals(getUsername_db()) && password.equals(getPassword_db())) {//valid user and paward
loggedIn = true;
msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "Welcome", getUsername_db());
//new lines
FacesContext context2 = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context2.getExternalContext().getSession(true);
session.setAttribute("user", username);
//end of new lines
...
我需要隐藏如果用户未登录,则来自dataTable的列。
现在我的问题是,如何在我的Facelets页面中访问会话属性?
I need to hide a column from the dataTable, if the user is not logged in.Now my problem is, how can I access session attribute inside my Facelets page?
推荐答案
您已将登录用户存储为名为user的会话属性。
You've stored the logged-in user as a session attribute with the name "user".
所以它在EL中可用作为如下:
So it's in EL available as follows:
#{user}
您可以在EL中使用空
关键字来检查它是否存在(即是否已登录)和您可以使用JSF组件的呈现的
属性来指示是否生成HTML输出。
You can just use the empty
keyword in EL to check if it's present or not (i.e. if it's logged-in or not) and you can use JSF component's rendered
attribute to instruct whether to generate HTML output or not.
<h:panelGroup rendered="#{not empty user}">
<p>Welcome #{user}, you have been logged in!</p>
</h:panelGroup>
在隐藏表列的特定情况下,只需按如下方式使用它:
In your specific case of hiding a table column, just use it as follows:
<p:column rendered="#{not empty user}">
...
</p:column>
存储会话属性的更好方法是使用 ExternalContext#getSessionMap()
。这样你的代码就没有臭 javax.servlet。*
imports。
A nicer way to store a session attribute is using ExternalContext#getSessionMap()
. This way your code is free of smelly javax.servlet.*
imports.
FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("user", username);
无关到具体问题,为什么进行以下检查?
Unrelated to the concrete problem, why the following check?
if (username.equals(getUsername_db()) && password.equals(getPassword_db())) {
为什么不进行 SELECT ... FROM用户WHERE用户名=? SQL中的AND password =?
?或者你不相信它返回右行的数据库?
Why don't you just do a SELECT ... FROM user WHERE username=? AND password=?
in SQL? Or don't you trust the DB that it returns the right row?
这篇关于如何在Facelets页面中访问会话属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!