Thursday, December 31, 2020

How to catch SQLException in JSP working via JDBC with MySQL 8.0.22 on Tomcat 9.0.41

 Encapsulate JDBC setup into public DBConnection.java and afterwards in any JSP working with database we should be able import this class and invoke :-

 Connection conn = DBConnection.createConnection();

Define public class DBConnection.java and static method inside named createConnection()

 [tomcat@sever33fedora src]$ cat DBConnection.java

package net.javaguides.jsp.jdbc.database;

import java.sql.Connection;

import java.sql.DriverManager;

public class DBConnection {

 public static Connection createConnection()

 {

     String url = "jdbc:mysql://localhost/ebookshop?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC";

     String username = "root"; 

     String password = "root"; 

     out.println("In DBConnection.java class ");

     Connection conn = null;

try  {

 try  {  

Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance();

 }   catch (ClassNotFoundException e)    {  

                e.printStackTrace();  

        }   

           conn = DriverManager.getConnection(url, username, password); 

      }   catch (Exception e)   {  

        e.printStackTrace(); 

     }   

   return conn ; 

   }

}

[tomcat@sever33fedora GuruVerify]$ cat  WebUpdateExt.jsp         
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.SQLException"%>
<%@page import="net.javaguides.jsp.jdbc.database.DBConnection"%>
<%@page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>

<%
String query = "update books set author = ?, title = ?  where id = ?";  
try(Connection conn
=DBConnection.createConnection(); PreparedStatement Stat = conn.prepareStatement(query)) 

  {  
        Statement stmt = conn.createStatement();  
        String avtor = request.getParameter("param1") ;
        String nazv =  request.getParameter("param2") ;
        String code =  request.getParameter("param3") ;
        int key = Integer.parseInt(code);

        Stat.setString(1, avtor);
        Stat.setString(2, nazv);
        Stat.setInt(3, key);
        Stat.executeUpdate();


   String strSelect = "select id, author, title, price, qty from books";
   out.println("The SQL statement is: " + strSelect + "\n");

   out.println("<br>");
   out.println("<br>");

        ResultSet rset = stmt.executeQuery(strSelect);

  out.println("The records selected are:");
  int rowCount = 0;
  out.println("<html>");
  out.println("<body bgcolor=\"C0C0C0\">");
  out.println("<table border=\"2\">");
  while(rset.next()) {
           int id = rset.getInt("id");
           String author = rset.getString("author");
           String title = rset.getString("title");
           double price = rset.getDouble("price");
           int    qty   = rset.getInt("qty");
           out.println("<tr>");
           out.println("<td>");
           out.println(Integer.toString(id)+','+author+','+title + ", " + price + ", " + qty);
           out.println("</td>");
           out.println("</tr>");
           ++rowCount;
        }   
 }  catch (SQLException e) {

      throw new ServletException("SQL failed!", e);
 }

  out.println("</table>");  
  out.println("</body>");
  out.println("</html>");
%>
[tomcat@sever33fedora GuruVerify]$ cat  WebInsertExt.jsp
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.SQLException"%>

<%@page import="net.javaguides.jsp.jdbc.database.DBConnection"%>
<%@page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
String query = "INSERT INTO books(id,title,author,price,qty) VALUES(?,?,?,?,?)";
try(Connection conn = DBConnection.createConnection(); PreparedStatement Stat = conn.prepareStatement(query))
  {   

        Statement stmt = conn.createStatement();  
        String code =  request.getParameter("param1") ;
        String nazv =  request.getParameter("param2") ;
        String avtor = request.getParameter("param3") ;
        String price  =  request.getParameter("param4") ;
        String quantity = request.getParameter("param5") ;

        int key = Integer.parseInt(code);
        double dprice  = Double.parseDouble(price+"d");
        int qntity = Integer.parseInt(quantity);

        Stat.setInt(1, key);
        Stat.setString(2, nazv);
        Stat.setString(3, avtor);
        Stat.setDouble(4, dprice);
        Stat.setInt(5, qntity);

        Stat.executeUpdate();


   String strSelect = "select id, author, title, price, qty from books";
   out.println("The SQL statement is: " + strSelect + "\n");

   out.println("<br>");
   out.println("<br>");

        ResultSet rset = stmt.executeQuery(strSelect);

  out.println("The records selected are:");
  int rowCount = 0;
  out.println("<html>");
  out.println("<body bgcolor=\"C0C0C0\">");
  out.println("<table border=\"2\">");
  while(rset.next()) {
           int id = rset.getInt("id");
           String author = rset.getString("author");
           String title = rset.getString("title");
           double price1 = rset.getDouble("price");
           int    qty   = rset.getInt("qty");
           out.println("<tr>");
           out.println("<td>");
           out.println(Integer.toString(id)+','+author+','+title + ", " + price1 + ", " + qty);
           out.println("</td>");
           out.println("</tr>");
           ++rowCount;
        }
 }  catch (SQLException e) {

   throw new ServletException("SQL failed!", e);
 }

  out.println("</table>");  
  out.println("</body>");
  out.println("</html>");
