mercredi 18 septembre 2013

Simple CRUD Using JSF (standard) and MySQL with netbeans and Tomcat

The Data
  • The database (an example)
create database TestDB;
use TestDB;


CREATE TABLE TestDB.`users` (
  `userid` int(11) NOT NULL AUTO_INCREMENT,
  `firstname` varchar(45) DEFAULT NULL,
  `lastname` varchar(45) DEFAULT NULL,
  `dob` date DEFAULT NULL,
  `email` varchar(100) DEFAULT NULL,
  PRIMARY KEY (`userid`)
) ENGINE=InnoDB AUTO_INCREMENT=9 DEFAULT CHARSET=utf8
The handy ORM

  • The entity (POJO)
public class User {

    private int userid;
    private String firstName;
    private String lastName;
    private Date dob;
    private String email;
    public int getUserid() {
        return userid;
    }
    public void setUserid(int userid) {
        this.userid = userid;
    }
    public String getFirstName() {
        return firstName;
    }
    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }
    public String getLastName() {
        return lastName;
    }
    public void setLastName(String lastName) {
        this.lastName = lastName;
    }
    public Date getDob() {
        return dob;
    }
    public void setDob(Date dob) {
        this.dob = dob;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    @Override
    public String toString() {
        return "User [userid=" + userid + ", firstName=" + firstName
                + ", lastName=" + lastName + ", dob=" + dob + ", email="
                + email + "]";
    }    
}
  • The DAO (insert, select, update, delete)
1 
 2 package dao;
 3 
 4 import entities.User;
 5 import gm.GM;
 6 import java.sql.Connection;
 7 import java.sql.PreparedStatement;
 8 import java.sql.ResultSet;
 9 import java.sql.SQLException;
10 import java.sql.Statement;
11 import java.util.ArrayList;
12 import java.util.List;
13 import javax.naming.NamingException;
14 
15 /**
16  *
17  * @author pascalfares
18  */
19 public class UserDao {
20     public static void addUser(User user) throws SQLException, NamingException {
21             Connection connection = GM.getTestDB().getConnection();
22             PreparedStatement preparedStatement = connection
23                     .prepareStatement("insert into users(firstname,lastname,dob,email) values (?, ?, ?, ? )");
24             // Parameters start with 1
25             preparedStatement.setString(1, user.getFirstName());
26             preparedStatement.setString(2, user.getLastName());
27             preparedStatement.setDate(3, new java.sql.Date(user.getDob().getTime()));
28             preparedStatement.setString(4, user.getEmail());
29             preparedStatement.executeUpdate();
30 
31       
32     }
33 
34     public static void deleteUser(int userId) throws NamingException, SQLException {
35         Connection connection = GM.getTestDB().getConnection();
36             PreparedStatement preparedStatement = connection
37                     .prepareStatement("delete from users where userid=?");
38             // Parameters start with 1
39             preparedStatement.setInt(1, userId);
40             preparedStatement.executeUpdate();
41 
42     }
43 
44     public static void updateUser(User user) throws NamingException, SQLException {
45         Connection connection = GM.getTestDB().getConnection();
46             PreparedStatement preparedStatement = connection
47                     .prepareStatement("update users set firstname=?, lastname=?, dob=?, email=?" +
48                             "where userid=?");
49             // Parameters start with 1
50             preparedStatement.setString(1, user.getFirstName());
51             preparedStatement.setString(2, user.getLastName());
52             preparedStatement.setDate(3, new java.sql.Date(user.getDob().getTime()));
53             preparedStatement.setString(4, user.getEmail());
54             preparedStatement.setInt(5, user.getUserid());
55             preparedStatement.executeUpdate();
56 
57         
58     }
59 
60     public static List<User> getAllUsers() throws NamingException, SQLException {
61         List<User> users = new ArrayList<User>();
62         Connection connection = GM.getTestDB().getConnection();
63             Statement statement = connection.createStatement();
64             ResultSet rs = statement.executeQuery("select * from users");
65             while (rs.next()) {
66                 User user = new User();
67                 user.setUserid(rs.getInt("userid"));
68                 user.setFirstName(rs.getString("firstname"));
69                 user.setLastName(rs.getString("lastname"));
70                 user.setDob(new java.util.Date(rs.getDate("dob").getTime()));
71                 user.setEmail(rs.getString("email"));
72                 users.add(user);
73             }
74         
75 
76         return users;
77     }
78 
79     public static User getUserById(int userId) throws NamingException, SQLException {
80         User user = new User();
81         Connection connection = GM.getTestDB().getConnection();
82             PreparedStatement preparedStatement = connection.
83                     prepareStatement("select * from users where userid=?");
84             preparedStatement.setInt(1, userId);
85             ResultSet rs = preparedStatement.executeQuery();
86 
87             if (rs.next()) {
88                 user.setUserid(rs.getInt("userid"));
89                 user.setFirstName(rs.getString("firstname"));
90                 user.setLastName(rs.getString("lastname"));
91                 user.setDob(rs.getDate("dob"));
92                 user.setEmail(rs.getString("email"));
93             }
94        
95         return user;
96     }
97 }
98 
The UI

  • The ManagedBean
