This is a sample from mkyong.com that I slightly modified. I added an inputtext and command
to send the next offset for paging in mysql. The first page autoloads with an offset of 0 as expected. If I type 5 in the inputtext, it actually works, and the next page displays the next 5 records. However, if I now enter 10, it stops working and page just keeps trying to load. I waited 5 minutes, nothing. Another retry, 0 first on load entered 15 just to test, it worked. But trying to make it work after first use of the commandButton, it just stalls.
In the url is displayed a current sessionid. Is this a session problem, or a configuration problem?
I'm new to jsf, and am trying to learn how to properly send request through to make a page display something. I got the inputText and commandButton idea direct from the javaeetutorial6 on oracles site, the guessnumber/duke example.
package model;
//import java.util.Date;
public class Customer{
public String petid;
public String petname;
public String tmpvar;
private String offset;
//public String address;
//public Date created_date;
//private String searchText;
//public String getSearchText() { return searchText; }
//public void setSearchText(String s) { searchText = s; }
public String getpetid() {
return petid;
}
public void setpetid(String petid) {
this.petid = petid;
}
public String getpetname() {
return petname;
}
public void setpetname(String petname) {
this.petname = petname;
}
/*public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Date getCreated_date() {
return created_date;
}
public void setCreated_date(Date created_date) {
this.created_date = created_date;
}*/
public String gettmpvar() {
return tmpvar;
}
public void settmpvar(String tmpvar) {
this.tmpvar = tmpvar;
}
}
package cust;
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.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.http.HttpServletRequest;
import javax.sql.DataSource;
import model.Customer;
#ManagedBean(name="Customer")
//#SessionScoped
public class CustomerBean implements Serializable{
int userNumber;
String offset;
//String SearchText;
//resource injection
#Resource(name="jdbc/petback2")
private DataSource ds;
//if resource injection is not support, you still can get it manually.
/*public CustomerBean(){
try {
Context ctx = new InitialContext();
ds = (DataSource)ctx.lookup("jdbc/petback2");
} catch (NamingException e) {
}
}*/
//connect to DB and get customer list
public String searchText;
//private String offset;
public String getSearchText() { return searchText; }
public void setSearchText(String s) { searchText = s; }
public List<Customer> getCustomerList() throws SQLException{
int rowsperpage = 5;
//String offset;
//HttpServletRequest request = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
//offset = request.getParameter("offset");
//if ( offset == null ? "" == null : offset.equals(""))
//if (offset null ? "" == null : offset.equals("0")
//{
//getoffset();
//String voffset;
//voffset = offset;
if (offset == null)
{
offset = "0";
}
System.out.println(offset);
//}
//int pageno = 0;
//int offset = 5;
//offset = "5";
//offset = CustomerBean.this.searchText;
//offset = getResponse();
if(ds==null)
throw new SQLException("Can't get data source");
//get database connection
Connection con = ds.getConnection();
if(con==null)
throw new SQLException("Can't get database connection");
PreparedStatement ps
= con.prepareStatement(
"select petid, petname from pets LIMIT "+ offset + ", " + rowsperpage);
//"select petid, petname from pets LIMIT "+ offset + ", " + rowsperpage);
//get customer data from database
ResultSet result = ps.executeQuery();
List<Customer> list = new ArrayList<Customer>();
//Customer cust2 = new Customer();
while(result.next()){
Customer cust2 = new Customer();
cust2.setpetid(result.getString("petid"));
cust2.setpetname(result.getString("petname"));
//cust2.setAddress(result.getString("address"));
//cust2.setCreated_date(result.getDate("created_date"));
//store all data into a List
list.add(cust2);
}
//List<Customer> list1 = new ArrayList<Customer>();
//Customer cust3 = new Customer();
Customer cust2 = new Customer();
cust2.settmpvar("hello");
list.add(cust2);
return list;
}
public void setoffset(String user_number) {
this.offset = user_number;
System.out.println(offset);
}
public String getoffset() {
return offset;
}
}
newjsf.html
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<h:outputStylesheet library="css" name="table-style.css" />
<script type="text/javascript" src="include/jquery.js"></script>
<script type="text/javascript" src="include/myjq.js"></script>
</h:head>
<h:body>
<h:form>
<h:dataTable id="myTable" value="#{Customer.customerList}" var="c" border="1"
styleClass="order-table"
headerClass="order-table-header"
rowClasses="order-table-odd-row,order-table-even-row"
>
<h:column>
<f:facet name="header">
petid
</f:facet>
#{c.petid}
</h:column>
<h:column>
<f:facet name="header">
petname
</f:facet>
#{c.petname}
</h:column>
</h:dataTable>
<h:inputText
id="userNo"
value="#{Customer.offset}">
</h:inputText>
<h:commandButton id="submit" value="Submit"
action="newjsf.xhtml"/>
</h:form>
</h:body>
</html>
config:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
<!--<url-pattern>/faces/*</url-pattern>
<url-pattern>/faces/*</url-pattern>-->
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/newjsf.xhtml</welcome-file>
</welcome-file-list>
</web-app>
Got it working, changed over to ui:repeat, and used the below to send gets
instead of post:
<h:outputLink id="link1" value="newui.xhtml?voffset=#{Customer.offset - 5}">
<h:outputText value="prev" />
</h:outputLink>
<h:outputLink id="link2" value="newui.xhtml?voffset=#{Customer.offset + 5}">
<h:outputText value="next" />
</h:outputLink>
And in the bean:
HttpServletRequest req = (HttpServletRequest)FacesContext.getCurrentInstance().getExternalContext().getRequest();
offset = req.getParameter("voffset");
if (offset == null) {
offset = "0";
}
and,
public void setoffset(String voffset) {
this.offset = voffset;
//System.out.println(offset);
}
public String getoffset() {
return offset;
}
I don't know how, but the set/get works without a call to it, probably auto handled.
Anyway now paging works like a champ, and more control than a datatable.
Related
I'm using Netbeans 7.2.1 and GlassFish 3.1.
I created web application using JSF, ejb classes and JDBC data source.
xhtml pages reference backing managed beans, which call local interface functions on ejb classes which run queries through the data source, directly getting connection and executing queries.
The project builds successfully, but when I run the project, browser shows error "No data received", and browser tab title says failed to load. I think maybe I have some missing configurations, cause when I run same project with no reference to managed beans (and hence not to ejb's and database) , there's no such message.
Frankly I got lost in what configuration files are needed for such a project, and what is needed to configure there. I saw numerous explanations, each saying something else, and I'm not clear which one is relevant here. If you could point me to some clear relevant explanation, I'd be grateful.
Do I need to configure for this project somewhere data source? ejb classes? anything else?
web.xml :
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
beans.xml :
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/beans_1_0.xsd">
</beans>
index.xhtml :
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<title>Movie Tickets Order </title>
</h:head>
<h:body>
<h:panelGrid columns="2" rendered="#{!UserBean.loggedIn}">
<h:outputLabel for="username" value="Username:"></h:outputLabel>
<h:inputText id="username" value="#{UserBean.username}"/>
<h:outputLabel for="password" value="Password: "></h:outputLabel>
<h:inputSecret id="password" value="#{UserBean.password}"/>
</h:panelGrid>
<h:commandButton value="Login" action="#{UserBean.login}" rendered="#{!UserBean.loggedIn}"/>
<h:commandButton value="Logout" action="#{UserBean.logout}" rendered="#{UserBean.loggedIn}"/>
<h:outputLink value="EditMovie" rendered="#{UserBean.isAdmin}"> Add/Edit Movie </h:outputLink>
</h:body>
UserBean
import TicketsEJB.UserejbLocal;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.io.Serializable;
import javax.ejb.EJB;
#Named(value = "UserBean")
#SessionScoped
public class UserBean implements Serializable {
private static final long serialVersionUID = 20130908L;
private String username;
private String password;
private String status;
private boolean exist = false;
private boolean loggedIn = false;
private final String statusAdmin = "admin";
private final String statusUser = "user";
#EJB
UserejbLocal userejb;
public boolean isAdmin() {
return status.equals(statusAdmin);
}
public void setLoggedIn(boolean loggedIn) {
this.loggedIn = loggedIn;
}
public boolean isLoggedIn() {
return loggedIn;
}
public void login() {
status = userejb.getUser(username, password);
exist = (status == null) ? false : true;
if (exist) {
//render "Hello user"
if (status.equals(statusAdmin)) {
loggedIn=true;
//render admin part:
}
} else {
//render "Sorry, wrong credentials"
}
password = null;
}
....
Userejb class:
#Stateful
#Local(UserejbLocal.class)
public class Userejb implements UserejbLocal {
private Connection connection = null;
private PreparedStatement getUser = null;
private PreparedStatement addUser = null;
private PreparedStatement getUserSalt = null;
private boolean exist;
private String status;
#Resource( name = "jdbc/Movies")
DataSource dataSource;
#PostConstruct
#Override
public void prepareStatements() {
try {
if (dataSource == null) {
throw new SQLException("Unable to obtain DataSource");
}
connection = dataSource.getConnection();
if (connection == null) {
throw new SQLException("Unable to connect to DataSource");
}
try {
getUser = connection.prepareStatement(
"SELECT STATUS "
+ "FROM Users"
+ "WHERE NAMEU= ? and HASHP=?");
addUser = connection.prepareStatement(
"insert into Users values ('?','?','?','?')");
getUserSalt = connection.prepareStatement(
"SELECT SALTP "
+ "FROM Users"
+ "WHERE NAMEU= ? ");
} catch (SQLException sqlException) {
sqlException.printStackTrace();
System.exit(1);
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
System.exit(1);
}
}
#Override
public void addUser(String name, String password, String status) {
String salt = Security.salt();
try {
addUser.setString(1, name);
addUser.setString(2, Security.hash(password + salt));
addUser.setString(3, salt);
addUser.setString(4, status);
addUser.executeUpdate();
} catch (SQLException ex) {
Logger.getLogger(Userejb.class.getName()).log(Level.SEVERE, null, ex);
}
}
....
UserejbLocal interface :
public interface UserejbLocal {
void prepareStatements();
void addUser(String name, String password, String status);
public java.lang.String getUser(java.lang.String name, java.lang.String password);
}
Thanks for the help!
The problem was SQLSyntaxErrorException. Just needed to look at server log (output tab , glassfish server tab) to see what was the problem. Fixing SQL syntax rendered the page correctly.
You are missing a space between Users and WHERE in your query. This is causing the query to be parsed as:
SELECT STATUS FROM UsersWHERE NAMEU ...............
i want to create dynamic textbox in jsf2 in datatable having textboxes based on clicking add row button. Iam a newbie for jsf programming.Can someone tell me a basic example for dynamic for generation . I have read ui:repeatand c:foreach but i need some practical example.
For your sample,
xhtml code:
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
</h:head>
<h:body>
<h:form id="form1">
<h:commandButton value="Add new Row" actionListener="#{myBean.addNewEmployee}"/>
<h:dataTable value="#{myBean.employeeList}" var="emp">
<h:column>
<f:facet name="header">
Employee Id
</f:facet>
#{emp.empId}
</h:column>
<h:column>
<h:inputText value="#{emp.empName}"/>
</h:column>
</h:dataTable>
</h:form>
</h:body>
</html>
jsf manged bean
#ManagedBean
#ViewScoped
public class MyBean implements Serializable {
List<Employee> employeeList;
public List<Employee> getEmployeeList() {
return employeeList;
}
public void setEmployeeList(List<Employee> employeeList) {
this.employeeList = employeeList;
}
public void addNewEmployee(ActionEvent event) {
employeeList.add(new Employee(employeeList.size(), null));
}
#PostConstruct
public void init() {
employeeList = new ArrayList<Employee>();
employeeList.add(new Employee(1, "Emp1"));
employeeList.add(new Employee(2, "Emp2"));
}
public MyBean() {
}
}
Employee Class(You can use your entity class)
public class Employee {
Integer empId;
String empName;
public Integer getEmpId() {
return empId;
}
public void setEmpId(Integer empId) {
this.empId = empId;
}
public String getEmpName() {
return empName;
}
public void setEmpName(String empName) {
this.empName = empName;
}
public Employee(Integer empId, String empName) {
this.empId = empId;
this.empName = empName;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
final Employee other = (Employee) obj;
if (this.empId != other.empId && (this.empId == null || !this.empId.equals(other.empId))) {
return false;
}
return true;
}
#Override
public int hashCode() {
int hash = 5;
hash = 41 * hash + (this.empId != null ? this.empId.hashCode() : 0);
return hash;
}
}
You can directly use above code. And also I suggest to use PrimeFaces component for advanced manipulations
I'm trying execute the DataTable example avaiable on Primefaces Showcase. All functions works but when i select a row, the value of the selected row isn't displayed on my <p:dialog>.
I've already checked all alternatives and nothing works. Could someone help me?
I'm using Primefaces 3.3 and glassfish 3.0.1. Here goes my code:
dataTableComplex.xhtml
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
</h:head>
<body>
<h:form id="form">
<p:dataTable var="car" value="#{tableBean.cars}" rowKey="#{car.model}" paginator="true" rows="10"
selection="#{tableBean.selectedCar}" selectionMode="single" id="carsTable">
<p:ajax event="rowSelect" update=":form:display" oncomplete="carDialog.show()" />
<f:facet name="header">
List of Cars
</f:facet>
<p:column headerText="Model" sortBy="#{car.model}" filterBy="#{car.model}" id="model">
#{car.model}
</p:column>
<p:column headerText="Year" sortBy="#{car.year}" filterBy="#{car.year}" id="year">
#{car.year}
</p:column>
<p:column headerText="Manufacturer" sortBy="#{car.manufacturer}" filterBy="#{car.manufacturer}" id="manufacturer">
#{car.manufacturer}
</p:column>
<p:column headerText="Color" sortBy="#{car.color}" filterBy="#{car.color}" id="color">
#{car.color}"
</p:column>
</p:dataTable>
<p:dialog header="Car Detail" widgetVar="carDialog" resizable="false"
width="200" showEffect="explode" hideEffect="explode">
<h:panelGrid id="display" columns="2" cellpadding="4">
<h:outputText value="Model:" />
<h:outputText value="#{tableBean.selectedCar.model}" id="model"/>
<h:outputText value="Year:" />
<h:outputText value="#{tableBean.selectedCar.year}" id="year"/>
<h:outputText value="Manufacturer:" />
<h:outputText value="#{tableBean.selectedCar.manufacturer}" id="manufacturer"/>
<h:outputText value="Color:" />
<h:outputText value="#{tableBean.selectedCar.color}" id="color"/>
</h:panelGrid>
</p:dialog>
</h:form>
</body>
</html>
TableBean.java
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
#ViewScoped
#ManagedBean(name = "tableBean")
#SessionScoped
public class TableBean implements Serializable {
private final static String[] colors;
private final static String[] manufacturers;
static {
colors = new String[10];
colors[0] = "Black";
colors[1] = "White";
colors[2] = "Green";
colors[3] = "Red";
colors[4] = "Blue";
colors[5] = "Orange";
colors[6] = "Silver";
colors[7] = "Yellow";
colors[8] = "Brown";
colors[9] = "Maroon";
manufacturers = new String[10];
manufacturers[0] = "Mercedes";
manufacturers[1] = "BMW";
manufacturers[2] = "Volvo";
manufacturers[3] = "Audi";
manufacturers[4] = "Renault";
manufacturers[5] = "Opel";
manufacturers[6] = "Volkswagen";
manufacturers[7] = "Chrysler";
manufacturers[8] = "Ferrari";
manufacturers[9] = "Ford";
}
private List<Car> cars;
private Car selectedCar;
private Car[] selectedCars;
public TableBean() {
cars = new ArrayList<Car>();
populateRandomCars(cars, 50);
}
public Car getSelectedCar() {
return selectedCar;
}
public void setSelectedCar(Car selectedCar) {
this.selectedCar = selectedCar;
}
private void populateRandomCars(List<Car> list, int size) {
for(int i = 0 ; i < size ; i++)
list.add(new Car(getRandomModel(), getRandomYear(), getRandomManufacturer(), getRandomColor()));
}
private int getRandomYear() {
return (int) (Math.random() * 50 + 1960);
}
private String getRandomColor() {
return colors[(int) (Math.random() * 10)];
}
private String getRandomManufacturer() {
return manufacturers[(int) (Math.random() * 10)];
}
private String getRandomModel() {
return UUID.randomUUID().toString().substring(0, 8);
}
public List<Car> getCars() {
return cars;
}
}
Car.java
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.faces.bean.ManagedBean;
#ManagedBean(name = "car")
#SessionScoped
public class Car implements Serializable {
private String model;
private int year;
private String manufacturer;
private String color;
private int price;
public Car(){
}
public Car(String model, int year, String manufacturer, String color) {
this.model = model;
this.year = year;
this.manufacturer = manufacturer;
this.color = color;
}
public Car(String model, int year, String manufacturer, String color, int price) {
this.model = model;
this.year = year;
this.manufacturer = manufacturer;
this.color = color;
this.price = price;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
public String getManufacturer() {
return manufacturer;
}
public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
#Override
public boolean equals(Object obj) {
if(obj == null)
return false;
if(!(obj instanceof Car))
return false;
Car compare = (Car) obj;
return compare.model.equals(this.model);
}
#Override
public int hashCode() {
int hash = 1;
return hash * 31 + model.hashCode();
}
#Override
public String toString() {
return "Car{" + "model=" + model + ", year=" + year + ", manufacturer=" + manufacturer + ", color=" + color + ", price=" + price + '}';
}
}
Edited: to solve this problem just add #ViewScoped on TableBean.java.
Your TableBean should be ViewScoped.
Add #ViewScoped on top of TableBean or configure it using faces-config.xml file.
You are using the example from the Showcase Labs, which is running on PrimeFaces version 3.4 (still in development at time of posting).
Since you are using PrimeFaces 3.3, you should be using the examples from the common Showcase.
Remember that the Labs version of the Showcase is always running on the still-on-development versions, while the common Showcase is always on the lastest final release.
You can always see what version is running behind the Showcase by checking the bottom of the page.
Since class Car is just a common class, not a manage bean, You don't need the declaration:
#ManagedBean(name = "car")
#SessionScoped
I am working on a project where Administrator selects a movie from a list. Then the data of the movie are displayed in inputTexts, so the admin can change it and onblur with ajax updates the database.
I created a bean in order to select the right data and display them in the inputTexts.
Thats ok. Now, I dont know how to allow the inputText to refer to the second bean where i have the update queries..
UPDATED
The Select Bean.
package Beans;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* #author Vasilis
*/
#ManagedBean
#RequestScoped
public class Select {
Connection con;
Statement statement;
String query;
private List perInfoAll = new ArrayList();
public List getperInfoAll() {
int i = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "Bill", "1989");
statement = con.createStatement();
query = "SELECT NAME,SURNAME FROM AJAX";
ResultSet resultset = statement.executeQuery(query);
while (resultset.next()) {
perInfoAll.add(i, new Select.perInfo(resultset.getString(1), resultset.getString(2)));
i++;
}
} catch (Exception e) {
System.out.println("Error Data : " + e.getMessage());
}
return perInfoAll;
}
public class perInfo {
String NAME;
String SURNAME;
public perInfo(String NAME, String SURNAME) {
this.NAME = NAME;
this.SURNAME = SURNAME;
}
public String getNAME() {
return NAME;
}
public String getSURNAME() {
return SURNAME;
}
}
}
The Update Bean
package Beans;
import java.sql.*;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
/**
*
* #author Vasilis
*/
#ManagedBean
#RequestScoped
public class Update {
Statement statement;
Connection con;
String query1;
String query2;
ResultSet resultset1;
ResultSet resultset2;
String NewName;
String NewSurname;
public void setNewSurname(String NewSurname) {
this.NewSurname = NewSurname;
}
public void setNewName(String NewName) {
this.NewName = NewName;
}
public String getNewSurname() {
return NewSurname;
}
public String getNewName() {
return NewName;
}
public void DatabaseConnection(String NewName) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException error) {
System.err.println("Error:Unable to load");
}
try {
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "BILL", "1989");
statement = con.createStatement();
query1 = "UPDATE AJAX SET NAME = ('" + NewName + "')";
resultset1 = statement.executeQuery(query1);
resultset1.next();
} catch (SQLException error1) {
System.err.println("Mistake");
}
}
public String updateit() {
DatabaseConnection(NewName);
return "ok";
}
public void DatabaseConnection1(String NewSurname) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException error) {
System.err.println("Error:Unable to load");
}
try {
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "BILL", "1989");
statement = con.createStatement();
query2 = "UPDATE AJAX SET SURNAME = ('" + NewSurname + "')";
resultset2 = statement.executeQuery(query2);
resultset2.next();
} catch (SQLException error1) {
System.err.println("Mistake");
}
}
public String updateit1() {
DatabaseConnection1(NewSurname);
return "ok";
}
}
The index.xhtml
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<link rel="stylesheet" type="text/css" href="my.css" />
</h:head>
<h:body>
<h:form>
<h:inputText value="#{update.newName}" required="true" >
<f:ajax event="blur" render="#this" listener="#{update.updateit}" />
</h:inputText>
<h:inputText value="#{update.newSurname}" required="true" >
<f:ajax event="blur" render="#this" listener="#{update.updateit1}" />
</h:inputText>
</h:form>
</h:body>
So i want in index.xhtml to get the values from the select bean and when updated the value will sent to update bean
You should do something like this...
assign the inputText to a variable name in the bean class as -
private String myData;
//getters and setters.
public void updateData(ActionEvent e)
{
//put your query here to update to the database.
}
and in your web file do like this -
<h:inputText value="#{bean.myData}">
<a4j:support event="onblur" actionListener="#{bean.updateData}"/>
</h:inputText>
Show your list as you were showing, and after onblur it will directly update this value to the database by calling a function described above.
Hope it clears your doubt.
I am developing an application using jsf2.0, richfaces 4.0, tomcat 6.0. On a page I am trying to delete a row . But when I click the delete icon, sometimes popup panel does not appear and when it is shown , nothing happens on clicking the delete button.
Following is my .xhtml file:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:c="http://java.sun.com/jsp/jstl/core"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:a4j="http://richfaces.org/a4j"
xmlns:rich="http://richfaces.org/rich">
<ui:composition template="template.xhtml">
<ui:define name="metadata">
<f:metadata>
<f:viewParam name="meetingId" required="true" value="#{meetingBean.selectedMeetId}" />
</f:metadata>
</ui:define>
<ui:define name="content">
<h3>List of Employees in selected meeting</h3>
<a4j:status onstart="#{rich:component('statPane')}.show()"
onstop="#{rich:component('statPane')}.hide()" />
<h:form>
<c:if test="#{! empty meetingBean.selectedMeeting}">
<c:set target="#{flash}" property="selectedMeeting"
value="#{meetingBean.selectedMeeting}" />
</c:if>
<c:if test="#{! empty flash.selectedMeeting}">
<c:set target="#{meetingBean}" property="selectedMeeting"
value="#{flash.selectedMeeting}" />
</c:if>
<rich:extendedDataTable value="#{meetingBean.selectedMeeting.employees}" var="empMeet" border="1" id="table">
<rich:column>
<f:facet name="header">Employee Id</f:facet>
#{empMeet.empId}
</rich:column>
<rich:column>
<f:facet name="header"> Employee Name</f:facet>
#{empMeet.firstName} #{empMeet.lastName}
</rich:column>
<rich:column>
<a4j:commandLink execute="#this" render="#none" oncomplete="#{rich:component('confirmPanel')}.show();">
<h:graphicImage value="/images/icons/delete.gif" alt="delete" />
<a4j:param value="#{empMeet.empId}" assignTo="#{meetingBean.deleteEmpId}" />
</a4j:commandLink>
</rich:column>
</rich:extendedDataTable>
<a4j:jsFunction name="removeEmp" action="#{meetingBean.deleteEmployee}" render="table" execute="#this"
oncomplete="#{rich:component('confirmPanel')}.hide();" >
</a4j:jsFunction>
<rich:popupPanel id="statPane" autosized="true">
<h:graphicImage value="/images/ai.gif" />
Please wait...
</rich:popupPanel>
<rich:popupPanel id="confirmPanel" autosized="true" >
Are you sure you want to delete the row?
<a4j:commandButton value="Cancel" onclick="#{rich:component('confirmPane')}.hide(); return false;" />
<a4j:commandButton value="Delete" onclick="removeEmp(); return false;" />
</rich:popupPanel>
<h:commandButton action="addEmpMeeting" value="Invite More Employees" />
</h:form>
</ui:define>
</ui:composition>
</html>
Following is my bean class:
package com.drishti.apps.mommanager.meeting;
/**
* this class represents a meeting object
*/
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.event.ComponentSystemEvent;
import javax.faces.model.DataModel;
import javax.faces.model.ListDataModel;
import org.richfaces.component.SortOrder;
import com.drishti.apps.mommanager.employee.AbstractBacking;
import com.drishti.apps.mommanager.employee.EmployeeEntity;
import com.drishti.apps.mommanager.employee.EmployeeService;
#ManagedBean
public class MeetingBean extends AbstractBacking {
#ManagedProperty(value = "#{requestScope}")
private Map<String, Object> requestMap;
private int meetingId;
private Date meetingTime;
private String agenda;
private String result;
public String[] empIdsInMeeting;
private List<EmployeeEntity> employees = new ArrayList<EmployeeEntity>();
private Integer selectedMeetId;
private MeetingEntity selectedMeeting;
private String selectedAgenda;
private int deleteEmpId;
private EmployeeEntity deletableEmployee;
/**
* this method is used to load a meeting object when it is being updated
*
* #param cse
*/
public void loadMeeting(ComponentSystemEvent cse) {
if (null == getSelectedMeeting()) {
Integer meetId = getSelectedMeetId();
if (meetId == null) {
meetId = (Integer)getFlash().get("selectedMeetId");
}
if (meetId == null) {
getFacesContext().addMessage(null, new FacesMessage("The meeting is invalid"));
getFlash().setKeepMessages(true);
getFacesContext().getApplication().getNavigationHandler()
.handleNavigation(getFacesContext(), null, "listMeetings");
} else {
MeetingEntity meet = MeetingService.getCurrentInstance().getMeetingForId(meetId);
if (meet == null) {
getFacesContext().addMessage(null, new FacesMessage("The meeting is invalid"));
getFlash().setKeepMessages(true);
getFacesContext().getApplication().getNavigationHandler()
.handleNavigation(getFacesContext(), null, "listMeetings");
} else {
getFlash().put("selectedMeeting", meet);
getSelectedMeeting();
}
}
}
}
/**
* this method updates a meeting object
*
* #return
*/
public void updateMeeting() {
//String result = null;
MeetingService meetSer = MeetingService.getCurrentInstance();
MeetingEntity meeting = getSelectedMeeting();
meetSer.updateMeeting(meeting);
getFlash().clear();
//result = "meetUpdated";
//return result;
}
/**
* this method adds a meeting object to database
*
* #return
*/
public void addMeeting() {
MeetingEntity meeting = (MeetingEntity)getRequestMap().get("meetingEntity");
MeetingService.getCurrentInstance().addMeeting(meeting);
//return "successMeeting";
}
/**
* this method is used to delete a meeting
*/
public void deleteMeeting(){
MeetingService meetSer = MeetingService.getCurrentInstance();
MeetingEntity meeting = getSelectedMeeting();
meetSer.deleteMeeting(meeting);
getFlash().clear();
}
/**
* returns data model containing all meetings present in database
*
* #return
*/
public DataModel<MeetingEntity> getMeetingList() {
DataModel<MeetingEntity> meetingList = new ListDataModel<MeetingEntity>(MeetingService.getCurrentInstance()
.getMeetings());
return meetingList;
}
/**
* returns list containing agenda of all meetings
*
* #return
*/
public ArrayList<String> getAgendaList() {
ArrayList<String> agendaList = new ArrayList<String>();
agendaList.add(getSelectedMeeting().getAgenda());
return agendaList;
}
/**
* this method is used to get a list of employee names for employees who are not invited to a particular meeting
*/
public List<String> getEmpNameIdList() {
List<EmployeeEntity> employeeList = new ArrayList<EmployeeEntity>(EmployeeService.getCurrentInstance()
.getEmployeeList());
List<String> uninvitedEmpList = new ArrayList<String>();
ListIterator<EmployeeEntity> empIter = employeeList.listIterator();
ArrayList<Integer> idList = new ArrayList<Integer>();
while (empIter.hasNext()) {
idList.add(empIter.next().getEmpId());
}
MeetingEntity meeting = getSelectedMeeting();
List<EmployeeEntity> employees = meeting.getEmployees();
if(employees!=null){
ListIterator<EmployeeEntity> invitedIter = employees.listIterator();
ArrayList<Integer> invitedIds = new ArrayList<Integer>();
while (invitedIter.hasNext()) {
invitedIds.add(invitedIter.next().getEmpId());
}
idList.removeAll(invitedIds);
}
EmployeeEntity emp;
ListIterator<Integer> idIter = idList.listIterator();
while (idIter.hasNext()) {
int id = idIter.next();
emp = EmployeeService.getCurrentInstance().getEmployeeForId(id);
uninvitedEmpList.add(emp.getFirstName() + " " + emp.getLastName() + " (" + emp.getEmpId() + ")");
}
return uninvitedEmpList;
}
/**
* this method adds employees to a meeting
* #return
*/
public String addEmpToMeeting() {
MeetingEntity meeting = MeetingService.getCurrentInstance().getMeetingFromAgenda(
getSelectedMeeting().getAgenda());
for (int i = 0; i < empIdsInMeeting.length; i++) {
String id = null;
id = empIdsInMeeting[i].substring(empIdsInMeeting[i].lastIndexOf("(") + 1,
empIdsInMeeting[i].lastIndexOf(")"));
int empId = Integer.parseInt(id);
meeting.getEmployees().add(EmployeeService.getCurrentInstance().getEmployeeForId(empId));
}
MeetingService.getCurrentInstance().addMeeting(meeting);
return "empAddedToMeeting";
}
/**
* this method removes employee from a meeting
* #return
*/
public void deleteEmployee(){
List<EmployeeEntity>inviteEmployees=getSelectedMeeting().getEmployees();
EmployeeEntity emp=getDeletableEmployee();
inviteEmployees.remove(emp);
}
public Integer getSelectedMeetId() {
return selectedMeetId;
}
public void setSelectedMeetId(Integer selectedMeetId) {
this.selectedMeetId = selectedMeetId;
setSelectedMeeting(MeetingService.getCurrentInstance().getMeetingForId(selectedMeetId));
}
public MeetingEntity getSelectedMeeting() {
return selectedMeeting;
}
public void setSelectedMeeting(MeetingEntity selectedMeeting) {
this.selectedMeeting = selectedMeeting;
}
public Map<String, Object> getRequestMap() {
return requestMap;
}
public void setRequestMap(Map<String, Object> requestMap) {
this.requestMap = requestMap;
}
public Date getMeetingTime() {
return meetingTime;
}
public void setMeetingTime(Date meetingTime) {
this.meetingTime = meetingTime;
}
public String getAgenda() {
return agenda;
}
public void setAgenda(String agenda) {
this.agenda = agenda;
}
public String getResult() {
return result;
}
public void setResult(String result) {
this.result = result;
}
public int getMeetingId() {
return this.meetingId;
}
public List<EmployeeEntity> getEmployees() {
return employees;
}
public String[] getEmpIdsInMeeting() {
return empIdsInMeeting;
}
public void setEmpIdsInMeeting(String[] empIdsInMeeting) {
this.empIdsInMeeting = empIdsInMeeting;
}
public void setEmployees(List<EmployeeEntity> employees) {
this.employees = employees;
}
public String getSelectedAgenda() {
return selectedAgenda;
}
public void setSelectedAgenda(String selectedAgenda) {
this.selectedAgenda = selectedAgenda;
}
public void setTimeOrder(SortOrder timeOrder) {
this.timeOrder = timeOrder;
}
public int getDeleteEmpId() {
return deleteEmpId;
}
public void setDeleteEmpId(int deleteEmpId) {
this.deleteEmpId = deleteEmpId;
setDeletableEmployee(EmployeeService.getCurrentInstance().getEmployeeForId(deleteEmpId));
}
public EmployeeEntity getDeletableEmployee() {
return deletableEmployee;
}
public void setDeletableEmployee(EmployeeEntity deletableEmployee) {
this.deletableEmployee = deletableEmployee;
}
}
Please help .
The problem is probably related to JSF overriding your custom onclick.
The work-around would be to use onmousedown instead of onclick, with the potential caveat described here:
http://blogs.oracle.com/jtb/entry/jsf_h_commandlink_and_onclick
i had the same problem few days ago, changing the return to true may work for you.