%>
[tomcat@sever33fedora GuruVerify]$ cat WebWorkExt.jsp            
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.SQLException"%>
<%@page import="net.javaguides.jsp.jdbc.database.DBConnection"%>
<%@page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
try(Connection conn = DBConnection.createConnection(); Statement stmt = conn.createStatement())
 {

   String strSelect = "select id, author, title, price, qty from books";
   out.println("The SQL statement is: " + strSelect + "\n");
   out.println("<br>");
   out.println("<br>");

        ResultSet rset = stmt.executeQuery(strSelect);

   out.println("The records selected are:");
   int rowCount = 0;
   out.println("<html>");
   out.println("<body bgcolor=\"C0C0C0\">");
   out.println("<table border=\"2\">");
    while(rset.next()) {
           int    id = rset.getInt("id");
           String author = rset.getString("author");
           String title = rset.getString("title");
           double price = rset.getDouble("price");
           int    qty   = rset.getInt("qty");
           out.println("<tr>");
           out.println("<td>");
           out.println(Integer.toString(id)+','+author+','+title + ", " + price + ", " + qty);
           out.println("</td>");
           out.println("</tr>");
           ++rowCount;
     } 
 } catch (SQLException e) {

      throw new ServletException("SQL failed!", e);
 }

  out.println("</table>");  
  out.println("</body>");
  out.println("</html>");
%>

A sample of html form accepting data and invoking JSP

[tomcat@sever33fedora GuruVerify]$ cat ThreeParamsForm.html 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> 
<HTML><HEAD><TITLE>Collecting Three Parameters</TITLE></HEAD> 
<BODY BGCOLOR="#C0C0C0"> 
<H1 ALIGN="CENTER">Updating MySQL Table via JDBC</H1> 
<FORM ACTION="WebUpdateExt.jsp"> 
<TABLE BORDER="2"> 
<tr> 
<td> 
Update Author: <INPUT TYPE="TEXT" NAME="param1"> 
</td> 
</tr> 
<tr> 
<td> 
Update Title: <INPUT TYPE="TEXT" NAME="param2"> 
</td> 
</tr> 
<tr> 
<td> 
Key Record's Code : <INPUT TYPE="TEXT" NAME="param3"> 
</td> 
</tr> 
<tr> 
<td> 
<CENTER><INPUT TYPE="SUBMIT"></CENTER> 
</td> 
</tr> 
</TABLE> 
</FORM> 
</BODY></HTML>

FILE LAYOUT

.:
FiveParamsForm.html  images  WEB-INF  WebUpdateExt.jsp
index.jsp  ThreeParamsForm.html  WebInsertExt.jsp  WebWorkExt.jsp
./images:
tomcat.gif
./WEB-INF:
classes  lib  src  web.xml
./WEB-INF/classes:
net
./WEB-INF/classes/net:
javaguides
./WEB-INF/classes/net/javaguides:
jsp
./WEB-INF/classes/net/javaguides/jsp:
jdbc
./WEB-INF/classes/net/javaguides/jsp/jdbc:
database
./WEB-INF/classes/net/javaguides/jsp/jdbc/database:
DBConnection.class
./WEB-INF/lib:
 mysql-connector-java-8.0.22.jar
./WEB-INF/src:
DBConnection.java



Wednesday, December 30, 2020

Refactoring Java CRUD App to be deployed to Tomcat 9.0.41 (MySQL 8.0.22)

Consider code provided by https://www.javaguides.net/2019/03/jsp-servlet-jdbc-mysql-crud-example-tutorial.html 

