Tuesday, February 9, 2021

Refactoring one Java CRUD Application via adding two constructors to Bean class

The original application   https://www.javatpoint.com/crud-in-jsp  is using bean without any explicitly declared  constructor . To be able invoke different constructors first one for "Update","Insert", "Delete" and another one for "Select" which is supposed to be invoked explicitly we've done following updates to bean User.java. The more intensively we start to use JSP when developing applications, the more imperceptible we come to JSF technology .

package com.javatpoint.bean;

public class User {

private int id;

private String name,password,email,sex,country;

public User() {}

public User(String name, String password, String email, String sex, String country) {

        super();

        this.name = name;

        this.password = password;

        this.email = email;

        this.sex = sex;

        this.country = country;

    }

public User(int id, String name, String password, String email, String sex, String country) {

        super();

        this.id = id;

        this.name = name;

        this.password = password;

        this.email = email;

        this.sex = sex;

        this.country = country;

   }

public int getId() {

        return id;

}

public void setId(int id) {

        this.id = id;

}

public String getName() {

        return name;

}

public void setName(String name) {

        this.name = name;

}

public String getPassword() {

        return password;

}

.  .  .  .  .  .  .  .   .

}
public void setCountry(String country) {
        this.country = country;
  }

}

Due to changes to User.java class UserDao.java requires two explicit calls of second constructor to perform properly the "Select" statements

package com.javatpoint.dao;  

import java.sql.*;  

import java.util.ArrayList;  

import java.util.List;  

import com.javatpoint.bean.User;  

public class UserDao {  

public static Connection getConnection(){  

    Connection con=null;  

    try{  

        Class.forName("com.mysql.jdbc.Driver");  

        con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","*******");  

    }catch(Exception e){System.out.println(e);}  

    return con;  

}  

//  For instance adduser.jsp would call static method                     

//  UserDao.save() utilizing default constructor

public static int save(User u)  {  

    int status=0;  

    try{  

        Connection con=getConnection();  

        PreparedStatement ps=con.prepareStatement(  

"insert into register(name,password,email,sex,country) values(?,?,?,?,?)");  

        ps.setString(1,u.getName());  

        ps.setString(2,u.getPassword());  

        ps.setString(3,u.getEmail());  

        ps.setString(4,u.getSex());  

        ps.setString(5,u.getCountry());  

        status=ps.executeUpdate();  

    }catch(Exception e){System.out.println(e);}  

    return status;  

}  

public static int update(User u){  

    int status=0;  

    try{  

        Connection con=getConnection();  

        PreparedStatement ps=con.prepareStatement(  

"update register set name=?,password=?,email=?,sex=?,country=? where id=?");  

        ps.setString(1,u.getName());  

        ps.setString(2,u.getPassword());  

        ps.setString(3,u.getEmail());  

        ps.setString(4,u.getSex());  

        ps.setString(5,u.getCountry());  

        ps.setInt(6,u.getId());  

        status=ps.executeUpdate();  

    }catch(Exception e){System.out.println(e);}  

    return status;  

}  

public static int delete(User u){  

    int status=0;  

    try{  

        Connection con=getConnection();  

        PreparedStatement ps=con.prepareStatement("delete from register where id=?");  

        ps.setInt(1,u.getId());  

        status=ps.executeUpdate();  

    }catch(Exception e){System.out.println(e);}  

  return status;  

}  

public static List<User> getAllRecords(){  

    List<User> list=new ArrayList<User>();  

    try{  

        Connection con=getConnection();  

        PreparedStatement ps=con.prepareStatement("select * from register");  

        ResultSet rs=ps.executeQuery();  

        while(rs.next()){ 

            int id = rs.getInt("id");

            String name = rs.getString("name");

            String password = rs.getString("password");

            String email = rs.getString("email");

            String sex = rs.getString("sex");

            String country = rs.getString("country");

            User u=new User(id, name, password, email, sex, country);

            list.add(u);  

        }  

    }catch(Exception e){System.out.println(e);}  

    return list;  

}  

public static User getRecordById(int id){  

    User u = null;  

    try{  

        Connection con=getConnection();  

        PreparedStatement ps=con.prepareStatement("select * from register where id=?");  

        ps.setInt(1,id);  

        ResultSet rs=ps.executeQuery();  

        while(rs.next()){  

             int id1 = rs.getInt("id");

            String name1 = rs.getString("name");

            String password1 = rs.getString("password");

            String email1 = rs.getString("email");

            String sex1 = rs.getString("sex");

            String country1 = rs.getString("country");

            u = new User(id1, name1, password1, email1, sex1, country1); 

        }  

    }catch(Exception e){System.out.println(e);}  

    return u;  

}  

}  

