I'm currently evaluating Java EE 6 / JSF 2.1 with RichFaces.
A bean which is declared as
#ManagedBean
#ViewScoped
Gets an ID set (to prepare e.g. a delete operation).
Via JSF a confirmation popup is displayed.
If the user confirms, the delete method is invoked and removes the row for which the ID was stored in step 1.
Since CDI beans don't have a ViewScope I tried to declare the bean as:
#Named
#ConversationScoped
Now the processing fails in step 3. because the value that was set in step 1 (checked that) is no longer available.
Do I have to use Conversation.begin() and Conversation.end() methods?
If so, where would be good place to invoke them?
If you can upgrade to JSF 2.2, immediately do it. It offers a native #ViewScoped annotation for CDI.
import javax.faces.view.ViewScoped;
import javax.inject.Named;
#Named
#ViewScoped
public class Bean implements Serializable {
// ...
}
Alternatively, install OmniFaces which brings its own CDI compatible #ViewScoped, including a working #PreDestroy (which is broken on JSF #ViewScoped).
import javax.inject.Named;
import org.omnifaces.cdi.ViewScoped;
#Named
#ViewScoped
public class Bean implements Serializable {
// ...
}
Another alternative is to install MyFaces CODI which transparently bridges JSF 2.0/2.1 #ViewScoped to CDI. This only adds an autogenerated request parameter to the URL (like #ConversationScoped would do).
import javax.faces.bean.ViewScoped;
import javax.inject.Named;
#Named
#ViewScoped
public class Bean implements Serializable {
// ...
}
If you really need to use #ConversationScoped, then you indeed need to manually begin and end it. You need to #Inject a Conversation and invoke begin() in the #PostConstruct and end() in the latest step of the conversation, usually an action method which redirects to a new view.
import javax.enterprise.context.Conversation;
import javax.enterprise.context.ConversationScoped;
import javax.inject.Named;
#Named
#ConversationScoped
public class Bean implements Serializable {
#Inject
private Conversation conversation;
// ...
#PostConstruct
public void init() {
conversation.begin();
}
public String submit() {
// ...
conversation.end();
return "some.xhtml?faces-redirect=true";
}
}
See also:
How to choose the right bean scope?
I think you can benefit from CDI extension to create your own scope so you can implement the context and use the #NormalScope.
CDI fires an event AfterBeanDiscovery after each bean call
You can use CDI extension to #Observes this event and add your context implementation
In your scope implementation you can :
Use Contextual to get your bean by its name from FacesContext ViewRoot Map and return it after each ajax call back
Use CreationalContext if the bean name from first step is not found to create it in the FacesContext ViewRoot Map
For a more in-depth explanation, I recommend this link : http://www.verborgh.be/articles/2010/01/06/porting-the-viewscoped-jsf-annotation-to-cdi/
Inject the conversation into your bean and in the #PostConstructor method start the conversation if the conversation is transient.
And after deleting the record, end your conversation and navigate to your destination page. When beginning a conversation. Here is an example
public class BaseWebBean implements Serializable {
private final static Logger logger = LoggerFactory.getLogger(BaseWebBean.class);
#Inject
protected Conversation conversation;
#PostConstruct
protected void initBean(){
}
public void continueOrInitConversation() {
if (conversation.isTransient()) {
conversation.begin();
logger.trace("conversation with id {} has started by {}.", conversation.getId(), getClass().getName());
}
}
public void endConversationIfContinuing() {
if (!conversation.isTransient()) {
logger.trace("conversation with id {} has ended by {}.", conversation.getId(), getClass().getName());
conversation.end();
}
}
}
#ConversationScoped
#Named
public class yourBean extends BaseWebBean implements Serializable {
#PostConstruct
public void initBean() {
super.initBean();
continueOrInitConversation();
}
public String deleteRow(Row row)
{
/*delete your row here*/
endConversationIfContinuing();
return "yourDestinationPageAfter removal";
}
}
There is a project which holds an extentions to the Java EE stack features: DeltaSpike. It is a consolidation of Seam 3, Apache CODI. Above others, it includes the #ViewScoped into CDI. This is an old article and by now it has reached version 1.3.0
You can use:
import javax.annotation.PostConstruct;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
#Named
#ViewScoped
public class PageController implements Serializable {
private String value;
public void setValue(String value) {
this.value = value;
}
public String getValue() {
return value;
}
public void execute() {
setValue("value");
}
#PostConstruct
public void init() {
System.out.println("postcontructor");
}
}
Related
I am seeing this strange behavior when using #ManagedProperty. I have 2 beans:
UserManager (SessionScoped)
#ManagedBean
#SessionScoped
public class UserManager extends BaseBean implements Serializable
{
private static final long serialVersionUID = 1861000957282002416L;
private User currentUser;
public String login()
{
// set value of currentUser after authentication
}
public User getCurrentUser() {
return currentUser;
}
public boolean isLoggedIn() {
return getCurrentUser() != null;
}
}
CartBean (ALSO SessionScoped)
...
import javax.faces.bean.ManagedProperty;
...
#ManagedBean
#SessionScoped
public class CartBean extends BaseBean implements Serializable
{
#ManagedProperty(value = "#{userManager.loggedIn}")
private boolean loggedIn;
public void updateCart(Movie selectedMovie)
{
if (!loggedIn) {
return;
}
System.out.println("UPDATE CART REQUEST");
int id = selectedMovie.getMovieID();
if (cart.containsKey(id)) {
cart.remove(id);
}
else {
cart.put(id, selectedMovie);
}
}
public void setLoggedIn(boolean loggedIn) {
this.loggedIn = loggedIn;
}
}
After logging in successfully, the value of loggedIn still remains false.
However, if I change the scope of CartBean to #ViewScoped, the value of loggedIn gets updated and I see the sysout.
As per my understanding and also after reading various articles, one can inject a managed bean or its property only if it is of the same or broader scope. But the "same scope" case does not seem to work in my code. What am I missing here?
I am using:
Mojarra 2.1.16
Spring 3.2
Hibernate 4.1
Tomcat 7.0.37
#ManagedProperty annotation can only provide static injection, which means that the annotated property will get injected when and only when the holding #ManagedBean is instantiated.
When you deploy your application, I believe your CartBean was referenced right at the beginning through things like the View cart button, etc. As a consequence, the injection took place too early and since the bean is #SessionScoped, you will carry the initial false value till the end of time :).
Instead of injecting only the boolean field, you should, instead, inject the whole UserManager bean:
#ManagedBean
#SessionScoped
public class CartBean extends BaseBean implements Serializable {
#ManagedProperty(value = "#{userManager}")
private UserManager userManager;
public void updateCart(Movie selectedMovie) {
if (!userManager.isLoggedIn()) {
return;
}
...
}
}
The solution is using Omnifaces it worked for me each time the value change you will get the new value
#ManagedBean
#ViewScoped
public class CartBean extends BaseBean implements Serializable {
private boolean loggedIn;
public void updateCart(Movie selectedMovie) {
loggedIn=Faces.evaluateExpressionGet("#{userManager.loggedIN}");
if (!userManager.isLoggedIn()) {
return;
}
...
}
}
I am trying to get session scoped bean data in another Managed bean. When I am doing that value is coming as null and giving java.lang.NullPointerException error. I am new to JSF so keep in mind that I might be missing simple thing.
Here is the SessionScoped Bean
#ManagedBean
#SessionScoped
public class UserSessionBean {
private superProcessId;
//getter setter and other code
}
Here is the Managed Bean I am trying to get this data
#ManagedBean
public class AddProcessBean {
#ManagedProperty(value="#{UserSessionBean}")
private UserSessionBean sessionData;
//Getter Setter for sessionData
public UserSessionBean getSessionData() {
return sessionData;
}
public void setSessionData(UserSessionBean sessionData) {
this.sessionData = sessionData;
}
public void addAction() {
System.out.println(getSessionData().getSuperProcessId());
}
}
Your value is not good in #ManagedProperty. Use:
#ManagedProperty(value="#{userSessionBean}")
Default name for bean is same as class name with lower first letter. Also scope of your bean whose managed property is should be session or lower (view, request).
I have the following ApplicationScoped bean
package es.caib.gesma.gesman.data;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import es.caib.gesma.gesman.ejb.Dao;
#ManagedBean(name="priorityList")
#ApplicationScoped
public class PriorityList {
#EJB
Dao daoEjb;
private List<Priority> priorities = null;
public PriorityList() {
}
#PostConstruct
public void refresh() {
this.priorities = daoEjb.findPriorities();
}
public List<Priority> getPriorities() {
return this.priorities;
}
public Priority fromId(int id) {
for(Priority priority : this.priorities) {
if (priority.getId() == id) {
return priority;
}
}
return null;
}
}
I try to inject that bean inside a Converter
package es.caib.gesma.gesman.data.converter;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.ConverterException;
import es.caib.gesma.gesman.data.Priority;
import es.caib.gesma.gesman.data.PriorityList;
#ManagedBean
#ApplicationScoped
public class PriorityConverter implements Converter {
#ManagedProperty("#{priorityList}")
private PriorityList priorityList;
#Override
public Object getAsObject(FacesContext arg0, UIComponent arg1, String arg2) {
...
}
#Override
public String getAsString(FacesContext arg0, UIComponent arg1, Object arg2) {
...
}
public void setPriorityList(PriorityList priorityList) {
System.out.println("SET PRIORITYLIST " + priorityList);
this.priorityList = priorityList;
}
}
Whenever I try to access the property, it is null. The setter is never called.
From this question and this one, it looks like it is not possible to inject the bean the usual way (please correct me if I am wrong). There is any alternative so I avoid having to get the entire list of values from the EJB (= database access) each time?
You can't (currently) inject dependencies into converters. However, if you can use Seam 3, the seam-faces module will enable this. You don't need to do anything special, just have the seam-faces JAR (and any of its dependencies) in the classpath and injection into converters will magically work. Just watch out for other unintended side-effects (I've noticed differences in transaction boundaries when the seam-persistence JAR is in the classpath).
I think you should be able to pull this bean out from the HttpSession (it works for me in PhaseListener with SessionScoped bean)
FacesContext context = FacesContext.getCurrentInstance();
HttpSession session = (HttpSession) context.getExternalContext().getSession(true);
SessionForm sessionBean = (SessionForm) session.getAttribute("priorityList");
Or if I may borrow article from BalusC about JSF communication, on the bottom is described how to make a converter from ManagedBean (so you could easily inject your ApplicationScoped bean there)
I've tried to learn the JSF 2.0 with bean validation at the class level as the following: -
The utility
#Singleton
public class MyUtility {
public boolean isValid(final String input) {
return (input != null) || (!input.trim().equals(""));
}
}
The constraint annotation
#Retention(RetentionPolicy.RUNTIME)
#Target({
ElementType.TYPE,
ElementType.ANNOTATION_TYPE,
ElementType.FIELD
})
#Constraint(validatedBy = Validator.class)
#Documented
public #interface Validatable {
String message() default "Validation is failure";
Class<?>[] groups() default {};
Class<? extends Payload>[] payload() default {};
}
The constraint validator
public class Validator extends ConstraintValidator<Validatable, MyBean> {
//
//----> Try to inject the utility, but it cannot as null.
//
#Inject
private MyUtility myUtil;
public void initialize(ValidatableconstraintAnnotation) {
//nothing
}
public boolean isValid(final MyBean myBean,
final ConstraintValidatorContext constraintContext) {
if (myBean == null) {
return true;
}
//
//----> Null pointer exception here.
//
return this.myUtil.isValid(myBean.getName());
}
}
The data bean
#Validatable
public class MyBean {
private String name;
//Getter and Setter here
}
The JSF backing bean
#Named
#SessionScoped
public class Page1 {
//javax.validation.Validator
#Inject
private Validator validator;
#Inject
private MyBean myBean;
//Submit method
public void submit() {
Set<ConstraintViolation<Object>> violations =
this.validator.validate(this.myBean);
if (violations.size() > 0) {
//Handle error here.
}
}
}
After running I've faced the exception as java.lang.NullPointerException at the class named "Validator" at the line return this.myUtil.isValid(myBean.getName());. I understand that the CDI does not inject my utility instance. Please correct me If I'm wrong.
I'm not sure if I'm doing something wrong or it is a bean validation limitation. Could you please help to explain further?
Your right, Hibernate Constraint Validator is not registered as a CDI-Bean by default (and though cannot receive dependencies).
Just put the Seam-Validation module on your classpath, and everything should run fine.
BTW: studying the source-code of the module is an excellent example of the elegance and simplicity of CDI extension. It's doesn't need more than a few dozens lines of code to bridge from CDI to hibernate validations...
The first "nonpostback" request to viewBean, someValue property in sessionBean is null.
Now, in a postback request, I am setting a user input to someValue. The problem is that someValue is always null in any "nonpostback" request.
Here is my code:
#ManagedBean
#ViewScoped
public class ViewBean implements Serializable {
#ManagedProperty(value = "#{sessionBean}")
private SessionBean sessionBean;
private String inputText;
#PostConstruct
public void init() {
if (sessionBean.getSomeValue() != null) // ALWAYS NULL
doSomething(sessionBean.getSomeValue());
}
private void doSomething(String s) {}
public void action(final ActionEvent ae) {
sessionBean.setSomeValue(getInputText());
doSomething(getInputText());
}
GETTERS/SETTERS
}
#ManagedBean
#SessionScoped
public class SessionBean implements Serializable {
private String someValue;
GETTER/SETTER
}
I feel I am doing something wrong. I am using Mojarra 2.1.2
Any advice is appreciated. Thank you.
UPDATE:
Using evaluateExpressionGet on both methods (init and action) works fine:
FacesContext context = FacesContext.getCurrentInstance();
SessionBean sessionBean = context.getApplication().evaluateExpressionGet(context,
"#{sessionBean}", SessionBean.class);
This is a known issue:
SessionScoped bean inside a ViewScoped bean is resolved as different bean depending on the expression used
I just changed the state saving method in my web.xml:
<context-param>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>server</param-value>
</context-param>
I use GAE (Google App Engine) and need to set javax.faces.STATE_SAVING_METHOD to client. This problem can have workaround. After the action, just call refreshSession() with new value force the session object persist
protected void refreshSession(){
saveSession(CeaConst.SESSION_ATTR_NAME_LAST_REFRESH_TIME, new java.util.Date());
}