Upgrade MySQL up to 8.0.22 would affect JDBC setup mentioned in post above utilizing mysql-connector-java-8.0.13.jar. Refactoring this code for the most recent version of MySQL follows below.  We also intend to add DBConnection.java and update correspondingly UserDAO.java, encapsulating JDBC setup into public DBConnection.java  as public static method createConnection(). The only jars been placed under WEB-INF/lib are jstl-1.2.jar  and    mysql-connector-java-8.0.22.jar

[tomcat@sever33fedora classes]$ cat ../src/DBConnection.java
package net.javaguides.usermanagement.model;
 
import java.sql.Connection;
import java.sql.DriverManager;
 
public class DBConnection {
 public static Connection createConnection()
 {
     String url = "jdbc:mysql://localhost/demo?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC";

     String username = "root"; 
     String password = "root"; 
     System.out.println("In DBConnection.java class ");
     Connection conn = null;
      
     try
     {
         try
         {
           Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance();
         } 
         catch (ClassNotFoundException e)
         {
            e.printStackTrace();
         }       
          conn = DriverManager.getConnection(url, username, password); 
     } 
     catch (Exception e) 
     {
        e.printStackTrace();
     }   
      return conn ; 
 }
}
[tomcat@sever33fedora classes]$ cat  ../src/UserDAO.java                       
package net.javaguides.usermanagement.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import net.javaguides.usermanagement.model.User;
import net.javaguides.usermanagement.model.DBConnection ;

public class UserDAO {

  private static final String INSERT_USERS_SQL = "INSERT INTO users" + "  (name, email, country) VALUES " +
        " (?, ?, ?);";

 private static final String SELECT_USER_BY_ID = "select id,name,email,country from users where id =?";
 private static final String SELECT_ALL_USERS = "select * from users";
 private static final String DELETE_USERS_SQL = "delete from users where id = ?;";
 private static final String UPDATE_USERS_SQL = "update users set name = ?,email= ?, country =? where id = ?;";


  public void insertUser(User user) throws SQLException {
       System.out.println(INSERT_USERS_SQL);
       try(Connection connection = DBConnection.createConnection();PreparedStatement preparedStatement = 
connection.prepareStatement(INSERT_USERS_SQL))
{ preparedStatement.setString(1, user.getName()); preparedStatement.setString(2, user.getEmail()); preparedStatement.setString(3, user.getCountry()); System.out.println(preparedStatement); preparedStatement.executeUpdate(); } catch (SQLException e) { printSQLException(e); } } public User selectUser(int id) { User user = null; try(Connection connection = DBConnection.createConnection();PreparedStatement preparedStatement =
connection.prepareStatement(SELECT_USER_BY_ID))
{ preparedStatement.setInt(1, id); System.out.println(preparedStatement); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { String name = rs.getString("name"); String email = rs.getString("email"); String country = rs.getString("country"); user = new User(id, name, email, country); } } catch (SQLException e) { printSQLException(e); } return user; } public List < User > selectAllUsers() { List < User > users = new ArrayList < > (); try(Connection connection = DBConnection.createConnection();PreparedStatement preparedStatement =
connection.prepareStatement(SELECT_ALL_USERS))
{ System.out.println(preparedStatement); ResultSet rs = preparedStatement.executeQuery(); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String email = rs.getString("email"); String country = rs.getString("country"); users.add(new User(id, name, email, country)); } } catch (SQLException e) { printSQLException(e); } return users; } public boolean deleteUser(int id) throws SQLException { boolean rowDeleted = true ; try(Connection connection = DBConnection.createConnection();PreparedStatement statement =
connection.prepareStatement(DELETE_USERS_SQL))
{ statement.setInt(1, id); rowDeleted = statement.executeUpdate() > 0; } catch (SQLException e) { printSQLException(e); } return rowDeleted; } public boolean updateUser(User user) throws SQLException { boolean rowUpdated = true ; try(Connection connection = DBConnection.createConnection();PreparedStatement statement =
connection.prepareStatement(UPDATE_USERS_SQL))
{ statement.setString(1, user.getName()); statement.setString(2, user.getEmail()); statement.setString(3, user.getCountry()); statement.setInt(4, user.getId()); rowUpdated = statement.executeUpdate() > 0; } catch (SQLException e) { printSQLException(e); } return rowUpdated; } private void printSQLException(SQLException ex) { for (Throwable e: ex) { if (e instanceof SQLException) { e.printStackTrace(System.err); System.err.println("SQLState: " + ((SQLException) e).getSQLState()); System.err.println("Error Code: " + ((SQLException) e).getErrorCode()); System.err.println("Message: " + e.getMessage()); Throwable t = ex.getCause(); while (t != null) { System.out.println("Cause: " + t); t = t.getCause(); } } } } }
Compile source files
 $  javac -cp .:$CLASSPATH ../src/DBConnection.java -d  .  
 $  javac -cp .:$CLASSPATH ../src/User.java -d  . 
 $  javac -cp .:$CLASSPATH ../src/UserDAO.java -d  .
 $  javac -cp .:$CLASSPATH ../src/UserServlet.java -d  .
