getting null value from inputtext field and comandbutton not invoked action method in primefaces - primefaces

<h:form> <p:inputText id="uname" value="#{user.name}"/>
<p:inputText id="ac" value="#{user.account}"/>
<p:commandButton id="submit1" value="Submit" action="#{user.commandButtonAction}" /> ​
</h:form>
this is xhtml main code
backingbean is used managedbean and viewscoped annotation
#ManagedBean(name="user")
#ViewScoped
public class user {
private String account;
private String name;
public String getName() {
System.out.println(" name is ::"+ name);
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAccount() {
System.out.println("account no is:: "+ account);
return account;
}
}
public void setAccount(String account) {
this.account = account;
}
public void commandButtonAction() throws IOException{
System.out.println("succesful");
}

Related

PrimeFaces DataTable not displaying anything, as backing bean's methods are not called at all

I have a problem similar to the ones described here:
primefaces datatable not displaying anything
PrimeFaces DataTable "No records found" when there are records
my PrimeFaces datatable does not show any results, altough there are records in the database. Moreover: it seems that NO JAVA method is called when I request the page from the browser - at least the init() method of the backing bean seems not to be called at all
Where can the problem be? I would appreciate any help!
Thank you!
My template:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:p="http://primefaces.org/ui"
xmlns:c="http://java.sun.com/jsp/jstl/core">
<h:head>
<meta charset="UTF-8"/>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Bibliothek - Customers </title>
</h:head>
<h:body>
<h:form id="customersform">
<p:growl id="growl" life="2000" />
<p:panel header="All customers in the application" />
<p:dataTable id="customersTable" var="customer"
value="#{kundenBean.dataModel}" paginator="true" rows="10"
paginatorTemplate="{RowsPerPageDropdown} {FirstPageLink} {PreviousPageLink} {CurrentPageReport} {NextPageLink} {LastPageLink}"
resizableColumns="true" rowsPerPageTemplate="5,10,15"
selection="#{kundenBean.selektierterKunde}" selectionMode="single"
rowKey="#{customer.id}" lazy="true">
<p:column headerText="Customer's Name" style="width:332px;text-align:center"
sortBy="#{customer.vorname}" filterBy="#{customer.vorname}">
<h:outputText value="#{customer.vorname}" />
</p:column>
<p:column headerText="Customer's Address" sortBy="#{customer.adresse}"
filterBy="#{customer.adresse}">
<h:outputText value="#{customer.adresse}" />
</p:column>
</p:dataTable>
</h:form>
</h:body>
</html>
The Backing Bean:
#Named
#ViewScoped
public class KundenBean {
private Logger logger = Logger.getLogger(KundenBean.class.getName());
public static final String SELECTED_CUSTOMER = "selectedCustomer";
#Inject
private KundeDBService kundenDBService;
private LazyKundeDataModel dataModel;
private Kunde selektierterKunde;
private int selectedCustId;
#PostConstruct
private void init() {
this.dataModel = new LazyKundeDataModel(kundenDBService);
}
public LazyKundeDataModel getDataModel() {
return dataModel;
}
public void setDataModel(LazyKundeDataModel dataModel) {
this.dataModel = dataModel;
}
public Kunde getSelektierterKunde() {
return selektierterKunde;
}
public int getSelectedCustId() {
return selectedCustId;
}
public void setSelektierterKunde(Kunde selektierterKunde) {
this.selektierterKunde = selektierterKunde;
}
public void onRowSelect(SelectEvent event) {
selectedCustId = ((Kunde) event.getObject()).getId();
}
public void onRowDblClick(final SelectEvent event) {
selectedCustId = ((Kunde) event.getObject()).getId();
try {
ExternalContext extCtx = FacesContext.getCurrentInstance()
.getExternalContext();
extCtx.getFlash().put(SELECTED_CUSTOMER,((Kunde) event.getObject()));
FacesContext.getCurrentInstance().getExternalContext().redirect("rents.xhtml?custId=" +selectedCustId);
} catch (IOException e) {
e.printStackTrace();
logger.error(e.getMessage(), e);
}
}
}
The Data Model:
public class LazyKundeDataModel extends LazyDataModel<Kunde> {
private static final long serialVersionUID = 1L;
private KundeDBService kundeDBService;
public LazyKundeDataModel(KundeDBService kundeDBService) {
this.kundeDBService = kundeDBService;
}
#Override
public Kunde getRowData(String rowKey) {
return kundeDBService.getKundeById(Integer.valueOf(rowKey));
}
#Override
public Object getRowKey(Kunde kunde) {
return kunde.getId();
}
#Override
public List<Kunde> load(int first, int pageSize, String sortField, SortOrder sortOrder,
Map<String, Object> filters) {
List result = this.kundeDBService.load(first, pageSize, sortField, sortOrder, filters);
// rowCount
this.setRowCount(result.size());
this.setPageSize(pageSize);
return result;
}
}
The DB Service:
#Stateless
public class KundeDBService {
#PersistenceContext
private EntityManager em;
public static final String JOINING_OR = " OR ";
public static final String JOINING_AND = " AND ";
public static final String CONDITION_WHERE = " WHERE ";
private static Logger logger = Logger.getLogger(KundeDBService.class.getName());
public List<? extends Kunde> load(int first, int pageSize, String sortField, SortOrder sortOrder,
Map<String, Object> filters) {
List<? extends Kunde> result = new ArrayList<Kunde>();
String selectQUERY = " select k from Kunde k ";
if (filters.size() > 0) {
selectQUERY += addFiltersToQuery(filters);
}
if (sortField != null) {
selectQUERY += " order by k." + sortField;
if (sortOrder != null) {
selectQUERY += " " + (sortOrder);
}
}else { // sortField == null, default sort by customer's name
selectQUERY += " order by k.vorname asc";
}
Query emQuery = em.createQuery(selectQUERY);
emQuery.setFirstResult(first);
emQuery.setMaxResults(pageSize);
result = (List<Kunde>) emQuery.getResultList();
return result;
}
private String addFiltersToQuery(Map<String, Object> filters) {
if (filters.size() == 0)
return StringUtils.EMPTY;
StringBuilder whereCondition = new StringBuilder(CONDITION_WHERE);
int pseudoCounter = 0;
for (Entry<String, Object> entry : filters.entrySet()) {
whereCondition.append("k." + entry.getKey() + " LIKE :" + "x" + (++pseudoCounter));
whereCondition.append(JOINING_AND);
}
if (whereCondition.length() > CONDITION_WHERE.length()) {
whereCondition.delete(whereCondition.length() - JOINING_AND.length(), whereCondition.length());
}
return whereCondition.toString();
}
public Kunde getKundeById(int id) {
return em.find(Kunde.class, Integer.valueOf(id));
}
}
I solved the problem by replacing the annotation #Named by the annotation javax.faces.bean.ManagedBean on the KundenBean class. I am not sure what exactly the problem was, but I suppose that it has something to do with the problem outlined here
JSF View Scoped Bean Reconstructed Multiple Times
So, now the changed and working KundenBean class looks like this:
#ManagedBean (name = "kundenBean")
#ViewScoped
public class KundenBean {
//rest of the lines unchanged

Open details of a single row in a datatable in a new page

I have a datatable from database and I would like details of one of the rows appear in a new table when I click on the "OPEN" button as in the screenshot below.
When I click on the OPEN button I get "No records found " as in the next screenshot below
Here is part of the index.xhtml
//
APP WEB
<p:ajax event="rowEdit" listener="#{transaction.onRowEdit}" update=":form1:messages" />
<p:ajax event="rowEditCancel" listener="#{transaction.onRowCancel}" update=":form1:messages" />
<p:column headerText="Reference">
<p:commandLink value="#{c.reference}" action="/faces/global/SingleTx.xhtml" target="_blank" >
<f:setPropertyActionListener target="#{transaction.showSelectedTx(reference)}" value="#{c}" />
</p:commandLink>
</p:column>
<p:column headerText="Rartner">
#{c.pname}
</p:column>
<p:column headerText="Status">
#{c.fk_status}
</p:column>
<p:column headerText="Sender">
#{c.sendername}
</p:column>
<p:column headerText="Beneficiary">
#{c.beneficiaryname}
</p:column>
<p:column headerText="Amounts">
#{c.beneficiary_currency} #{c.beneficiary_amount}
</p:column>
<p:column headerText="Action">
<p:commandButton style="float:right" value="Print" >
<p:confirm header="#{cd.reference}" message="Are you sure?" icon="ui-icon-alert" />
<p:button value="Open" href="/faces/global/SingleTx.xhtml" target="_self" />
</p:commandButton>
</p:column>
<p:column style="width:32px">
<p:rowEditor />
</p:column>
</p:dataTable>
<p:dialog modal="true" width="800px" height="400px" widgetVar="singletx"
id="dialog">
Name :#{transaction.showSelectedTx(reference)}
</p:dialog>
</h:form>
Here is the backing bean:
package com.mycompany.data;
/**
*
* #author bryan
*/
import conn.DBConnector;
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;
#ManagedBean(name = "transaction")
#SessionScoped
public class TransactionBean implements Serializable {
//added
private static final long serialVersionUID = 1L;
public String reference;
public String fk_status;
public String sendername;
public String beneficiaryname;
public String beneficiary_currency;
public double beneficiary_amount;
public String pname;
Transaction user;
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getFk_status() {
return fk_status;
}
public void setFk_status(String fk_status) {
this.fk_status = fk_status;
}
public String getSendername() {
return sendername;
}
public void setSendername(String sendername) {
this.sendername = sendername;
}
public String getBeneficiaryname() {
return beneficiaryname;
}
public void setBeneficiaryname(String beneficiaryname) {
this.beneficiaryname = beneficiaryname;
}
public String getBeneficiary_currency() {
return beneficiary_currency;
}
public void setBeneficiary_currency(String beneficiary_currency) {
this.beneficiary_currency = beneficiary_currency;
}
public double getBeneficiary_amount() {
return beneficiary_amount;
}
public void setBeneficiary_amount(double beneficiary_amount) {
this.beneficiary_amount = beneficiary_amount;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
//resource injection
#Resource(name = "jdbc/primefaces")
//connect to DB and get customer list
public List<Transaction> getTransactionList() throws SQLException, ClassNotFoundException {
Connection con = null;
con = DBConnector.getDBConnection();
if (con == null) {
throw new SQLException("Can't get database connection");
}
PreparedStatement ps
= con.prepareStatement(
"select tx.reference,p.pname,ts.name, tx.sendername, tx.beneficiaryname, tx.beneficiary_currency,tx.beneficiary_amount from transaction_stage tx join transaction_status ts on tx.fk_status=ts.id join partner p on tx.fk_partner=p.id");
//get customer data from database
ResultSet result = ps.executeQuery();
List<Transaction> list = new ArrayList<Transaction>();
while (result.next()) {
Transaction cust = new Transaction();
cust.setReference(result.getString("reference"));
cust.setFk_status(result.getString("name"));
cust.setSendername(result.getString("sendername"));
cust.setBeneficiaryname(result.getString("beneficiaryname"));
cust.setBeneficiary_currency(result.getString("beneficiary_currency"));
cust.setBeneficiary_amount(result.getDouble("beneficiary_amount"));
cust.setPname(result.getString("pname"));
//store all data into a List
list.add(cust);
}
return list;
//added
}
//view single transaction
private List<Transaction> selectSingleTx;
public Transaction getUser() {
return user;
}
public void setUser(Transaction user) {
this.user = user;
}
public List<Transaction> getSelectSingleTx() {
return selectSingleTx;
}
public void setSelectSingleTx(List<Transaction> selectSingleTx) {
this.selectSingleTx = selectSingleTx;
}
public void showSelectedTx(String reference){
Connection con=DBConnector.getDBConnection();
if(con==null){
System.out.println("No db connection");
}
String ref=getReference();
try {
String q="select tx.reference,p.pname,ts.name, tx.sendername, tx.beneficiaryname, tx.beneficiary_currency,tx.beneficiary_amount from transaction_stage tx join transaction_status ts on tx.fk_status=ts.id join partner p on tx.fk_partner=p.id where tx.reference="+ref+"";
PreparedStatement ps=null;
ResultSet rs=null;
ps.setString(1, reference);
rs=ps.executeQuery();
display(rs);
} catch (Exception e) {
}
}
public void selectTx(String reference){
showSelectedTx(reference);
}
// to be implemented later
private static void display(ResultSet myRs) throws SQLException {
while (myRs.next()) {
String sendername = myRs.getString("sendername");
String beneficiaryname = myRs.getString("beneficiaryname");
//double salary = myRs.getDouble("salary");
String department = myRs.getString("department");
System.out.printf("%s, %s \n", sendername, beneficiaryname);
}
}
}
//
As per the Reference link, you need to include the value of c.reference in the link
value="#{c.reference}"
See JSF ViewParam from CommandButton
or
How to pass a parameter along with h:commandButton

Pass data from JSF page to MySQL database [duplicate]

This question already has an answer here:
How to send form input values and invoke a method in JSF bean
(1 answer)
Closed 4 years ago.
So I have a JSF page which contains a panelgrid with <h:inputtext> and one <h:commandbutton>. When I press the button I want the data that is introduced in the inputtexts to be stored in the database. The action is performed,the problem is that the values stored in the database are null.
This is the the Bean :
package accountsPackage;
public class Accounts {
private String username;
private String password;
private String CustomerName;
private String CustomerFirstName;
private String CustomerMiddleName;
private String CustomerPhone;
private String CustomerMobilePhone;
private String repassword;
private String email;
private String address;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getCustomerName() {
return CustomerName;
}
public void setCustomerName(String customerName) {
CustomerName = customerName;
}
public String getCustomerFirstName() {
return CustomerFirstName;
}
public void setCustomerFirstName(String customerFirstName) {
CustomerFirstName = customerFirstName;
}
public String getCustomerMiddleName() {
return CustomerMiddleName;
}
public void setCustomerMiddleName(String customerMiddleName) {
CustomerMiddleName = customerMiddleName;
}
public String getCustomerPhone() {
return CustomerPhone;
}
public void setCustomerPhone(String customerPhone) {
CustomerPhone = customerPhone;
}
public String getCustomerMobilePhone() {
return CustomerMobilePhone;
}
public void setCustomerMobilePhone(String customerMobilePhone) {
CustomerMobilePhone = customerMobilePhone;
}
public String getRepassword() {
return repassword;
}
public void setRepassword(String repassword) {
this.repassword = repassword;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
This is the class which connects to MySQL database and sends the values:
package databaseConnection;
import java.sql.*;
import accountsPackage.Accounts;
public class ConnectToDatabase {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/crochet_onlineshop";
static final String USER = "root";
static final String PASS = "root";
Accounts acc=new Accounts();
PreparedStatement ps=null;
public String addUser() throws Exception,SQLException,ClassNotFoundException{
String username=acc.getUsername();
String password=acc.getPassword();
String CustomerName=acc.getCustomerName();
String CustomerFirstName=acc.getCustomerFirstName();
String CustomerMiddleName=acc.getCustomerMiddleName();
String CustomerPhone=acc.getCustomerPhone();
String CustomerMobilePhone=acc.getCustomerMobilePhone();
String repassword=acc.getRepassword();
String email=acc.getEmail();
String address=acc.getAddress();
Connection conn = null;
Class.forName("com.mysql.jdbc.Driver");
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
String sqlAcc= "INSERT INTO Customer (username, password, repassword, CustomerName, CustomerFirstName, CustomerMiddleName, CustomerMobilePhone, CustomerPhone, email, address) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
ps=conn.prepareStatement(sqlAcc);
ps.setNString(1, username);
ps.setNString(2, password);
ps.setNString(3, repassword);
ps.setNString(4, CustomerName);
ps.setNString(5, CustomerFirstName);
ps.setNString(6, CustomerMiddleName);
ps.setNString(7, CustomerMobilePhone);
ps.setNString(8, CustomerPhone);
ps.setNString(9, email);
ps.setNString(10, address);
if( ps.executeUpdate()==1)
return "success";
else
return "fail";
}
}
And this is the JSF page(jsp) :
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# taglib prefix="f" uri="http://java.sun.com/jsf/core"%>
<%# taglib prefix="h" uri="http://java.sun.com/jsf/html"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h4>Please fill in the necessary fields in order to complete your account</h4>
<f:view>
<h:panelGrid columns="1">
<h:outputLabel value="username"></h:outputLabel>
<h:inputText value="#{accounts.username}"></h:inputText>
<h:outputLabel value="password"></h:outputLabel>
<h:inputSecret value="#{accounts.password}"></h:inputSecret>
<h:outputLabel value="re-enter password"></h:outputLabel>
<h:inputSecret value="#{accounts.repassword}"></h:inputSecret>
<h:outputLabel value="name"></h:outputLabel>
<h:inputText value="#{accounts.customerName}"></h:inputText>
<h:outputLabel value="firstname"></h:outputLabel>
<h:inputText value="#{accounts.customerFirstName}"></h:inputText>
<h:outputLabel value="middle name"></h:outputLabel>
<h:inputText value="#{accounts.customerMiddleName}"></h:inputText>
<h:outputLabel value="mobile phone"></h:outputLabel>
<h:inputText value="#{accounts.customerMobilePhone}"></h:inputText>
<h:outputLabel value="phone"></h:outputLabel>
<h:inputText value="#{accounts.customerPhone}"></h:inputText>
<h:outputLabel value="email"></h:outputLabel>
<h:inputText value="#{accounts.email }"></h:inputText>
<h:outputLabel value="address"></h:outputLabel>
<h:inputText value="#{accounts.address }"></h:inputText>
<h:form>
<h:commandButton action="#{connectToDatabase.addUser}"></h:commandButton>
</h:form>
</h:panelGrid>
</f:view>
</body>
</html>
Can someone help me to find out why the values stored in the db are NULL?
Even if you are using XML, you are doing it completely wrong. You are not passing Accounts to your ManagedBean ConnectToDatabase. Instead you are creating a new Accounts() in ConnectToDatabase and adding it to database.
EDIT1:
You should add getter and setter for accounts in class ConnectToDatabase. Then use #{connectToDatabase.accounts.username}, ... for the fields.
EDIT2:
ManagedBean
public class ConnectToDatabase {
// all your code is here
// For simplicity rename your accounts
// Accounts accounts = new Accounts();
// add the following lines
public Accounts getAccounts(){
return accounts
}
public void setAccounts(accounts){
this.accounts = accounts;
}
}
View
// your code
<h:panelGrid columns="1">
<h:outputLabel value="username"></h:outputLabel>
<h:inputText value="#{connectToDatabase.accounts.username}"></h:inputText>
......
//your code

PrimeFaces SelectOneRadio

I have one req , where I have a datable , which has x columns. One column contains 3 radio buttons .Which i am able to display . But my problem is I want one radio button to be selected by default .
What I am doing : On Load of datatable i am creating one variable (also i tried with SlectIte list) , but unable to get checked value.
Can anyone provide a simple working example?
This is my demonstration which present how to default radio value in datatable
XHTML
<h:form>
<p:dataTable var="catalog" value="#{radioView.catalogs}">
<p:column headerText="City">
<p:selectOneRadio id="city"
value="#{catalog.city}"
columns="3">
<f:selectItems value="#{radioView.cities}"
var="c"
itemLabel="#{city}"
itemValue="#{city}"/>
</p:selectOneRadio>
</p:column>
</p:dataTable>
<p:commandButton value="changeSelection"
process="#form"
update="#form"
actionListener="#{radioView.changeSelection}"/>
<p:commandButton value="submit"
process="#form"
update="#form"
actionListener="#{radioView.submit}"/>
</h:form>
ManagedBean
#ManagedBean
public class RadioView {
private List<Catalog> catalogs;
private List<String> cities;
#PostConstruct
public void init() {
cities = new ArrayList<String>();
cities.add("San Francisco");
cities.add("London");
cities.add("Paris");
//default radio value
Catalog c1 = new Catalog("San Francisco");
Catalog c2 = new Catalog("London");
Catalog c3 = new Catalog("Paris");
Catalog c4 = new Catalog("London");
catalogs = new ArrayList<Catalog>();
catalogs.add(c1);
catalogs.add(c2);
catalogs.add(c3);
catalogs.add(c4);
}
public List<Catalog> getCatalogs() {
return catalogs;
}
public void setCatalogs(List<Catalog> catalogs) {
this.catalogs = catalogs;
}
public List<String> getCities() {
return cities;
}
public void changeSelection(ActionEvent event){
for (Catalog catalog : catalogs) {
catalog.setCity("San Francisco");
}
}
public void submit(ActionEvent event) {
for (Catalog catalog : catalogs) {
System.out.println(catalog.getCity());
}
}
}
Domain
public class Catalog implements Serializable{
private String city;
public Catalog(String city){
this.city = city;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
}

multi-column hibernate query to xhtml page

I am trying to do a multi-column query in hibernate, and I want to know how to map the results to the xhtml file (I'm using JSF/seam).
So, this is my hibernate query:
#Name("theusers")
#AutoCreate
#Scope(SESSION)
public class Users implements Serializable {
#In
private EntityManager entityManager;
String unameit;
public String getUnameit() {
return unameit;
}
public void setUnameit(String unameit) {
this.unameit = unameit;
}
private List<Myuser[]> theusers;
public List<Myuser[]> getUsers(String uname) {
try {
theusers = (List<Myuser[]>)entityManager.createQuery("SELECT username, lastname from Myuser where username = :uname")
.setParameter("uname", uname)
.getResultList();
} catch(Exception e) {
theusers = null;
}
return theusers;
}
}
Basically I want to retrieve the username and lastName column from the table user_detail.
This is how I want to visualize it in 2 columns in xhtml:
<h:form id="un_form">
<p>Enter your username: <h:inputText id="unameit" value="#{theusers.unameit}" size="40" /></p>
<p><h:commandButton value="Submit" /></p>
</h:form>
<h:dataTable value="#{theusers.getUsers(theusers.unameit)}" var="u">
<h:column>
<f:facet name="header">
User name
</f:facet>
#{u.getUserName()}
</h:column>
<h:column>
<f:facet name="header">
User last name
</f:facet>
#{u.getLastName()}
</h:column>
</h:dataTable>
And finally Myuser.java:
#Entity
#Table(name="user_detail")
#DiscriminatorColumn(name = "obj_type", discriminatorType = DiscriminatorType.STRING, length = 255)
public abstract class Myuser { //implements Serializable {
#Id
public int id;
public String username;
public String firstname;
public String lastname;
#Column(name="id")
public int getId() {
return id;
}
#Column(name = "username")
public String getUserName() {
return username;
}
#Column(name = "firstName")
public String getFirstName() {
return firstname;
}
#Column(name = "lastName")
public String getLastName() {
return lastname;
}
public Myuser(int id, String username, String firstname, String lastname) {
this.id = id;
this.username = username;
this.firstname = firstname;
this.lastname = lastname;
}
public void setId( int id ) {
this.id = id;
}
public void setFirstName( String firstname ) {
this.firstname = firstname;
}
public void setLastName( String lastname ) {
this.lastname = lastname;
}
public void setUserName( String username ) {
this.username = username;
}
}
I keep getting an error. What could be wrong?
Thanks!
Your query is not returning a list of 'Myuser's it is returning a list of username's and lastname's
If you change your query to...
from Myuser where username = :uname
and change the return type to List<Myuser>
You will then return a list of Myusers that you can use in the datatable
Additionally you need to rework your backing bean and view a bit, the method getUsers needs to be called from the h:commandButton, this sets 'theusers' in your bean
#Name("theusers")
#AutoCreate
#Scope(SESSION)
public class Users implements Serializable {
#In
private EntityManager entityManager;
String unameit;
public String getUnameit() {
return unameit;
}
public void setUnameit(String unameit) {
this.unameit = unameit;
}
private List<Myuser> theusers;
public void getUsers() {
try {
theusers = (List<Myuser>)entityManager.createQuery("from Myuser where username = :uname")
.setParameter("uname", uname)
.getResultList();
}catch(Exception e) {
theusers = null;
}
}
}
and your page...
<h:form id="un_form">
<p>Enter your username: <h:inputText id="unameit" value="#{theusers.unameit}" size="40" /></p>
<p><h:commandButton action="#{theusers.getUsers}" value="Submit" /></p>
</h:form>
<h:dataTable value="#{theusers.theusers}" var="u">
<h:column>
<f:facet name="header">
User name
</f:facet>
#{u.getUserName()}
</h:column>
<h:column>
<f:facet name="header">
User last name
</f:facet>
#{u.getLastName()}
</h:column>
</h:dataTable>