JSF - Updating a JSF datatable on page refresh - jsf

I have a datatable on my JSF page, which gets filled dynamically on page load thanks to BalusC and Odelya.
But now when I try to refresh the JSF page to retrieve the updated data from database, I don't get the updated data in the Datatable.
I have already gone through the following link but couldn't understand the nuances..!
JSF datatable refresh on page load

Is your bean scope configured as a Session?
Have you tried to change its scope to Request?
Don't forget to close your connection after filling your resultset, which has to be a CachedRowSet
Here is an example from Core JavaServer Faces book:
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.annotation.Resource;
import javax.faces.bean.ManagedBean;
import javax.enterprise.context.RequestScoped;
import javax.sql.DataSource;
import javax.sql.rowset.CachedRowSet;
#ManagedBean
#RequestScoped
public class CustomerBean {
#Resource(name = "jdbc/mydb")
private DataSource ds;
public ResultSet getAll() throws SQLException {
Connection conn = ds.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM Customers");
CachedRowSet crs = new com.sun.rowset.CachedRowSetImpl();
crs.populate(result);
return crs;
} finally {
conn.close();
}
}
}

'#RequestScoped' should be added to refresh your bean File to get the new data.

Related

JDBC Web application in netbeans with wildfly server

I am trying to run my Web application in netbeans with wildfly server. I got error
"jboss.naming.context.java.module.LocalShop.LocalShop.env.ReadBean.dp is missing [jboss.naming.context.java.jboss.datasources.shopstyles]" and I think line
#Resource (lookup= "java:jboss/datasources/shopstyles") is causing the error. Can someone help me?
Package structure
MANIFEST.MF
My code for web application in netbeans:
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.Resource;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import javax.sql.DataSource;
#Named (value="readBean")
#RequestScoped
public class ReadBean implements Serializable {
#Resource (lookup= "java:jboss/datasources/shopstyles")
private DataSource dp;
public List<Veggie>performRead() throws SQLException{
if(dp == null){
throw new SQLException("Cannot access data pool");
}
List<Veggie>list;
try (Connection con =dp.getConnection()){
if(con == null){
throw new SQLException("Cannot establish connection to database");
}
PreparedStatement ps =con.prepareStatement("select veggie_id,name,price,created_date from veggie");
ResultSet result =ps.executeQuery();
list=new ArrayList<>();
while(result.next()){
Veggie veggie=new Veggie();
veggie.setVeggieID(result.getInt("veggie_id"));
veggie.setName(result.getString("name"));
veggie.setPrice(result.getString("price"));
veggie.setCreated_date(result.getDate("created_date"));
list.add(veggie);
}
}
return list;
}
}
Manifest.mf code:
Manifest-Version: 1.0
Netbeans config
Part of Standalone

How can I list included source files of a page?

I am trying to list all jsf files that are included (e.g. via ui:include) in the current page. I was hoping that I can find that information somehow on each UIComponent so that I just had to iterate over all UIComponents on that page and add the source file to a set but I can't find anything that would give me the source file.
Any ideas?
Kukeltje's suggestion to check out BalusC's (who else?) post Obtaining Facelets templates/files from an external filesystem or database was the answer.
So in order to list all includes for the page that is being loaded use the following:
As I am using JSF 2.1 here is my solution:
import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import javax.faces.FacesException;
import javax.faces.view.facelets.ResourceResolver;
import org.jboss.seam.log.Log;
import org.jboss.seam.log.Logging;
public class FacesResourceResolver extends ResourceResolver {
private ResourceResolver parent;
public FacesResourceResolver(ResourceResolver parent) {
this.parent = parent;
}
private static final Log log = Logging
.getLog(FacesResourceResolver.class);
#Override
public URL resolveUrl(String path) {
URL url = parent.resolveUrl(path);
log.info("Resource #0", path);
return url;
}
}
And add the following to web.xml
<context-param>
<param-name>javax.faces.FACELETS_RESOURCE_RESOLVER</param-name>
<param-value>com.locuslive.odyssey.developer.FacesResourceResolver</param-value>
</context-param>

How to get selectonemenu value after ajax process [duplicate]