FILES LAYOUT

[tomcat@server33fedora WEB-INF]$ ls -CR
.:
classes  lib  src

./classes:
net

./classes/net:
javaguides

./classes/net/javaguides:
usermanagement

./classes/net/javaguides/usermanagement:
dao  model  web

./classes/net/javaguides/usermanagement/dao:
UserDAO.class

./classes/net/javaguides/usermanagement/model:
DBConnection.class  User.class

./classes/net/javaguides/usermanagement/web:
UserServlet.class

./lib:
jstl-1.2.jar  mysql-connector-java-8.0.22.jar

./src:
DBConnection.java  UserDAO.java  User.java  UserServlet.java














































Definition of User.java been proposed in original link
package net.javaguides.usermanagement.model;

/**
 * User.java
 * This is a model class represents a User entity
 * @author Ramesh Fadatare
 *
 */
public class User {
    protected int id;
    protected String name;
    protected String email;
    protected String country;

    public User() {}

    public User(String name, String email, String country) {
        super();
        this.name = name;
        this.email = email;
        this.country = country;
    }
    public User(int id, String name, String email, String country) {
        super();
        this.id = id;
        this.name = name;
        this.email = email;
        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 getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getCountry() {
        return country;
    }
    public void setCountry(String country) {
        this.country = country;
    }
}

Tuesday, December 29, 2020

Deployment Java CRUD App to Tomcat 9.0.40 (MySQL 8.0.22)

Encapsulate JDBC setup into public DBConnection.java and afterwards in any JSP working with database we should be able import this class and invoke :-

 Connection conn = DBConnection.createConnection();

Define public class DBConnection.java and static method inside named createConnection()

 [tomcat@sever33fedora src]$ cat DBConnection.java

package net.javaguides.jsp.jdbc.database;

import java.sql.Connection;

import java.sql.DriverManager;

public class DBConnection {

 public static Connection createConnection()

 {

     String url = "jdbc:mysql://localhost/ebookshop?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC";

     String username = "root"; 

     String password = "root"; 

     System.out.println("In DBConnection.java class ");

     Connection conn = null;

     try

     {

         try

         {    

 Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance();

         } 

         catch (ClassNotFoundException e)

         {

            e.printStackTrace();

         }       

         conn = DriverManager.getConnection(url, username, password); 

     } 

     catch (Exception e) 

     {

        e.printStackTrace();

     }   

      return conn ; 

 }

}

[tomcat@sever33fedora GuruVerify]$ cat WebWorkExt.jsp

<%@page import="java.sql.ResultSet"%>

<%@page import="java.sql.Statement"%>

<%@page import="java.sql.DriverManager"%>

<%@page import="java.sql.Connection"%>

<%@page import="net.javaguides.jsp.jdbc.database.DBConnection"%>

<%@page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>

<%

    Connection conn = DBConnection.createConnection();

    Statement stmt = conn.createStatement();

    String strSelect = "select id, author, title, price, qty from books";

    out.println("The SQL statement is: " + strSelect + "\n");

    out.println("<br>");

    out.println("<br>");

         ResultSet rset = stmt.executeQuery(strSelect);

    out.println("The records selected are:");

   int rowCount = 0;

   out.println("<html>");

   out.println("<body bgcolor=\"C0C0C0\">");

   out.println("<table border=\"2\">");

   while(rset.next()) {

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

            String author = rset.getString("author");

            String title = rset.getString("title");

            double price = rset.getDouble("price");

            int    qty   = rset.getInt("qty");

            out.println("<tr>");

            out.println("<td>");

            out.println(Integer.toString(id)+','+author+','+title + ", " + price + ", " + qty);

            out.println("</td>");

            out.println("</tr>");

            ++rowCount;

         }

   out.println("</table>"); 

   out.println("</body>");

