Edit: This is an epic face palm situation. Wrong import for SessionScoped. So tired last night while checking it I was sure I was using enterprise sessionscoped import while I was still using faces sessionscoped import. I'm leaving this up as an aid to doofuses like me. :)
It is early in this project. After implementing up to this point with managed beans, I changed my managed beans to CDI beans as this seems to be the latest consensus on the best way to do things But this has broken previously working code. I cannot for the life of me figure out why. Help and advice is appreciated.
Happy Path (Summary... detail below code extracts)
If user not logged in, show login or register links.
If user logged in show user preferences or logout links.
Now Crappy Path with CDI (I don't blame CDI)
If user not logged in, show login or register links.
If user logged in still see login or register links. (bad, bad app)
The objects involved are
a facelet menu panel (with a primefaces login dialog... I don't think this has any thing to do with it but included for completeness) with render attributes if logged in or not,
a session scoped user bean,
a request scoped authentication bean to log the user in and out.
Objects used listed below. Implemented as CDI beans.
facelet
<h:panelGroup id="loginPanel" rendered="#{!user.loggedIn}">
Show login buttons and stuff
</h:panelGroup>
<h:panelGroup id="logoutPanel" rendered="#{user.loggedIn}">
Show logout buttons and stuff
</h:panelGroup
authentication bean
#Named(value = "webAuthenticationBean") //formerly managedbean
#RequestScoped
public class WebAuthenticationBean implements Serializable {
#Inject private UserBean user; //formerly a managed property which worked
...
request.login(uername, password);
user.setuserdata(username); // sessionscoped user state here used to check login state among other things later.
...
return(true) // they are now logged in
user bean
#Named(value = "user") //formerly managedbean
#SessionScoped
public class UserBean implements Serializable {
#EJB
private UserService userService; //stateless session bean
private userInfo = new UserInfo(); // keeps user state and can be used as a DTO/VO
#PostConstruct
public void init() {
//sets default state to "guest user". This is NOT a logged in state
}
public void setuserdata(String username){
userInfo = userService.getUserInfo(username);
// method called from WebAuthenticationBean
// sets the user state to a non-guest user (they're logged in).
// I can see in debug mode that this is being called and retrieving
// the user data from the database and setting "userInfo"
}
public void isLoggedIn() throws InvalidUserException{
// checks state to see if they are logged in, basically a bit more than are they still a guest or not
returns (true) if logged in
returns (false) if not logged in
// this worked with managed beans
}
...
So here is the actual use case when I watch in debug mode:
Happy Path (prior to change to CDI bean)
1) User navigates to the welcome page
2) the user bean is queried to see if they are logged in (user.loggedIn in the facelet).
3) userbean checks logged in state. If they are still a guest they aren’t logged in.
4) They are identified as a guest so isLoggedIn() returns false.
5) Login button is shown.
6) User requests logs in
7) authentication bean begins login process: request.login returns successfully
8) authenticationbean sets user data: user.setuserdata(username) returns successfuly.
9) authentication bean loginMethod returns (they are logged userprincipal on the server)
Alternate (crappy) path branch here (happy path continues)
10) The menu rechecks login state (user.loggedIn)
11) userbean checks for appropriate state and sees they are valid non guest user
12) userbean returns (true) they are logged in
13) menu shows logout button
Crappy Path (what happens after I changed these to CDI beans)
10) The menu rechecks login state (user.loggedIn)
11) userbean checks for appropriate state and sees they are a guest //the updated user state seems to have disappeared from this user in this session.
12) userbean returns (false) they are not logged in //but they are
13) menu shows login button // they can’t login anyway since the server already sees them as logged in, in this session (ServletException: Attempt to re-login while the user identity already exists).
Why using managedbeans would I be able to see the userbean maintain its data in session scope but with cdi beans it does not? I am stumped. I’ll switch back to managed beans if I have to, it isn’t a big issue, but I would like to find out what I messed up.
I added some debugging code in the init method of the UserBean, and it appears as if the system is treating the SessionScoped UserBean as if it were RequestScoped. That is it is initializing on every call.
#PostConstruct
public void init() {
if (userInfo == null) {
userInfo = new UserInfoDTO();
userInfo.setUserName("Guest");
List<String> guestGroup = Arrays.asList(CoreUserGroupType.GUEST.toString());
userInfo.setUserGroups(guestGroup);
System.out.println("UserBean.init INSIDE Init If Statement");
}
System.out.println("UserBean.init OUTSIDE Init If Statement");
}
If it were really acting like it was SessionScoped the userInfo object would not be null every time and the 'if' statement would not be executed every time. But it is executing on every call to UserBean. So this is at the crux of the problem. As a matter of fact if it acted like it were in session scope it would not hit the init method at all on every call as it would still be initialized.
Am I not creating a sessionscoped bean properly? It would appear so, but I don't see how. As mentioned, this code ran fine when defined as a managedbean.
changed to the correct sessionscoped import and all is well. nothing hurt but my pride.
Related
I'm trying to create a localized JSF web application which allows user to select a language via dropdown. When language is selected, I simulate a redirect to the same page but with URL parameter:
window.location.replace(urlToMyApp + '?locale=DE');
Next, I read 'locale' parameter in application's web filter and write it in a cookie with the same name:
String localeValue = httpRequest.getParameter("locale");
Cookie cookie = new Cookie("locale", localeValue);
cookie.setMaxAge(-1);
cookie.setDomain(cookieDomain);
cookie.setPath(cookiePath);
httpResponse.addCookie(cookie);
Now when I try to read that cookie in request bean init method, cookie is not available. If I select another language via dropdown (EN for example), previously selected language (DE) is read in init method.
I assume that cookie written in filter is not available before next "request - response" cycle, can someone confirm that?
If that's true I'm asking for an idea to translate my application immediately after selecting another language.
Just one thing that I think I need to mention - language dropdown is not part of my application. It's part of some kind of framework for several applications to be included (like portal).
I assume that cookie written in filter is not available before next "request - response" cycle, can someone confirm that?
That's correct.
You've added the new cookie to the response, not to the request. So any attempt to read it from the same request won't work. The cookie will only be available in the request if the browser has actually sent it. But it can only do that if it has obtained the cookie data from a previous response.
If that's true I'm asking for an idea to translate my application immediately after selecting another language.
If the request scoped bean is managed by CDI #Named, then just inject it in the filter and set the locale over there.
#Inject
private Bean bean;
public void doFilter(...) {
// ...
bean.setLocale(locale);
// ...
}
Else if it's not managed by CDI, but by the since JSF 2.3 deprecated #ManagedBean, then manually instantiate it and put it in request scope so that JSF will just reuse the same bean.
public void doFilter(...) {
// ...
Bean bean = new Bean();
bean.init(); // If necessary.
bean.setLocale(locale);
request.setAttribute("bean", bean); // "bean" is managed bean name.
// ...
}
See also:
Get JSF managed bean by name in any Servlet related class
Localization in JSF, how to remember selected locale per session instead of per request/view
I'm having some difficulty interacting with a Session-scoped managed bean after a user programmatically logs into my web application.
BACKGROUND:
I have a [javax.enterprise.context.]Session-scoped bean named "SessionHelper" where I place a lot of information gathered from the user as he/she uses the application. In my logon page (which is NOT SessionScoped), Here's a sample of what I'm doing:
#Inject SessionHelper theHelper;
....
FacesContext theContext = FacesContext.getCurrentInstance();
ExternalContext externalContext = theContext.getExternalContext();
HttpServletRequest theRequest = (HttpServletRequest) externalContext.getRequest();
....
theRequest.login(username, password);
....
theSession.method(dostuff);
After this section of code is executed, my application redirects into a protected directory and allows the user (based on roles) to perform their job functions.
When I attempt to "#Inject SessionHelper" into any of my protected resources, my understanding is that I should get the specific SessionScoped instance of SessionHelper that has the data set right after the call to login. This should be available to me for as long as the session (for that specific user) is valid. Unfortunately, the instance I'm getting has none of my "theSession.method(dostuff)" in it.
Am I fundamentally misunderstanding the scope here?
The only thing I could potentially see is that the initial #Inject into my login page is not carried over after the session has been created. If this is the case, is there a way to force a re-injection after the session is created?
As always, thank you very much for your help!!
My Problem
I have a #SessionScoped sessionInformationBean, which holds a Person-Entity from a logged in user. So, if a User logs in, I am looking up the corresponding Entity and put in in the #SessionScoped CDI Bean. This Bean is used to retrieve the current user (a Person-Entity) at any position in code, so that you can check, if it is a Admin or things like that.
#Inject
private PersonFacade personFacade;
private Person currentUser;
public Person getCurrentUser() {
if (currentUser == null) {
String loginname = FacesContext.
getCurrentInstance().
getExternalContext().getRemoteUser();
currentUser = personFacade.findByLoginname(loginname);
}
return currentUser;
}
But set the case, an Admin is giving this logged in user ( the Person-Entity) some Admin-Rights and saves him to the database. In this case, the Person at the #SessionScoped Bean is not updated, therefore the already logged in user is not seeing his Admin-Rights after a refresh of his page. Thats the problem. To avoid this problem I am fetching the user new from the database every access (There is no cache activated) to the #SessionScoped bean.
What I want
But I want to cache him and avoid a database access every time. So, I thought, if anyone saves a user, I will simply notice all sessionInformationBean-Instances and set the currentUser-Attribute to null. So, the next call, they fetch it again from database and cache it till its set to null again from my Person.save()-Operation.
What I tried
But that seems to be a little bit tricky. I thought I can handle it with CDI-Events, but they only will be pushed to the sessionInformationBean of the user, that is editing the other user.
Maybe something to do with my problem: CDI Events observed across sessions
Then I thought.. okay.. lets do it with Primefaces-Push. But the same thing.. the Events are just coming to my own sessionInformationBean.
EventBus eventBus = EventBusFactory.getDefault().eventBus();
eventBus.publish("/session", "test");
I thought the purpose of push and WebSockets is to notify all users or sessions.
What should I do?
So, the question is: How to access all instances of a specific #SessionScopedBean? I just want to access the sessionInformationBean from every logged in user and set the currentUserto null.
There's no built in way I can think of to do this. What I would recommend is to add an ApplicationScoped bean. Whenever your SessionScoped bean is created, register it with this app scoped bean. When you want to process this event iterate through all of these objects.
I'm curious though, what happens when you have multiple servers?
So I'm having a problem trying to pass a String value.
The String value is entered through a login page as username.
The JSF then calls the Bean to verify log in information then proceeds to another JSF page.
I was wondering how to pass the username along to the new JSF page. Thank you.
If you're performing a navigation instead of a redirect, then you basically don't need to do anything. The information is also just available in the navigated page.
E.g. in login page,
<h:inputText value="#{bean.username}" />
and in the navigated page:
<p>You have entered the following username: #{bean.username}</p>
If you're however performing a redirect instead of a navigation, then you basically need to store the information in a bit broader scope. You didn't clearly elaborate the concrete functional requirement in the question, but if I guess it right, you just wanted to remember the currently logged-in user for the remaining of the HTTP session. In that case, just store it in the session scope during the login action.
public String login() {
// ...
User user = userService.find(username, password);
// ...
externalContext.getSessionMap().put("user", user);
// ...
return "nextpage?faces-redirect=true";
}
This way it's available by #{user} throughout the entire HTTP session.
<p>You're logged in as #{user.name}.</p>
You can also use <t:saveState> without using session scope. <t:saveState> is longer than the request scope but shorter than session scope.
This may help you : http://myfaces.apache.org/tomahawk-project/tomahawk12/tagdoc/t_saveState.html
I am trying to cache the authentication information in a SessionScoped managed bean.
When I open a browser and login into the server (the browser asks me for username/password) the first time, it works as it should.
The trouble comes when I restart the webapp or the server (it is a development setup). Then, accessing the webapp from one of the browser where I had previously logged in, causes that in my #PostConstruct method, FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal() returns null (I check that it is effectively executed).
On the other hand, if I just check that value from getUser(), it works correctly.
AFAIK, I expected the browser the just cache the credentials and that when I was reentering the application after a restart the only difference was that the browser would automatically send the credentials without prompting me again. I did not expect that it would make any difference in the server.
The code is the following (simplified)
#ManagedBean
#SessionScoped
public class UserManager {
private Principal userPrincipal = null;
#PostConstruct
public void init() {
this.userPrincipal =
FacesContext.getCurrentInstance().getExternalContext().getUserPrincipal();
System.out.println("EN POSTCONSTRUCT DE LDAP PRINCIPAL!! " + this.userPrincipal);
}
public String getUser() {
return this.userPrincipal.getName();
}
}
The setup is JBoss 6.1 Final with Mojarra 2.03, JDK 6. I have tested it both with IE7 and Firefox.
UPDATE: I have found more about it. If I go into my welcome page, then the webapp works as expected. It is when I try to directly access another page (*1) that it fails to initialize the user info.
*1: I am not talking about reloading the page as this always fails, but typing http://myserver/mywebapp/page_that_is_not_welcome_one.xhtml in the URL bar.