This question already has answers here:
Validation Error: Value is not valid
(3 answers)
Closed 6 years ago.
I know this seems to be a common one, but I'm lost with it. Occurs on clicking the Add button in assessment.jsf. Anyway, I've attached what I think are the relevant sections.
FWIW, AssessmentType.equals() isn't triggered when I debug.
Thanks in advance.
j_idt38:j_idt47:j_idt48: Validation Error: Value is not valid
assessment.xhtml:
<h:form>
<h:selectOneMenu value="#{assessmentBean.assessmentField}">
<f:selectItems value="#{assessmentBean.assessment.type.fields}" />
</h:selectOneMenu>
<h:commandButton value="Add" action="#{assessmentBean.doAddField}">
<f:param name="assessmentId"
value="#{assessmentBean.assessment.id}" />
</h:commandButton>
</h:form>
assessment.jsf:
<form id="j_idt38:j_idt47" name="j_idt38:j_idt47" method="post" action="/jsf-web/edit/assessment.jsf" enctype="application/x-www-form-urlencoded">
<input type="hidden" name="j_idt38:j_idt47" value="j_idt38:j_idt47" />
<select name="j_idt38:j_idt47:j_idt48" size="1"> <option value="1">Presenting Condition</option>
<option value="2">Problem Duration</option>
</select>
<script type="text/javascript" src="/jsf-web/javax.faces.resource/jsf.js.jsf?ln=javax.faces"></script>
<input type="submit" name="j_idt38:j_idt47:j_idt50" value="Add" onclick="mojarra.jsfcljs(document.getElementById('j_idt38:j_idt47'),{'j_idt38:j_idt47:j_idt50':'j_idt38:j_idt47:j_idt50','assessmentId':'1'},'');return false" /><input type="hidden" name="javax.faces.ViewState" id="javax.faces.ViewState" value="3431661972220941645:6952134510589038883" autocomplete="off" />
</form>
AssessmentType.java:
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import javax.validation.constraints.NotNull;
import lombok.Data;
import org.hibernate.envers.Audited;
#Audited
#Data
#Entity
public class AssessmentType implements Comparable<AssessmentType> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
private String name;
#OneToMany( fetch=FetchType.EAGER, cascade = {CascadeType.PERSIST, CascadeType.MERGE}, targetEntity=AssessmentField.class )
private List<AssessmentField> fields;
#Override
public int compareTo(final AssessmentType o) {
return getId().compareTo(o.getId());
}
#Override
public String toString() {
return getName();
}
}
AssessmentFieldConverter.java
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;
import javax.faces.convert.FacesConverter;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import com.htu.fizio.api.AssessmentFieldManager;
import com.htu.fizio.domain.AssessmentField;
#FacesConverter(forClass = AssessmentField.class)
public class AssessmentFieldConverter implements Converter {
AssessmentFieldManager<AssessmentField> assessmentFieldManager;
#SuppressWarnings({ "unchecked", "rawtypes" })
#Override
public Object getAsObject(FacesContext ctx, UIComponent component, String value) {
try {
final InitialContext ic = new InitialContext();
assessmentFieldManager = (AssessmentFieldManager) ic.lookup("fizio/AssessmentFieldManagerImpl/local");
return assessmentFieldManager.find(Long.valueOf(value));
} catch (NamingException e) {
e.printStackTrace();
}
return null;
}
#Override
public String getAsString(FacesContext ctx, UIComponent component, Object value) {
return String.valueOf(((AssessmentField) value).getId());
}
}
AssessmentBean.java
import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.EJB;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
import lombok.Getter;
import lombok.Setter;
import com.htu.fizio.api.AssessmentManager;
import com.htu.fizio.domain.Assessment;
import com.htu.fizio.domain.AssessmentField;
import com.htu.fizio.domain.AssessmentFieldValue;
import com.htu.fizio.jsf.faces.FacesUtil;
...
#PostConstruct
public void init() {
if (FacesUtil.containsKey("assessmentId")) {
final Long id = Long.parseLong(FacesUtil.get("assessmentId"));
assessment = assessmentManager.find(id);
} else {
assessment = new Assessment();
}
}
public String doAddField() {
final AssessmentFieldValue value = new AssessmentFieldValue();
value.setField(assessmentField);
value.setValue("");
assessment.getFieldValues().add(value);
assessmentManager.save(assessment);
return "/edit/assessment";
}
Edit:
Just noticed this when debugging, is it a likely suspect?:
Daemon Thread [HandshakeCompletedNotify-Thread] (Suspended (exception ConcurrentModificationException))
HashMap$EntryIterator(HashMap$HashIterator<E>).nextEntry() line: 793
HashMap$EntryIterator.next() line: 834
HashMap$EntryIterator.next() line: 832
SSLSocketImpl$NotifyHandshakeThread.run() line: 2214
Validation Error: Value is not valid
To the point, this error means that the selected item does not match any of the items available in the list. I.e. the object represented by the selected item value has never returned true on its equals() call with any of the available select items.
There are only two causes for this problem:
The equals() method of the object type in question is broken.
The contents of the list of items is different during the validations phase of the form submit request than as it was during the render response phase of the initial request to display the form.
Since the first seems to be properly implemented -as per the comments-, the only cause left is the second. Assuming that you're nowhere doing business logic in a getter method, an easy test is to put the #{assessmentBean} in the session scope. If it works, then the data (pre)loading logic of the list of select items is definitely wrong.
The validation is failing because after your converter converts the String representation of AssessmentType back to an object, JSF iterates over the existing values (assessmentBean.assessment.type.fields) and compares this recently converted object with all those existing ones.
Since you did not implement Object#equals for AssessmentType, it will default to an object identity comparison (roughly spoken, the memory address of your object) , which will of course fail.
The solution is thus to either implement Object#equals, or let the converter get the object from assessmentBean.assessment.type.fields instead of from AssessmentTypeManager.
I think I've resolved this, at least, I've moved on to the next error!
Despite posting reams of code I'd not posted the full xhtml in which there were multiple and nested form tags. Just the one form seems to allow passing the assessmentId parameter which in turn allows the AssessmentBean to then populate the List of AssessmentFields for the assessment type correctly.
Thanks for all the help.