   out.println("</html>");

%>

[tomcat@sever33fedora GuruVerify]$ cat WebUpdateExt.jsp

<%@page import="java.sql.ResultSet"%>

<%@page import="java.sql.Statement"%>

<%@page import="java.sql.DriverManager"%>

<%@page import="java.sql.Connection"%>

<%@page import="java.sql.PreparedStatement"%>

<%@page import="java.sql.Statement"%>

<%@page import="net.javaguides.jsp.jdbc.database.DBConnection"%>

<%@page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>

<%

     Connection conn = DBConnection.createConnection();

     Statement stmt = conn.createStatement(); 

     String avtor = request.getParameter("param1") ;

     String nazv =  request.getParameter("param2") ;

     String code =  request.getParameter("param3") ;

     int key = Integer.parseInt(code);

         String query = "update books set author = ?, title = ?  where id = ?";

         PreparedStatement Stat = conn.prepareStatement(query);

         Stat.setString(1, avtor);

         Stat.setString(2, nazv);

         Stat.setInt(3, key);

         Stat.executeUpdate();

    String strSelect = "select id, author, title, price, qty from books";

    out.println("The SQL statement is: " + strSelect + "\n");

    out.println("<br>");

    out.println("<br>");

         ResultSet rset = stmt.executeQuery(strSelect);

   System.out.println("The records selected are:");

   int rowCount = 0;

   out.println("<html>");

   out.println("<body bgcolor=\"C0C0C0\">");

   out.println("<table border=\"2\">");

   while(rset.next()) {

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

            String author = rset.getString("author");

            String title = rset.getString("title");

            double price = rset.getDouble("price");

            int    qty   = rset.getInt("qty");

            out.println("<tr>");

            out.println("<td>");

            out.println(Integer.toString(id)+','+author+','+title + ", " + price + ", " + qty);

            out.println("</td>");

            out.println("</tr>");

            ++rowCount;

         }

   out.println("</table>"); 

   out.println("</body>");

   out.println("</html>");

%>

[tomcat@sever33fedora GuruVerify]$ cat WebInsertExt.jsp

<%@page import="java.sql.ResultSet"%>

<%@page import="java.sql.Statement"%>

<%@page import="java.sql.DriverManager"%>

<%@page import="java.sql.Connection"%>

<%@page import="java.sql.PreparedStatement"%>

<%@page import="java.sql.Statement"%>

<%@page import="net.javaguides.jsp.jdbc.database.DBConnection"%>

<%@page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>

<%

         Connection conn = DBConnection.createConnection();

         Statement stmt = conn.createStatement(); 

         String code =  request.getParameter("param1") ;

         String nazv =  request.getParameter("param2") ;

         String avtor = request.getParameter("param3") ;

         String price  =  request.getParameter("param4") ;

         String quantity = request.getParameter("param5") ;

         int key = Integer.parseInt(code);

         double dprice  = Double.parseDouble(price+"d");

         int qntity = Integer.parseInt(quantity);

         String query = "INSERT INTO books(id,title,author,price,qty) "

            + "VALUES(?,?,?,?,?)";

         PreparedStatement Stat = conn.prepareStatement(query);

         Stat.setInt(1, key);

         Stat.setString(2, nazv);

         Stat.setString(3, avtor);

         Stat.setDouble(4, dprice);

         Stat.setInt(5, qntity);

         Stat.executeUpdate();

    String strSelect = "select id, author, title, price, qty from books";

    out.println("The SQL statement is: " + strSelect + "\n");

    out.println("<br>");

    out.println("<br>");

         ResultSet rset = stmt.executeQuery(strSelect);

   System.out.println("The records selected are:");

   int rowCount = 0;

   out.println("<html>");

   out.println("<body bgcolor=\"C0C0C0\">");

   out.println("<table border=\"2\">");

   while(rset.next()) {

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

            String author = rset.getString("author");

            String title = rset.getString("title");

            double price1 = rset.getDouble("price");

            int    qty   = rset.getInt("qty");

            out.println("<tr>");

            out.println("<td>");

            out.println(Integer.toString(id)+','+author+','+title + ", " + price1 + ", " + qty);

            out.println("</td>");

            out.println("</tr>");

            ++rowCount;

         }

   out.println("</table>"); 

   out.println("</body>");

