EJB annotation doesnt work in JSF - jsf

i'm starting with JEE and i need to work with JSF-EJB-JPA.
I have an EJB project and it deploys ok, my war file too. When i use the annotation EJB to in a properti in the war, it simply doesnt work, no information is show
I have an h:dataTable and i want to populate it with info that comes from a database, injeting an EJB, but the data just not show (i dont know if it didnt arrive to the WAR or only it isnt being showed). The table is empty, only with the headers that i (of course) wrote directly.
if i dont use #EJB anywhere, the data that doesnt come from the EJB is showed correctly, for example, if i write "Hello world" i cant print it in , but when i dare to use #EJB even that information stop working, as if using #EJB broke all the conection between the xhtml and the manager.
i followed a tutorial, and in the video everything went good.
a part of the controller:
import javax.inject.Named;
import javax.inject.Inject;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import javax.ejb.EJB;
#Named(value = "editorialController")
#SessionScoped
public class EditorialController implements Serializable {
#EJB//(name=Tutorial-ejb")
private EditorialFacade editorialFacade;
private Integer randomInt;
public List<Editorial> findAll()
{
return this.editorialFacade.findAll();
}
public Integer getRandomInt() {
return randomInt;
}
public void setRandomInt(Integer randomInt) {
this.randomInt = randomInt;
}
}
a pice of the xhtml
<h:body>
Hello from Facelets
<h:outputLabel value="#{editorialController.randomInt}"></h:outputLabel>
<h:form>
<h:dataTable var="p" value="#{editorialController.findAll()}">
<h:column>
<f:facet name="Header">
<h:outputText value="NAME"></h:outputText>
</f:facet>
<h:outputText value="#{p.nombre}"></h:outputText>
</h:column>
</h:dataTable>
</h:form>
</h:body>
i tried with: #{editorialController.findAll()} and #{editorialController.findAll}
For the EJB, are as usual: a package for entities, other for facades; netbeans generated them, so i think its not necesary copy&paste the code.
im using glassfish (payara). web.xml has all the JSF stuff.
the persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="Tutorial-ejbPU" transaction-type="JTA">
<jta-data-source>jdbc/MyDataSource</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>

Related

commandButton doesn't invoke managed bean action

I've been reading and searching among the many pages with similar questions, but I cannot find why my commandButton is not invoking the action (I have debugged it and that is the problem). My code looks simple but... doesn't work. Maybe it's a newbie problem, but I don't know where it is.
I'm writing a portlet for liferay using JSF2 and Liferay Faces Alloy.
I've also read the question commandLink/commandButton/ajax backing bean action/listener method not invoked, very educational for me, but none of the points have solved my problem.
Here is my mainView.xhtml file:
<?xml version="1.0"?>
<f:view
xmlns="http://www.w3.org/1999/xhtml"
xmlns:aui="http://liferay.com/faces/aui"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head />
<h:body>
<h:form>
<h:messages globalOnly="true" layout="table" />
<h:outputText id="esteTexto" value="#{ramSession.texto}" />
<br />
<h:commandButton action="#{ramSession.add}" styleClass="btn btn-default" value="#{ramSession.texto}">
</h:commandButton>
</h:form>
</h:body>
</f:view>
And here is my SessionScoped ManagedBean file, RamSession.java:
#ManagedBean
#SessionScoped
public class RamSession extends AbstractBaseBean implements Serializable {
private static final long serialVersionUID = 919724848720360000L;
private String texto;
public void add() {
this.texto = new String("Entrando");
}
#PostConstruct
public void postConstruct() {
this.texto = new String("Jereje");
}
public String getTexto() {
logger.info("gettingTexto");
addGlobalSuccessInfoMessage();
return this.texto;
}
public void setTexto(String texto) {
this.texto = texto;
}
}
I have also tried returning a String (even not necessary), with an actionListener method and even with ajax but nothing. Can anybody help me? Thanks a lot.
Maybe your mojarra listner is not configured correctly.
Follow one of the two following sub-steps
a. Add the liferay-faces-init.jar dependency in each Liferay JSF project by adding the following code to each pom.xml :
<dependency>
<groupId>com.liferay.faces</groupId>
<artifactId>liferay-faces-init</artifactId>
<version>3.1.3-ga4</version>
</dependency>
b. Add the following code in each WEB-INF/web.xml of all your JSF projects :
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
Why not initialize texto in the declaration?
private String texto = "Jereje";
public void addGlobalSuccessInfoMessage(){
//faces message
}
//Getter Setter
Then you can remove the entire PostConstruct method.
Also if all you want to do is set a string and update without navigation just use f:setPropertyActionListener with a f:ajax for updating your messages. You can use action if you want by returning null or void, or actionListener and set the string inside of that, but I'm not seeing why you'd want to. This link may help with those options... Answer by Balus C.
May want to remove any extra logic from your getter method as well. This won't affect your problem but it's cleaner and creating a success message on a getter seems problematic.
<h:form id="myForm">
<h:messages globalOnly="true" layout="table" />
<h:outputText id="esteTexto" value="#{ramSession.texto}" />
<br />
<h:commandButton value="#{ramSession.texto}" actionListener="#{ramSession.addGlobalSuccessInfoMessage()}" styleClass="btn btn-default">
<f:setPropertyActionListener value="Entrando" target="#{ramSession.texto}" />
<f:ajax render="myForm" />
</h:commandButton>
</h:form>