Create the UserControl managedBean


 1 package mb;
 2 
 3 import dao.UserDao;
 4 import entities.User;
 5 import java.sql.SQLException;
 6 import java.util.List;
 7 import javax.faces.bean.ManagedBean;
 8 import javax.faces.bean.SessionScoped;
 9 import javax.naming.NamingException;
10 
11 /**
12  * A minimal Managed Bean for CRUD 2 attributes
13  * one for current User
14  * one for the list of users
15  * @author pfares
16  */
17 @ManagedBean
18 @SessionScoped
19 public class UserControl {
20     private User selectedUser;
21     private List<User> lusers;
22     /**
23      * Creates a new instance of UserControl
24      */
25     public UserControl() {
26         selectedUser=new User();
27     }
28 
29     /**
30      * @return the selectedUser
31      */
32     public User getSelectedUser() {
33         return selectedUser;
34     }
35 
36     /**
37      * @param selectedUser the selectedUser to set
38      */
39     public void setSelectedUser(User selectedUser) {
40         this.selectedUser = selectedUser;
41     }
42 
43     /**
44      * @return the lusers
45      */
46     public List<User> getLusers() throws NamingException, SQLException {
47         lusers=UserDao.getAllUsers();
48         return lusers;
49     }
50 
51     /**
52      * @param lusers the lusers to set
53      */
54     public void setLusers(List<User> lusers) {
55         this.lusers = lusers;
56     }
57     
58     public String create() throws SQLException, NamingException {
59         UserDao.addUser(selectedUser);
60         
61         return "index";
62         
63     }
64 }

Minimal pages : List Users and Create Users
1 <?xml version='1.0' encoding='UTF-8' ?>
 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 3 <html xmlns="http://www.w3.org/1999/xhtml"
 4       xmlns:h="http://java.sun.com/jsf/html"
 5       xmlns:f="http://java.sun.com/jsf/core">
 6     <h:head>
 7         <title>Facelet Title</title>
 8     </h:head>
 9     <h:body>
10         <f:view>
11             <h:form>
12                 <h:dataTable border="1" value="#{userControl.lusers}" var="item">
13                     <h:column>#{item.firstName}</h:column>
14                     <h:column>#{item.lastName}</h:column>
15                     <h:column>#{item.userid}</h:column>
16                     <h:column>#{item.email}</h:column>
17                     <h:column>
18                         <h:outputText value="#{item.dob}" />
19                     </h:column>
20                 </h:dataTable>
21             </h:form>
22         </f:view>
23 
24     </h:body>
25 </html>
===
1 <?xml version='1.0' encoding='UTF-8' ?>
 2 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 3 <html xmlns="http://www.w3.org/1999/xhtml"
 4       xmlns:h="http://java.sun.com/jsf/html"
 5       xmlns:f="http://java.sun.com/jsf/core">
 6     <h:head>
 7         <title>Crud Example : Create a user</title>
 8     </h:head>
 9     <h:body>
10         <f:view>
11             <h:form>
12                 <h:outputLabel value="Nom" for="nom" />
13                 <h:inputText id="nom" value="#{userControl.selectedUser.lastName}" />
14                 <h:outputLabel value="PreNom" for="prenom" />
15                 <h:inputText id="prenom" value="#{userControl.selectedUser.firstName}" />
16                  <h:outputLabel value="Email" for="email" />
17                 <h:inputText id="email" required="true" label="email" size="40"
18                              requiredMessage="Please enter your email address."
19                              validatorMessage="Invalid email format"
20                              value="#{userControl.selectedUser.email}">
21                     <f:validateRegex
22                         pattern="^[_A-Za-z0-9-\+]+(\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\.[A-Za-z0-9]+)*(\.[A-Za-z]{2,})$" />
23                 </h:inputText>
24                 <h:message for="email" />
25                 <h:inputText value="#{userControl.selectedUser.dob}" >
26                     <f:convertDateTime pattern="dd-MM-yyyy" />
27                 </h:inputText>
28                 <h:commandButton action="#{userControl.create()}" value="Create" />
29             </h:form>
30         </f:view>
31     </h:body>
32 </html>

Aucun commentaire:

Enregistrer un commentaire