   out.println("</html>");

%>

A sample of html form accepting data and invoking JSP

[tomcat@sever33fedora GuruVerify]$ cat ThreeParamsForm.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML><HEAD><TITLE>Collecting Three Parameters</TITLE></HEAD>
<BODY BGCOLOR="#C0C0C0">
<H1 ALIGN="CENTER">Updating MySQL Table via JDBC</H1>
<FORM ACTION="WebUpdateExt.jsp">

<TABLE BORDER="2">
<tr>
<td>
Update Author: <INPUT TYPE="TEXT" NAME="param1">
</td>
</tr>
<tr>
<td>
Update Title: <INPUT TYPE="TEXT" NAME="param2">
</td>
</tr>
<tr>
<td>
Key Record's Code : <INPUT TYPE="TEXT" NAME="param3">
</td>
</tr>
<tr>
<td>
<CENTER><INPUT TYPE="SUBMIT"></CENTER>
</td>
</tr>
</TABLE>
</FORM>
</BODY></HTML>

FILE LAYOUT
.:
FiveParamsForm.html  images  WEB-INF  WebUpdateExt.jsp
index.jsp  ThreeParamsForm.html  WebInsertExt.jsp  WebWorkExt.jsp
./images:
tomcat.gif
./WEB-INF:
classes  lib  src  web.xml
./WEB-INF/classes:
net
./WEB-INF/classes/net:
javaguides
./WEB-INF/classes/net/javaguides:
jsp
./WEB-INF/classes/net/javaguides/jsp:
jdbc
./WEB-INF/classes/net/javaguides/jsp/jdbc:
database
./WEB-INF/classes/net/javaguides/jsp/jdbc/database:
DBConnection.class
./WEB-INF/lib:
 mysql-connector-java-8.0.22.jar
./WEB-INF/src:
DBConnection.java



Sunday, December 27, 2020

Attempt to deploy "Employee Register" to Tomcat 9.0.40 (MySQL 8.0.22)

UPDATE 01/01/2021

See also    Refactoring Java CRUD App to be deployed to Tomcat 9.0.41 (MySQL 8.0.22)

END UPDATE

As far as I can see any Java CRUD App would require a hack kind  of  described below , no matter is it "update" or "insert" or "select" JDBC setup doesn't work as it did earlier . Code bellow - invoking  Connection "conn = DBConnection.createConnection();" along with setup JDBC encapsulated into DBConnection.java works for me. All updates to original code are marked bold.

Original code been refactored was taken from 

https://www.javaguides.net/2019/03/servlet-jsp-jdbc-mysql-example.html

However, inserts fails to commit on the most recent version of MySQL 8.0.22.

Following bellow are the only Java classes I was forced to update to get the job done.  Recreate table 

CREATE TABLE  employee (
   id int(3) NOT NULL  AUTO_INCREMENT,
   first_name varchar(20) DEFAULT NULL,
   last_name varchar(20) DEFAULT NULL,
   username varchar(250) DEFAULT NULL,
   password  varchar(20) DEFAULT NULL,
   address varchar(45) DEFAULT NULL,
   contact varchar(45) DEFAULT NULL,
   PRIMARY KEY (id)
)  ;

[tomcat@server33fedora src]$ cat  DBConnection.java
package net.javaguides.jsp.jdbc.database;
import java.sql.Connection;
import java.sql.DriverManager;
 
public class DBConnection {
 public static Connection createConnection()
 {
     String url = "jdbc:mysql://localhost/mysql_database?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC";
     String username = "root"; 
     String password = "root"; 
          Connection conn = null;
     try
     {
         try
         {
           Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance();
         } 
         catch (ClassNotFoundException e)
         {
            e.printStackTrace();
         }       
         conn = DriverManager.getConnection(url, username, password); 
     } 
     catch (Exception e) 
     {
        e.printStackTrace();
     }   
      return conn ; 
 }
}
[tomcat@server33fedora src]$ cat  EmployeeDao.java
package net.javaguides.jsp.jdbc.database;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import net.javaguides.jsp.jdbc.bean.Employee;
public class EmployeeDao {
    public int registerEmployee(Employee employee) throws ClassNotFoundException {
    int result = 0 ; 
    String INSERT_USERS_SQL = "INSERT INTO employee" +
    " (first_name, last_name, username, password, address, contact) VALUES " + " (?,?,?,?,?,?);"
   try(Connection conn = DBConnection.createConnection(); preparedStatement =
conn.prepareStatement(INSERT_USERS_SQL))
      {
         preparedStatement.setString(1, employee.getFirstName());
         preparedStatement.setString(2, employee.getLastName());
         preparedStatement.setString(3, employee.getUsername());
         preparedStatement.setString(4, employee.getPassword());
         preparedStatement.setString(5, employee.getAddress());
         preparedStatement.setString(6, employee.getContact());
        
         result = preparedStatement.executeUpdate();

        } catch (SQLException e) {
            // process sql exception
            printSQLException(e);
        }
        return result;
    }
    private void printSQLException(SQLException ex) {
        for (Throwable e: ex) {
            if (e instanceof SQLException) {
                e.printStackTrace(System.err);
                System.err.println("SQLState: " + ((SQLException) e).getSQLState());
                System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
                System.err.println("Message: " + e.getMessage());
                Throwable t = ex.getCause();
                while (t != null) {
                    System.out.println("Cause: " + t);
                    t = t.getCause();
                }
            }
        }
    }
}
Notice , that JSP containing :-
 Connection conn = DBConnection.createConnection();
would require import
<%@page import="net.javaguides.jsp.jdbc.database.DBConnection"%>

*******************
NO CHANGES HERE 
*******************
[tomcat@server33fedora src]$ cat EmployeeServlet.java
package net.javaguides.employeemanagement.web;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.javaguides.jsp.jdbc.database.EmployeeDao;
import net.javaguides.jsp.jdbc.bean.Employee;
@WebServlet("/register")
public class EmployeeServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    private EmployeeDao employeeDao;