#Named #Produces getter not recognized with bean-discovery-mode="annotated"

I am trying to get samples running of the book "Java EE 7 Development with WildFly". Now I face the following question/problem:
TheatreInfo.java:
#Model
public class TheatreInfo {
...
#Produces
#Named
public Collection<Seat> getSeats() {
return Lists.newArrayList(seats);
}
...
}
Seat.java:
#Dependent
#Named
public class Seat {
...
public String getName() {
return name;
}
...
}
index.xhtml:
<?xml version="1.0" encoding="UTF-8" ?>
<ui:composition xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets"
xmlns:f="http://xmlns.jcp.org/jsf/core"
xmlns:h="http://xmlns.jcp.org/jsf/html"
template="/WEB-INF/templates/default.xhtml">
<ui:define name="content">
<h1>TicketBooker Machine</h1>
<h:form id="reg">
<h:panelGrid columns="1" border="1" styleClass="smoke">
<h:dataTable var="_seat" value="#{seats}" rendered="#{not empty seats}" styleClass="simpletablestyle">
...
</h:dataTable>
</h:panelGrid>
</h:form>
</ui:define>
</ui:composition>
beans.xml:
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
version="1.1" bean-discovery-mode="all/annotated">
</beans>
This perfectly works - I see a table of seats in my web-brower - as long as I use bean-discovery-mode="all" in my beans.xml. As soon as I use bean-discovery-mode="annotated" in my beans.xml I don't see the table of seats anymore in my browser respectively I see an empty table but no error occurs.
In the book they use bean-discovery-mode="all" but I prefer to see which classes are managed beans an which are not. To use bean-discovery-mode="annotated" I had to add #Dependent to some classes but I have not been able to fix the issue with the names producer method. Can anyone help?
Hm, it runs if I use
#Named
#RequestScoped
public class TheatreInfo {
...
instread of
#Model
public class TheatreInfo {
...
Don't understand why, #Named and #RequestScoped is included in the #Model stereotype!? Does anyone know?
Thanks, Dominic

Richfaces editable dataTable not setting updated values in Bean

I have tried a bunch of suggestions after googling but none has so far worked for me. I am trying to display a simple datatable with editable inputText values in each row. table is being populated from database via a usual List of objects. Here is my xhtml page and managed bean
Richfaces 4.2.1, JSF 2 mojarra bundled with JBoss 7.1, JDK 1.6
<rich:dataTable value="#{wlScoreBean.scoreList}" binding="#{wlScoreBean.scoreTable}" var="item" id="table" style="width:100%">
<rich:column>
<f:facet name="header">PARAM NAME</f:facet>
<h:outputText value="#{item.paramName}" />
</rich:column>
<rich:column>
<f:facet name="header">1 Score</f:facet>
<h:inputText value="#{item.name1}" />
</rich:column>
<rich:column>
<f:facet name="header">2 Score</f:facet>
<h:inputText value="#{item.name2}" />
</rich:column>
</rich:dataTable>
<br/>
<h:panelGrid columns="3" id="buttonRow">
<a4j:commandButton value="Save" render="table" execute="#this" action="#{wlScoreBean.update()}">
</a4j:commandButton>
</h:panelGrid>
import java.io.Serializable;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.component.html.HtmlDataTable;
import javax.faces.event.ValueChangeEvent;
import org.richfaces.component.UIDataTable;
#ManagedBean(name = "wlScoreBean")
#ViewScoped
public class WS implements Serializable
{
private static final long serialVersionUID = 1L;
private HtmlDataTable scoreTable;
private List<WorkloadScore> scoreList;
public void watchScore(ValueChangeEvent e)
{
System.out.println("old value="+e.getOldValue() + ", New Value="+e.getNewValue());
}
public List<WorkloadScore> getScoreList() {
return scoreList;
}
public void setScoreList(List<WorkloadScore> scoreList) {
this.scoreList = scoreList;
}
#EJB
private WorkloadScoreManagerService wlScoreManager;
public HtmlDataTable getScoreTable() {
return scoreTable;
}
public void setScoreTable(HtmlDataTable scoreTable) {
this.scoreTable = scoreTable;
}
public WorkloadScoreBean()
{
}
#PostConstruct
private void getAllScores()
{
this.scoreList = wlScoreManager.getAllScores();
}
public void update()
{
for (WorkloadScore wls : getScoreList())
{
System.out.println(wls.getParamName()+"="+wls.getPortabilityScore()+","+wls.getVirtualizationScore());
}
//wlScoreManager.update(workloadScore);
}
}
Here's all the things I tried. All of them result in only the OLD VALUES being printed to console in the update() method.
Changed from rich:dataTable to plain old JSF h:dataTable, same result
Bound the dataTable to a Managed Bean property, checked in update() method, old values are being printed here too. I just did a getVlaue() on the UIDataTable object and cast it to List.
The List is supposed to have been updated with changed values from the form, but I do not see it happening. I did make sure to put the MBean in ViewScope.
do you have a h:form outside the datatable? and did you try to replace inputtext with inplaceinput fields?
See answer here https://community.jboss.org/thread/200684?tstart=0
I changed execute=#form and it worked! no need for ValueChangeEvent or messing with dataTable binding. The List values are updated in place and the update method prints the correct value

Use of JSTL/core tags screws up ViewScoped Bean

I think I have run into a bug in Mojarra 2.1.0. Maybe I missed something but damned if I can see it.
I rely a lot of #ViewScoped beans to save state whilst the browser does a lot of AJAX to the server. I find when I use certain tags, the #ViewScoped bean starts getting re-instantiated when it shouldn't be. Here is my test case backing bean:
/*
* TestStuff.java
*/
package test;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.event.ActionEvent;
/**
* Backing bean for test.xhtml -- working out AJAX/SVG connection
*
*/
#ManagedBean
#ViewScoped
public class TestStuff implements Serializable {
private int counter = 0;
public TestStuff() {
log("TestStuff(): {0}", this);
}
public String getRandomNumber() {
int i = (int) (Math.random() * 1000000.0);
return String.format("%d", i);
}
public int getCounter() { return counter; }
public List<String> getStuff() {
return Arrays.asList("big", "bad", "wolf");
}
public void pushButton(ActionEvent evt) {
log("TestStuff.pushButton({0}): {1}",
new Object[] { evt, ++counter });
}
}
And here is the JSF Facelets page that uses it:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.prime.com.tr/ui"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
<title>Test Page</title>
</h:head>
<h:body>
<h1>Test Page</h1>
<p>If you are reading this text, the server
is not properly configured.</p>
<ui:composition id="compRoot" template="/template5.xhtml">
<ui:define name="content">
<h1>Test</h1>
<h:form id="formTest">
<p:commandButton value="Do Me"
actionListener="#{testStuff.pushButton}"
update="testUpdate" />
<p:panel id="testUpdate" >
<h:outputText value="Random output is: " />
<h:outputText
value="#{testStuff.randomNumber}"
/>
<h:outputText value=" Counter is: "/>
<h:outputText
value="#{testStuff.counter}"
/>
</p:panel>
<h:panelGrid columns="5" border="1" >
<c:forEach items="#{testStuff.stuff}" var="x">
<h:outputText value="#{x}" />
</c:forEach>
</h:panelGrid>
</h:form>
</ui:define>
</ui:composition>
</h:body>
</html>
So here is what goes wrong. When you click on the "Do Me" command button, a new instance of the backing bean gets created each time, just as if it were a #RequestScoped bean. I can see this via the log() call in the constructor.
If you change the bean to #SessionScoped, this doesn't happen. You get one instance of the bean no matter how many times the button is clicked.
HOWEVER -- if you leave it as #ViewScoped, and you take out the c:foreach element and its content, it now no longer re-instantiates the bean each click. In other words it now works as expected.
Is this a mojarra bug or am I doing something wrong here?
This is a known "bug": issue 1665. It's a chicken-egg issue with regard to partial state saving.
In your case, however, you could also just use <ui:repeat>.
<ui:repeat value="#{testStuff.stuff}" var="x">
<h:outputText value="#{x}" />
</ui:repeat>
Your best bet is to try to avoid JSTL tags when using #ViewScoped. The only alternative is to disable partial state saving by a context param in web.xml:
<context-param>
<param-name>javax.faces.PARTIAL_STATE_SAVING</param-name>
<param-value>false</param-value>
</context-param>
But it makes the views more memory hogging.

jsf databinding does not work

I am trying to create a page using richfaces, I created the following field
<h:inputText value="#{petTest.pet.name}"/>
faces-config:
<managed-bean>
<managed-bean-name>petTest</managed-bean-name>
<managed-bean-class>petstore.PetTest</managed-bean-class>
<managed-bean-scope>request</managed-bean-scope>
</managed-bean>
managed bean:
package petstore;
public class PetTest {
private Pet pet;
public Pet getPet(){
return pet;
}
public void setPet(Pet pet){
this.pet = pet;
}
}
But I get a field and within it the literal value #{petTest.pet.name} instead of the value of the field. What am I doing wrong?
Is your h:inputText part of a h:form like this:
<h:form id="formId">
..
<h:inputText value="#{petTest.pet.name}"/>
..
</h:form>
Without a form h:inputText is not working.

Resources