JSF injected sessionscoped bean's method invocation become null pointer

I use CDI to annotate beans. One bean called SessionManager holds the logined user information with the declaration:
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import javax.ejb.Stateful;
#Stateful
#Named
#SessionScoped
public class SessionManagerImpl implements SessionManager, Serializable {
...
public UserDto getLoginedUser() {
...
}
}
And the other is called DashboardController as:
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
import javax.inject.Inject;
#Named
#RequestScoped
public class DashboardController implements Serializable {
#Inject
private SessionManager sessionManager;
...
public void loadUserInfo() {
...
UserDto userDto = sessionManager.getLoginedUser();
}
}
The first time i open a page refer DashboardController, it works well. And if i continue to use the website, it still works. But if i don't click any page for some minutes, and come back to open the page, it will display a null pointer for the javassist$$getLoginedUser method invocation (sessionManager is not null when i use debug to watch). The session is still valid for i can get values from session map directly using faces context.
What's wrong with the SessionManager? Thanks.
This occurs because your Stateful Session Bean (EJB) has passivated, and is not reintroduced to your session. If there isn't a strong need to make your session scoped object a session bean, I would just make it a SessionScoped managed bean.

Proper place to put initialization code in JSF?

Where is the proper 'place' in JSF to put initialisation snippet that follows, in order to get it executed just one time when the server starts?
1. ExternalContext extContext = FacesContext.getCurrentInstance().getExternalContext();
2. HttpSession sesion = (HttpSession)extContext.getSession(true);
3. String parA = extContext.getInitParameter("parA");
4. String parB = someCalculations(parA);
5. sesion.setAttribute("parB", parB);
Basically I want to read a parameter parA from web.xml context-param section, do some transformations, and include it in session (as new parB parameter).
PostConstructApplicationEvent and eager=true techniques doesn't works because session is null at this point (line 4).
ServletContextListener technique doesn't works because FacesContext isn't available.
Thanks!
There are no sessions at application start time; this requirement is impossible to meet.
I interpret your requirements as:
perform an expensive application-scope calculation
inject this application-scope result into other scopes
The JSF way to do this is via managed beans. Here is an application-scope bean to perform the one-time transformation of the context parameter:
package foo;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
#ManagedBean
#ApplicationScoped
public class SomeCalculationsBean {
#ManagedProperty("#{initParam.paraA}")
private String paraA;
private String someCalculation;
public String getParaA() {
return paraA;
}
public void setParaA(String paraA) {
this.paraA = paraA;
this.someCalculation = //do some transformation
}
public String getSomeCalculation() {
return someCalculation;
}
}
This value can then be injected into other scopes as you need it:
package foo;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.SessionScoped;
#ManagedBean
#SessionScoped
public class SomeSessionBean {
#ManagedProperty("#{someCalculationsBean.someCalculation}")
private String paraB;
public String getParaB() {
return paraB;
}
public void setParaB(String paraB) {
this.paraB = paraB;
}
}
Code untested. This implementation assumes JSF annotation support but you can do the same thing with faces-config.xml bean configuration.

Resources