Important Notice - Forums is archived
To simplify things and help our users to be more productive, we have archived the current forum and focus our efforts on helping developers on Stack Overflow. You can post new questions on Stack Overflow or join our Discord channel.

Vaadin lets you build secure, UX-first PWAs entirely in Java.
Free ebook & tutorial.
? equals = myPojoProviderService.getAllMyPojos()
A basic stupid question, please advise:
myPojoProviderService.getAllMyPojos = ?
https://vaadin.com/forum#!/thread/15526381
video notes
https://www.useloom.com/share/a8d11d541b454cfd9d984abcb19c9296
Grid<MyPojo> grid = new Grid<>();
grid.setItems(myPojoProviderService.getAllMyPojos());
The DAO bean I have is named sqlDAO.java
I do not know what:
??? = MyPojo
??? = myPojoProviderService.getAllMyPojos
Because this is a question about another forum user's sample code, it really should go on the original thread so that the original user can clarify his code.
In any case, the MyPojo class, the provider service, and the method are all completely made up to demonstrate that you can use Java generics with an arbitrary provider of an arbitrary generic type. Before Vaadin 8, you had to take your collection of items, configure and populate a container (e.g. BeanItemContainer), and then attach it to the component (e.g. Grid), sacrificing type safety along the way.
-- AC
Thank you Alejandro.
I did not continue with the original thread, as the question is something very basic, that would take someone that knows a few seconds to answer, but someone that does not know -- a lot of trial and error and searching.
All I am seeking is what is the EQUAL value of
myPojoProviderService.getAllMyPojos
my DAO bean is sqlDAO.java
would the same be represented as
??
What is getAllMyPojos represent ?
So close and yet so far away...
Please, there must be a REAL value for the generic example of
myPojoProviderService.getAllMyPojos
I only have two beans:
1. A Vaadin 8 Archetype called MainUI.java as seen in the screenshot
2. sqlDAO.java which connects to remote MySql data
Thank you!
sqlDAO.java
package com.basic.basicapp;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class sqlDAO
{
public static void main(String[] args) throws Exception
{
//access driver from jar
Class.forName("com.mysql.jdbc.Driver");
//create variable for connection "con"
Connection con = DriverManager.getConnection("jdbc:mysql://***************-west-2.rds.amazonaws.com:3306/webdata", "username", "password");
//query
PreparedStatement statement = con.prepareStatement("select * from product");
//create query variable
ResultSet result = statement.executeQuery();
while(result.next())
{
System.out.println(result.getString(1) + " " + result.getString(2) + " " + result.getString(3));
}
}
}
Thanks for the code. First thought is that this class is not a bean, nor really a DAO. This class needs a method that returns a collection of objects that have the data that you need. So, I recommend that you create an actual bean type that represents a single row in your product table, and will represent a single grid row. Note that I can't tell from your code what the actual column names are since you are using select *.
public class Product {
private final String field1;
private final String field2;
private final String field3;
public Product(String field1, String field2, String field3) {
this.field1 = field1;
this.field2 = field2;
this.field3 = field3;
}
public String getField1() { return field1; }
public String getField2() { return field2; }
public String getField3() { return field3; }
}
Next step, add a method to your DAO class that performs the database query and populates a Collection class, e.g. ArrayList<Product>().
public class SqlDAO {
public List<Product> getAllProducts() {
// ... your DB code here
// Populate a list of products
List<Product> products = new ArrayList<>();
while(result.next() {
products.add(new Product(result.getString(1), result.getString(2), result.getString(3)));
}
return products;
}
}
Finally, call this method and pass the results to the setItems() method on your Grid<Product>.
Thank you, shall create the Model and the DAO, then create a Vaadin Archetype to run setItems().
Thank you.
Hello, I originally tried to accomplish displaying my JSF web app data in a Vaadin Grid, but have yet to accomplish this, thus I began from scratch. I shall create the JSF - MODEL, CONTROLLER and DAO and then ask HOW to display that data in a Vaadin Grid.
Thank you.
Alejandro C De BacaThanks for the code. First thought is that this class is not a bean, nor really a DAO. This class needs a method that returns a collection of objects that have the data that you need. So, I recommend that you create an actual bean type that represents a single row in your product table, and will represent a single grid row. Note that I can't tell from your code what the actual column names are since you are using select *.
public class Product { private final String field1; private final String field2; private final String field3; public Product(String field1, String field2, String field3) { this.field1 = field1; this.field2 = field2; this.field3 = field3; } public String getField1() { return field1; } public String getField2() { return field2; } public String getField3() { return field3; } }
Next step, add a method to your DAO class that performs the database query and populates a Collection class, e.g. ArrayList<Product>().
public class SqlDAO { public List<Product> getAllProducts() { // ... your DB code here // Populate a list of products List<Product> products = new ArrayList<>(); while(result.next() { products.add(new Product(result.getString(1), result.getString(2), result.getString(3))); } return products; } }
Finally, call this method and pass the results to the setItems() method on your Grid<Product>.
Alejandro C De Baca: Thanks for the code. First thought is that this class is not a bean, nor really a DAO. This class needs a method that returns a collection of objects that have the data that you need. So, I recommend that you create an actual bean type that represents a single row in your product table, and will represent a single grid row. Note that I can't tell from your code what the actual column names are since you are using select *.
public class Product { private final String field1; private final String field2; private final String field3; public Product(String field1, String field2, String field3) { this.field1 = field1; this.field2 = field2; this.field3 = field3; } public String getField1() { return field1; } public String getField2() { return field2; } public String getField3() { return field3; } }
Next step, add a method to your DAO class that performs the database query and populates a Collection class, e.g. ArrayList<Product>().
public class SqlDAO { public List<Product> getAllProducts() { // ... your DB code here // Populate a list of products List<Product> products = new ArrayList<>(); while(result.next() { products.add(new Product(result.getString(1), result.getString(2), result.getString(3))); } return products; } }
Finally, call this method and pass the results to the setItems() method on your Grid<Product>.
Alejandro C De Baca: Can you post the code for sqlDAO.java?
Alejandro -- have reinstalled my system and just now creating a new Vaadin 8 Archetype I have my back end JSF beans:
1. MODEL
2. CONTROLLER
3. DAO
the data connectivity is within the context.xml and the web.xml
Am installing Vaadin for Eclipse right now, then shall -- again, try to connect the remote sql data to a Vaadin Grid.
Shall post here within the next 30 minutes, with a hope that you may have a moment to view.
Thank you.
Alejandro C De Baca: Can you post the code for sqlDAO.java?
Hi Alejandro C De Baca,
In a Vaadin 8 Archetype that I just created, I have placed my JSF java source files in the Project but do not know how to place the connection data. In the JSF, the connection data is in the context.xml (Resource) and web.xml (username, etc...)
The connection data is in the Project but is not being found.
Video notes
https://www.useloom.com/share/4bed85bbc99d4a76863ca14d58617444
I have the two Projects next to each other in Eclipse. The JSF web app runs with plain html table. The Vaadin 8 Archetype runs as well.
I can copy my Model, Controller and DAO files from the JSF to the Vaadin Archetype, but the data connection is within the context.xml and web.xml
How do I modify my Vaadin Archetype to access my remote data?
Hi,
I'm not sure what isn't working, but I can give you a few pointers to get you started.
If you have m2e and m2e-wtp installed in Eclipse, then you can add the Dynamic Web Module facet to your Vaadin archetype project (right click your project, select Properties, choose Project Facets from the left pane). If your project is not already in faceted form, converting it and adding Dynamic Web Module will give you a WebContent folder with a WEB-INF and a META-INF, so you now have a destination for your web.xml and context.xml.
Your deployment assembly (also under project properties) must include the following mappings:
/WebContent => /
/src/main/webapp => /
Maven Dependencies => WEB-INF/lib
I've attached an image that shows you the mappings I have for one of my projects that deploys to a server (instead of using the jetty-maven plugin). Note the options in the "New Assembly Directive" dialog box. If you don't see these options (e.g. Java Build Path Entries), then make sure m2e and m2e-wtp are installed correctly.
Finally, I recommend making your mysql jdbc connector 5.1.40 a maven dependency instead of a referenced library. You can do that by adding the following lines to your pom.xml in the <dependencies> section:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.40</version>
</dependency>
I matched the version you are using in the video; there are more recent releases than 5.1.40.
Best of luck.
-- AC
You are the BEST!
Shall make the change for the mysql jar right now.
Alejandro C De Baca: Hi,
I'm not sure what isn't working, but I can give you a few pointers to get you started.
If you have m2e and m2e-wtp installed in Eclipse, then you can add the Dynamic Web Module facet to your Vaadin archetype project (right click your project, select Properties, choose Project Facets from the left pane). If your project is not already in faceted form, converting it and adding Dynamic Web Module will give you a WebContent folder with a WEB-INF and a META-INF, so you now have a destination for your web.xml and context.xml.
Your deployment assembly (also under project properties) must include the following mappings:
/WebContent => /
/src/main/webapp => /
Maven Dependencies => WEB-INF/libI've attached an image that shows you the mappings I have for one of my projects that deploys to a server (instead of using the jetty-maven plugin). Note the options in the "New Assembly Directive" dialog box. If you don't see these options (e.g. Java Build Path Entries), then make sure m2e and m2e-wtp are installed correctly.
Finally, I recommend making your mysql jdbc connector 5.1.40 a maven dependency instead of a referenced library. You can do that by adding the following lines to your pom.xml in the <dependencies> section:
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.40</version> </dependency>
I matched the version you are using in the video; there are more recent releases than 5.1.40.
Best of luck.
-- AC
choose Project Facets from the left pane). If your project is not already in faceted form, converting it and adding Dynamic Web Module will give you a WebContent folder with a WEB-INF and a META-INF, so you now have a destination for your web.xml and context.xml.
It is already selected but there is NO Web Content folder created. I had copied the Web Content folder from the JSF Project and Pasted it into the Vaadin 8 Archetype Project
Does that image show the facets for your Vaadin archetype project? I don't think JSF should be selected, just Dynamic Web Module and Java. Regardless, what matter most are the deployment assembly mappings.
OK, it worked... the data displays!
You are the GREATEST!
Just need to now display same data in a Vaadin Grid
video notes
https://www.useloom.com/share/b4804fb5e8154ed9a2b2794933221fcd
Alejandro C De Baca: Does that image show the facets for your Vaadin archetype project? I don't think JSF should be selected, just Dynamic Web Module and Java. Regardless, what matter most are the deployment assembly mappings.
It works, now just to apply the specific Vaadin 8 code to populate the Vaadin Grid.
You can co-edit with me, if you desire.
https://zoom.us/j/574115666
Would I follow this one to reference my DAO bean?
https://www.voxxed.com/blog/2017/03/21-improvements-vaadin-8/
Video notes
https://www.useloom.com/share/8f6231b9766a4f2385a6121898f007b6
List<Product> products = Backend.getProducts();
Grid<Product> grid = new Grid<>(Product.class);
grid.setItems(products);
Import List and Grid - just click on the type, hit F2 and let Eclipse find the dependencies. Make sure to use java.util.List for the List (not java.awt.List).
Replace Backend with an instance of your DAO.
Modified MainUI.java with import com.vaadin.ui.Grid;
only two errors remain
List
Backend
[code] List<Product> products = Backend.getProducts();
[/code]
Alejandro C De Baca: Import List and Grid - just click on the type, hit F2 and let Eclipse find the dependencies. Make sure to use java.util.List for the List (not java.awt.List).
Replace Backend with an instance of your DAO.
Excellent. The Backend replacement is not working:
package com.dataSQL.basic;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Button;
import com.vaadin.ui.Grid;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
@Theme("maintheme")
public class MainUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
List<Product> products = ProductDbUtil.getProducts();
Grid<Product> grid = new Grid<>(Product.class);
grid.setItems(products);
}
@WebServlet(urlPatterns = "/*", name = "MainUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MainUI.class, productionMode = false)
public static class MainUIServlet extends VaadinServlet {
}
}
Create an instance of ProductDbUtil - use new, or call getInstance() if you have a factory method.
Thank you, you have been the best help I have received. I had hoped to populate a Vaadin Grid, but I am a lot closer than before. Thank you.
That
"Create an instance of ProductDbUtil - use new, or call getInstance() if you have a factory method."
is nowhere, not done or mentioned in the examples
https://www.voxxed.com/blog/2017/03/21-improvements-vaadin-8/
but shall explore to discover.
https://docs.oracle.com/javase/tutorial/reflect/member/ctorInstance.html
Alejandro C De Baca: Create an instance of ProductDbUtil - use new, or call getInstance() if you have a factory method.
Once again, I really thank you for the time you have shared with me -- way above and beyond what was hoped for, thank you!
Alejandro C De Baca: Create an instance of ProductDbUtil - use new, or call getInstance() if you have a factory method.
Hello, Alejandro. I am paying for a course in java Design Patterns to include 24:
Decorator, Factory, Abstract Factory, Strategy, Singleton, Adapter, Facade, Template, Iterator, MVC, Observer, Command, Composite, Builder, Chain of Responsibility, Memento, Visitor, State, Flyweight, Bridge, Mediator, Prototype, Proxy, Double-Checked Locking and Dependency Injection.
Would this lead to my understanding and ability to complete the coding to view a Vaadin Grid with my remote data, as a beginning? My immediate focus is to create a Vaadin Grid with my remote data, then go through the Book of Vaadin 8 to learn all about Vaadin using real examples, beginning from the Vaadin Grid and leading to Vaadin Designer.
Please, would taking the design pattern course enable me to resolve my current coding challenge with creating the instance?
I don't think that this is a design pattern issue, but just a few minor misunderstandings about Java. Can you post the code for the DC util class? I think that you are inches from the goal.
Wow, thank you! I have spent the last 4 hours posting to instructors about Java Patterns, seeking WHICH additional course to buy. I really want to spend my time reading the Book of Vaadin and LEARN Vaadin. I have instructors that I shall learn Java Architechture from. Everything you have generously shared with me, shall be printed and placed in my Vaadin coding note book.
What would you like me to post?
Shall post all three:
Model
Controller
DAO
plus the Vaadin Archetype MainUI.java
Four files.
One moment, please....
and Thank you.!
model
package com.dataSQL.basic;
import javax.faces.bean.ManagedBean;
@ManagedBean
public class Product {
private int id;
private String small_desc;
private String large_desc;
private String sku;
private String category;
private String barcode;
public Product() {
}
public Product(int id, String small_desc, String large_desc, String sku, String category, String barcode) {
this.id = id;
this.small_desc = small_desc;
this.large_desc = large_desc;
this.sku = sku;
this.category = category;
this.barcode = barcode;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSmall_desc() {
return small_desc;
}
public void setSmall_desc(String small_desc) {
this.small_desc = small_desc;
}
public String getLarge_desc() {
return large_desc;
}
public void setLarge_desc(String large_desc) {
this.large_desc = large_desc;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
@Override
public String toString() {
return "Product [id=" + id
+ ", small_desc=" + small_desc
+ ", large_desc=" + large_desc
+ ", sku=" + sku
+ ", category=" + category
+ ", barcode=" + barcode + "]";
}
}
Controller
package com.dataSQL.basic;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
@ManagedBean
@SessionScoped
public class ProductController {
private List<Product> products;
private ProductDbUtil productDbUtil;
private Logger logger = Logger.getLogger(getClass().getName());
public ProductController() throws Exception {
products = new ArrayList<>();
productDbUtil = ProductDbUtil.getInstance();
}
public List<Product> getProducts() {
return products;
}
public void loadProducts() {
logger.info("Loading products");
products.clear();
try {
// get all products from database
products = productDbUtil.getProducts();
} catch (Exception exc) {
// send this to server logs
logger.log(Level.SEVERE, "Error loading products", exc);
// add error message for JSF page
addErrorMessage(exc);
}
}
public String addProduct(Product theProduct) {
logger.info("Adding product: " + theProduct);
try {
// add product to the database
productDbUtil.addProduct(theProduct);
} catch (Exception exc) {
// send this to server logs
logger.log(Level.SEVERE, "Error adding products", exc);
// add error message for JSF page
addErrorMessage(exc);
return null;
}
return "list-products?faces-redirect=true";
}
public String loadProduct(int productId) {
logger.info("loading product: " + productId);
try {
// get product from database
Product theProduct = productDbUtil.getProduct(productId);
// put in the request attribute ... so we can use it on the form page
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> requestMap = externalContext.getRequestMap();
requestMap.put("product", theProduct);
} catch (Exception exc) {
// send this to server logs
logger.log(Level.SEVERE, "Error loading product id:" + productId, exc);
// add error message for JSF page
addErrorMessage(exc);
return null;
}
return "update-product-form.xhtml";
}
public String updateProduct(Product theProduct) {
logger.info("updating product: " + theProduct);
try {
// update product in the database
productDbUtil.updateProduct(theProduct);
} catch (Exception exc) {
// send this to server logs
logger.log(Level.SEVERE, "Error updating product: " + theProduct, exc);
// add error message for JSF page
addErrorMessage(exc);
return null;
}
return "list-products?faces-redirect=true";
}
public String deleteProduct(int productId) {
logger.info("Deleting product id: " + productId);
try {
// delete the product from the database
productDbUtil.deleteProduct(productId);
} catch (Exception exc) {
// send this to server logs
logger.log(Level.SEVERE, "Error deleting product id: " + productId, exc);
// add error message for JSF page
addErrorMessage(exc);
return null;
}
return "list-products";
}
private void addErrorMessage(Exception exc) {
FacesMessage message = new FacesMessage("Error: " + exc.getMessage());
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
DAO
package com.dataSQL.basic;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class ProductDbUtil {
private static ProductDbUtil instance;
private DataSource dataSource;
private String jndiName = "java:comp/env/jdbc/webdata";
public static ProductDbUtil getInstance() throws Exception {
if (instance == null) {
instance = new ProductDbUtil();
}
return instance;
}
private ProductDbUtil() throws Exception {
dataSource = getDataSource();
}
private DataSource getDataSource() throws NamingException {
Context context = new InitialContext();
DataSource theDataSource = (DataSource) context.lookup(jndiName);
return theDataSource;
}
public List<Product> getProducts() throws Exception {
List<Product> products = new ArrayList<>();
Connection myConn = null;
Statement myStmt = null;
ResultSet myRs = null;
try {
myConn = getConnection();
String sql = "select * from product order by category";
myStmt = myConn.createStatement();
myRs = myStmt.executeQuery(sql);
// process result set
while (myRs.next()) {
// retrieve data from result set row
int id = myRs.getInt("id");
String small_desc = myRs.getString("small_desc");
String large_desc = myRs.getString("large_desc");
String sku = myRs.getString("sku");
String category = myRs.getString("category");
String barcode = myRs.getString("barcode");
// create new product object
Product tempProduct = new Product(id, small_desc, large_desc, sku, category, barcode);
// add it to the list of products
products.add(tempProduct);
}
return products;
}
finally {
close (myConn, myStmt, myRs);
}
}
public void addProduct(Product theProduct) throws Exception {
Connection myConn = null;
PreparedStatement myStmt = null;
try {
myConn = getConnection();
String sql = "insert into product (small_desc, large_desc, sku, category, barcode) values (?, ?, ?, ?, ?)";
myStmt = myConn.prepareStatement(sql);
// set params
myStmt.setString(1, theProduct.getSmall_desc());
myStmt.setString(2, theProduct.getLarge_desc());
myStmt.setString(3, theProduct.getSku());
myStmt.setString(4, theProduct.getCategory());
myStmt.setString(5, theProduct.getBarcode());
myStmt.execute();
}
finally {
close (myConn, myStmt);
}
}
public Product getProduct(int productId) throws Exception {
Connection myConn = null;
PreparedStatement myStmt = null;
ResultSet myRs = null;
try {
myConn = getConnection();
String sql = "select * from product where id=?";
myStmt = myConn.prepareStatement(sql);
// set params
myStmt.setInt(1, productId);
myRs = myStmt.executeQuery();
Product theProduct = null;
// retrieve data from result set row
if (myRs.next()) {
int id = myRs.getInt("id");
String small_desc = myRs.getString("small_desc");
String large_desc = myRs.getString("large_desc");
String sku = myRs.getString("sku");
String category = myRs.getString("category");
String barcode = myRs.getString("barcode");
theProduct = new Product(id, small_desc, large_desc, sku, category, barcode);
}
else {
throw new Exception("Could not find product id: " + productId);
}
return theProduct;
}
finally {
close (myConn, myStmt, myRs);
}
}
public void updateProduct(Product theProduct) throws Exception {
Connection myConn = null;
PreparedStatement myStmt = null;
try {
myConn = getConnection();
String sql = "update product "
+ " set small_desc=?, large_desc=?, sku=?, category=?, barcode=?"
+ " where id=?";
myStmt = myConn.prepareStatement(sql);
// set params
myStmt.setString(1, theProduct.getSmall_desc());
myStmt.setString(2, theProduct.getLarge_desc());
myStmt.setString(3, theProduct.getSku());
myStmt.setString(4, theProduct.getCategory());
myStmt.setString(5, theProduct.getBarcode());
myStmt.execute();
}
finally {
close (myConn, myStmt);
}
}
public void deleteProduct(int productId) throws Exception {
Connection myConn = null;
PreparedStatement myStmt = null;
try {
myConn = getConnection();
String sql = "delete from product where id=?";
myStmt = myConn.prepareStatement(sql);
// set params
myStmt.setInt(1, productId);
myStmt.execute();
}
finally {
close (myConn, myStmt);
}
}
private Connection getConnection() throws Exception {
Connection theConn = dataSource.getConnection();
return theConn;
}
private void close(Connection theConn, Statement theStmt) {
close(theConn, theStmt, null);
}
private void close(Connection theConn, Statement theStmt, ResultSet theRs) {
try {
if (theRs != null) {
theRs.close();
}
if (theStmt != null) {
theStmt.close();
}
if (theConn != null) {
theConn.close();
}
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
Vaadin 8 Archetype MainUI.java
package com.dataSQL.basic;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Grid;
import com.vaadin.ui.UI;
@Theme("maintheme")
public class MainUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
List<Product> products = ProductDbUtil.getProducts();
Grid<Product> grid = new Grid<>(Product.class);
grid.setItems(products);
}
@WebServlet(urlPatterns = "/*", name = "MainUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MainUI.class, productionMode = false)
public static class MainUIServlet extends VaadinServlet {
}
}
In the MainUI init() method, have you tried
List<Products> products = ProductDbUtil.getInstance().getProducts();
?
did not work...
Multiple markers at this line
- Unhandled exception type Exception
- Unhandled exception type Exception
model
package com.dataSQL.basic;
import javax.faces.bean.ManagedBean;
@ManagedBean
public class Product {
private int id;
private String small_desc;
private String large_desc;
private String sku;
private String category;
private String barcode;
public Product() {
}
public Product(int id, String small_desc, String large_desc, String sku, String category, String barcode) {
this.id = id;
this.small_desc = small_desc;
this.large_desc = large_desc;
this.sku = sku;
this.category = category;
this.barcode = barcode;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getSmall_desc() {
return small_desc;
}
public void setSmall_desc(String small_desc) {
this.small_desc = small_desc;
}
public String getLarge_desc() {
return large_desc;
}
public void setLarge_desc(String large_desc) {
this.large_desc = large_desc;
}
public String getSku() {
return sku;
}
public void setSku(String sku) {
this.sku = sku;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public String getBarcode() {
return barcode;
}
public void setBarcode(String barcode) {
this.barcode = barcode;
}
@Override
public String toString() {
return "Product [id=" + id
+ ", small_desc=" + small_desc
+ ", large_desc=" + large_desc
+ ", sku=" + sku
+ ", category=" + category
+ ", barcode=" + barcode + "]";
}
}
Controller
package com.dataSQL.basic;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
@ManagedBean
@SessionScoped
public class ProductController {
private List<Product> products;
private ProductDbUtil productDbUtil;
private Logger logger = Logger.getLogger(getClass().getName());
public ProductController() throws Exception {
products = new ArrayList<>();
productDbUtil = ProductDbUtil.getInstance();
}
public List<Product> getProducts() {
return products;
}
public void loadProducts() {
logger.info("Loading products");
products.clear();
try {
// get all products from database
products = productDbUtil.getProducts();
} catch (Exception exc) {
// send this to server logs
logger.log(Level.SEVERE, "Error loading products", exc);
// add error message for JSF page
addErrorMessage(exc);
}
}
public String addProduct(Product theProduct) {
logger.info("Adding product: " + theProduct);
try {
// add product to the database
productDbUtil.addProduct(theProduct);
} catch (Exception exc) {
// send this to server logs
logger.log(Level.SEVERE, "Error adding products", exc);
// add error message for JSF page
addErrorMessage(exc);
return null;
}
return "list-products?faces-redirect=true";
}
public String loadProduct(int productId) {
logger.info("loading product: " + productId);
try {
// get product from database
Product theProduct = productDbUtil.getProduct(productId);
// put in the request attribute ... so we can use it on the form page
ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext();
Map<String, Object> requestMap = externalContext.getRequestMap();
requestMap.put("product", theProduct);
} catch (Exception exc) {
// send this to server logs
logger.log(Level.SEVERE, "Error loading product id:" + productId, exc);
// add error message for JSF page
addErrorMessage(exc);
return null;
}
return "update-product-form.xhtml";
}
public String updateProduct(Product theProduct) {
logger.info("updating product: " + theProduct);
try {
// update product in the database
productDbUtil.updateProduct(theProduct);
} catch (Exception exc) {
// send this to server logs
logger.log(Level.SEVERE, "Error updating product: " + theProduct, exc);
// add error message for JSF page
addErrorMessage(exc);
return null;
}
return "list-products?faces-redirect=true";
}
public String deleteProduct(int productId) {
logger.info("Deleting product id: " + productId);
try {
// delete the product from the database
productDbUtil.deleteProduct(productId);
} catch (Exception exc) {
// send this to server logs
logger.log(Level.SEVERE, "Error deleting product id: " + productId, exc);
// add error message for JSF page
addErrorMessage(exc);
return null;
}
return "list-products";
}
private void addErrorMessage(Exception exc) {
FacesMessage message = new FacesMessage("Error: " + exc.getMessage());
FacesContext.getCurrentInstance().addMessage(null, message);
}
}
DAO
package com.dataSQL.basic;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class ProductDbUtil {
private static ProductDbUtil instance;
private DataSource dataSource;
private String jndiName = "java:comp/env/jdbc/webdata";
public static ProductDbUtil getInstance() throws Exception {
if (instance == null) {
instance = new ProductDbUtil();
}
return instance;
}
private ProductDbUtil() throws Exception {
dataSource = getDataSource();
}
private DataSource getDataSource() throws NamingException {
Context context = new InitialContext();
DataSource theDataSource = (DataSource) context.lookup(jndiName);
return theDataSource;
}
public List<Product> getProducts() throws Exception {
List<Product> products = new ArrayList<>();
Connection myConn = null;
Statement myStmt = null;
ResultSet myRs = null;
try {
myConn = getConnection();
String sql = "select * from product order by category";
myStmt = myConn.createStatement();
myRs = myStmt.executeQuery(sql);
// process result set
while (myRs.next()) {
// retrieve data from result set row
int id = myRs.getInt("id");
String small_desc = myRs.getString("small_desc");
String large_desc = myRs.getString("large_desc");
String sku = myRs.getString("sku");
String category = myRs.getString("category");
String barcode = myRs.getString("barcode");
// create new product object
Product tempProduct = new Product(id, small_desc, large_desc, sku, category, barcode);
// add it to the list of products
products.add(tempProduct);
}
return products;
}
finally {
close (myConn, myStmt, myRs);
}
}
public void addProduct(Product theProduct) throws Exception {
Connection myConn = null;
PreparedStatement myStmt = null;
try {
myConn = getConnection();
String sql = "insert into product (small_desc, large_desc, sku, category, barcode) values (?, ?, ?, ?, ?)";
myStmt = myConn.prepareStatement(sql);
// set params
myStmt.setString(1, theProduct.getSmall_desc());
myStmt.setString(2, theProduct.getLarge_desc());
myStmt.setString(3, theProduct.getSku());
myStmt.setString(4, theProduct.getCategory());
myStmt.setString(5, theProduct.getBarcode());
myStmt.execute();
}
finally {
close (myConn, myStmt);
}
}
public Product getProduct(int productId) throws Exception {
Connection myConn = null;
PreparedStatement myStmt = null;
ResultSet myRs = null;
try {
myConn = getConnection();
String sql = "select * from product where id=?";
myStmt = myConn.prepareStatement(sql);
// set params
myStmt.setInt(1, productId);
myRs = myStmt.executeQuery();
Product theProduct = null;
// retrieve data from result set row
if (myRs.next()) {
int id = myRs.getInt("id");
String small_desc = myRs.getString("small_desc");
String large_desc = myRs.getString("large_desc");
String sku = myRs.getString("sku");
String category = myRs.getString("category");
String barcode = myRs.getString("barcode");
theProduct = new Product(id, small_desc, large_desc, sku, category, barcode);
}
else {
throw new Exception("Could not find product id: " + productId);
}
return theProduct;
}
finally {
close (myConn, myStmt, myRs);
}
}
public void updateProduct(Product theProduct) throws Exception {
Connection myConn = null;
PreparedStatement myStmt = null;
try {
myConn = getConnection();
String sql = "update product "
+ " set small_desc=?, large_desc=?, sku=?, category=?, barcode=?"
+ " where id=?";
myStmt = myConn.prepareStatement(sql);
// set params
myStmt.setString(1, theProduct.getSmall_desc());
myStmt.setString(2, theProduct.getLarge_desc());
myStmt.setString(3, theProduct.getSku());
myStmt.setString(4, theProduct.getCategory());
myStmt.setString(5, theProduct.getBarcode());
myStmt.execute();
}
finally {
close (myConn, myStmt);
}
}
public void deleteProduct(int productId) throws Exception {
Connection myConn = null;
PreparedStatement myStmt = null;
try {
myConn = getConnection();
String sql = "delete from product where id=?";
myStmt = myConn.prepareStatement(sql);
// set params
myStmt.setInt(1, productId);
myStmt.execute();
}
finally {
close (myConn, myStmt);
}
}
private Connection getConnection() throws Exception {
Connection theConn = dataSource.getConnection();
return theConn;
}
private void close(Connection theConn, Statement theStmt) {
close(theConn, theStmt, null);
}
private void close(Connection theConn, Statement theStmt, ResultSet theRs) {
try {
if (theRs != null) {
theRs.close();
}
if (theStmt != null) {
theStmt.close();
}
if (theConn != null) {
theConn.close();
}
} catch (Exception exc) {
exc.printStackTrace();
}
}
}
Vaadin 8 Archetype MainUI.java
package com.dataSQL.basic;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Grid;
import com.vaadin.ui.UI;
@Theme("maintheme")
public class MainUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
List<Product> products = ProductDbUtil.getProducts();
Grid<Product> grid = new Grid<>(Product.class);
grid.setItems(products);
}
@WebServlet(urlPatterns = "/*", name = "MainUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MainUI.class, productionMode = false)
public static class MainUIServlet extends VaadinServlet {
}
}
Wrap it in a try-catch block. You can also have Eclipse do it for you by hitting F2 with the cursor over the code with the red squiggly line.
Are you well acquainted with Java fundamentals? If not, and given that you are considering taking courses, I think it would be worthwhile to get the rudiments down solid. Creating instances and handling exceptions are common Java operations, and it would reduce the number of round trips when you are asking for help on these forums. It will also help you to better understand the code examples given on the blog posts that you have referenced. The post is actually quite self-explanatory, however the sample is not meant to be cut-and-pasted into your IDE; the writer expects the reader to adapt it to their own environment.
Just a suggestion.
-- AC
Shall be taking Java course to expand upon all that you have shared with me.
I found the solution, but do not know how to implement it
You need to create an instance of the object first using the "new" keyword, then call the method.
but do not know how to implement it to the following code:
[code]package com.dataSQL.basic;
import java.util.List;
import javax.servlet.annotation.WebServlet;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.ui.Grid;
import com.vaadin.ui.UI;
@Theme("maintheme")
public class MainUI extends UI {
@Override
protected void init(VaadinRequest vaadinRequest) {
List<Product> products = ProductDbUtil.getProducts();
Grid<Product> grid = new Grid<>(Product.class);
grid.setItems(products);
}
@WebServlet(urlPatterns = "/*", name = "MainUIServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = MainUI.class, productionMode = false)
public static class MainUIServlet extends VaadinServlet {
}
}
[/code]