    public void init() {
        employeeDao = new EmployeeDao();
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

        String firstName = request.getParameter("firstName");
        String lastName = request.getParameter("lastName");
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String address = request.getParameter("address");
        String contact = request.getParameter("contact");

        Employee employee = new Employee();
        employee.setFirstName(firstName);
        employee.setLastName(lastName);
        employee.setUsername(username);
        employee.setPassword(password);
        employee.setContact(contact);
        employee.setAddress(address);

        try {
            employeeDao.registerEmployee(employee);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        response.sendRedirect("employeedetails.jsp");
    }
}
************************
DIRECTORY STRUCTURE
************************
[tomcat@server33fedora WEB-INF]$ ls -CR
.:
classes  lib  src

./classes:
'\'   net

./classes/net:
javaguides

./classes/net/javaguides:
employeemanagement  jsp

./classes/net/javaguides/employeemanagement:
web

./classes/net/javaguides/employeemanagement/web:
EmployeeServlet.class

./classes/net/javaguides/jsp:
jdbc

./classes/net/javaguides/jsp/jdbc:
bean  database

./classes/net/javaguides/jsp/jdbc/bean:
Employee.class

./classes/net/javaguides/jsp/jdbc/database:
DBConnection.class  EmployeeDao.class
Just one jar under lib folder
./lib:
mysql-connector-java-8.0.22.jar

./src:
DBConnection.java  EmployeeDao.java  Employee.java  EmployeeServlet.java
Replaced page employeedetails.jsp
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.Statement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.SQLException"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.SQLException"%>
<%@page import="net.javaguides.jsp.jdbc.database.DBConnection"%>
<%@page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>
<%
  
try(Connection conn = DBConnection.createConnection();
PreparedStatement preparedStatement = conn.prepareStatement("select * from employee")) { ResultSet resultSet = preparedStatement.executeQuery(); int rowCount = 0; out.println("<html>"); out.println("<body bgcolor=\"C0C0C0\">"); out.println("<table border=\"2\">"); while(resultSet.next()) { int id = resultSet.getInt("id"); String first_name = resultSet.getString("first_name"); String last_name = resultSet.getString("last_name"); String username = resultSet.getString("username"); String address = resultSet.getString("address"); out.println("<tr>"); out.println("<td>"); out.println(Integer.toString(id)+','+first_name+' '+last_name+", "+username+", "+address); out.println("</td>"); out.println("</tr>"); ++rowCount; } } catch (SQLException e) { throw new ServletException("SQL failed!", e); } out.println("</table>"); out.println("</body>"); out.println("</html>"); %>
Regarding the most recent version of employeedetails.jsp
// Original code  https://www.javaguides.net/2019/01/jsp-registration-form-jdbc-mysql-example.html
// net.javaguides.jsp.jdbc.database.DBConnection is imported as well
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
 pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*"%>
<%@page import="net.javaguides.jsp.jdbc.database.*"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
 <jsp:useBean id="employee"
  class="net.javaguides.jsp.jdbc.database.Employee" />
 <jsp:setProperty property="*" name="employee" />