Starting JSP :-

[tomcat@fedora33server Newstuff]$ cat index.jsp
<!DOCTYPE html>  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
<title>JSP CRUD Example</title>  
</head>  
<body bgcolor="C0C0C0">  
<h1>JSP CRUD Example</h1>  
<a href="adduserform.jsp">Add User</a>  
<a href="viewusers.jsp">View Users</a>  
 </body>  
</html>  

HTML table below would be displayed via call static method UserDao.getAllRecords() which builds strings utilizing  instances of User Bean provided by second constructor.


[tomcat@fedora33server Newstuff]$ cat viewusers.jsp
<!DOCTYPE html>  
  <html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
<title>View Users</title>  
</head>  
<body bgcolor="C0C0C0">  
<%@page import="com.javatpoint.dao.UserDao,com.javatpoint.bean.*,java.util.*"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
<h1>Users List</h1>  
<%  
List<User> list=UserDao.getAllRecords();  
request.setAttribute("list",list);  
%>  
 <table border="1" width="90%">  
<tr><th>Id</th><th>Name</th><th>Password</th><th>Email</th>  
<th>Sex</th><th>Country</th><th>Edit</th><th>Delete</th></tr>  
<c:forEach items="${list}" var="u">  
<tr><td>${u.getId()}</td><td>${u.getName()}</td><td>${u.getPassword()}</td>  
<td>${u.getEmail()}</td><td>${u.getSex()}</td><td>${u.getCountry()}</td>  
<td><a href="editform.jsp?id=${u.getId()}">Edit</a></td>  
<td><a href="deleteuser.jsp?id=${u.getId()}">Delete</a></td></tr>  
</c:forEach>  
</table>  
<br/><a href="adduserform.jsp">Add New User</a>  
</body>  
</html>

Insert row into Mariadb table using default constructor:-

[tomcat@fedora33server Newstuff]$ cat adduserform.jsp
<!DOCTYPE html>  
<html>  
<head>  
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">  
<title>Add User Form</title>  
</head>  
<body bgcolor="C0C0C0">  
<jsp:include page="userform.html"></jsp:include>  
</body>  
</html>  

[tomcat@fedora33server Newstuff]$ cat userform.html
<a href="viewusers.jsp">View All Records</a><br/>  
<h1>Add New User</h1>  
<form action="adduser.jsp" method="post">  
<table>  
<tr><td>Name:</td><td><input type="text" name="name"/></td></tr>  
<tr><td>Password:</td><td>  
<input type="password" name="password"/></td></tr>  
<tr><td>Email:</td><td><input type="email" name="email"/></td></tr>  
<tr><td>Sex:</td><td>  
<input type="radio" name="sex" value="male"/>Male   
<input type="radio" name="sex" value="female"/>Female </td></tr>  
<tr><td>Country:</td><td>  
<select name="country" style="width:155px">  
<option>France</option>  
<option>USA</option>  
<option>UK</option>  
<option>Germany</option>  
<option>Other</option>  
</select>  
</td></tr>  
<tr><td colspan="2"><input type="submit" value="Add User"/></td></tr>  
</table>  
</form>  

[tomcat@fedora33server Newstuff]$ cat adduser.jsp
<%@page import="com.javatpoint.dao.UserDao"%>  
<jsp:useBean id="u" class="com.javatpoint.bean.User"></jsp:useBean>  
<jsp:setProperty property="*" name="u"/>  
<%  
int i=UserDao.save(u);  
if(i>0){  
response.sendRedirect("adduser-success.jsp");  
}else{  
response.sendRedirect("adduser-error.jsp");  
}  
%> 

Mariadb's database and table are declared as follows :-

create database test ;

use test ;
 
 create table register (
 id  int NOT NULL AUTO_INCREMENT,
  name varchar(30) NOT NULL,
  password varchar(30) NOT NULL,
  email  varchar(30) NOT NULL,
  sex varchar(10) NOT NULL,
  country varchar(30) NOT NULL ,
  PRIMARY KEY (id) ) ;

No changes have been done  to JSP's from original source.

 





















































































No comments:

Post a Comment