 <%
  EmployeeDao employeeDao = new EmployeeDao();
  int status = employeeDao.registerEmployee(employee);
  if (status > 0) {
   out.println("You are successfully registered");
   out.println("<br>");
   out.println("<br>");
  }

// Added by B.D.

   String fName = request.getParameter("firstName");
   String lName = request.getParameter("lastName");

try(Connection conn = DBConnection.createConnection(); PreparedStatement preparedStatement =  conn.prepareStatement("select * from employee where  first_name = ? and last_name = ?"))
  {
        preparedStatement.setString(1, fName);
        preparedStatement.setString(2, lName);

      ResultSet resultSet = preparedStatement.executeQuery();

   int rowCount = 0;
   out.println("<table border=\"2\">");
   while(resultSet.next()) {
            int    id = resultSet.getInt("id");
            String first_name = resultSet.getString("first_name");
            String last_name = resultSet.getString("last_name");
            String username = resultSet.getString("username");
            String address = resultSet.getString("address");

            out.println("<tr>");
            out.println("<td>");
            out.println(Integer.toString(id)+','+first_name+' '+last_name+", "+username+", "+address);
            out.println("</td>");
            out.println("</tr>");

            ++rowCount;
     }
    }  catch (SQLException e)   {
              throw new ServletException("SQL failed!", e);
    }
   out.println("</table>");
 %>
</body>
</html>











































 











Saturday, December 26, 2020

Sample of manual build MVC Web Application for Tomcat 9.0.40

This post follows up Practice coding in Java by writing a game recently published at LXER. Focus has been done on manual invoking "javac" using standard command line options for placing in right folders packaged Java Beans and Servlets which are required by Tomcat 9 Java Web's server.  I intentionally avoid storing data in MySQL 8.0.22 database what is actually common practice, but requires the most recent updates in coding JDBC connection to database ( LTS JDK 11 ) .  Just a reminder any Java Server converts JSPs (JSFs) into system generated servlets at runtime, in particular case it is Jasper Compiler integrated into Tomcat Server.

Content of Java beans and servlets along with JSPs might be found here

https://www.wideskills.com/servlets/mini-mvc

Now create standard folders structure under $CATALINA_HOME/webapps and and invoke javac to create packaged classes

[tomcat@sever33fedora WEB-INF]$ ls -l
total 4
drwxr-xr-x. 3 tomcat tomcat  17 Dec 26 12:39 classes
drwxr-xr-x. 2 tomcat tomcat 103 Dec 26 12:28 src
-rw-r--r--. 1 tomcat tomcat 800 Dec 26 12:45 web.xml

[tomcat@sever33fedora WEB-INF]$ pwd
/opt/tomcat/latest/webapps/Rooms/WEB-INF

[tomcat@sever33fedora WEB-INF]$ ls -l src
total 12
-rw-r--r--. 1 tomcat tomcat 3273 Dec 26 12:26 GetAvailableRoomsByResidence.java
-rw-r--r--. 1 tomcat tomcat 1092 Dec 26 12:28 GetRoomsByResidenceServlet.java
-rw-r--r--. 1 tomcat tomcat  837 Dec 26 12:23 Room.java

[tomcat@sever33fedora WEB-INF]$ cd classes

$ javac -cp .:$CLASSPATH ../src/Room.java -d .
$ javac -cp .:$CLASSPATH ../src/GetAvailableRoomsByResidence.java -d .
$ javac -cp .:$CLASSPATH ../src/GetRoomsByResidenceServlet.java -d .

[tomcat@sever33fedora classes]$ ls -CR
.:
com

./com:
servlet

./com/servlet:
tutorial

./com/servlet/tutorial:
GetAvailableRoomsByResidence.class  GetRoomsByResidenceServlet.class  Room.class 

$ cd ../../
[tomcat@sever33fedora Rooms]$ pwd
/opt/tomcat/latest/webapps/Rooms 

[tomcat@sever33fedora Rooms]$ ls -l
total 12
-rw-r--r--. 1 tomcat tomcat 1080 Dec 26 12:49 displayRooms.jsp
-rw-r--r--. 1 tomcat tomcat  192 Dec 26 12:49 noRooms.jsp
-rw-r--r--. 1 tomcat tomcat  803 Dec 26 12:50 SelectHostel.jsp
drwxr-xr-x. 4 tomcat tomcat   47 Dec 26 12:45 WEB-INF