Why packaging is important ? Original code was pretty straight forward Java coding which looks and works quite smoothly . However , all compiled classes appear to be placed in one folder WEB-INF/classes/ and in some way this minor design issue hides a business logic of apps see https://www.javatpoint.com/crud-in-servlet . Once again Connection to mariadb-Server on F33 is encapsulated in separate class and matches the most recent requirements (8.0.22) . Code below is just a tutorial for Java Servlets code writing rather then competitor for JSF && JPA
Orinal code may be found at https://www.javatpoint.com/crud-in-servlet .
Application is starting from HTML form
[tomcat@server33fedora ServletCRUD0121]$ cat index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body bgcolor='C0C0C0'>
<h1>Add New Employee</h1>
<form action="SaveServlet" 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>Country:</td><td>
<select name="country" style="width:150px">
<option>India</option>
<option>USA</option>
<option>UK</option>
<option>Other</option>
</select>
</td></tr>
<tr><td colspan="2"><input type="submit" value="Save Employee"/></td></tr>
</table>
</form>
<br/>
<a href="ViewServlet">view employees</a>
</body>
</html>
[tomcat@server33fedora src]$ cat DBConnection.java
package mypackage.dao ;
import java.util.*;
import java.sql.*;
public class DBConnection {
public static Connection getConnection(){
String url = "jdbc:mysql://localhost/data_demo?allowPublicKeyRetrieval=true&useSSL=false&serverTimezone=UTC";
String username = "root";
String password = "*******";
System.out.println("In DBConnection.java class ");
Connection con = null;
try
{
try
{
Class.forName("com.mysql.cj.jdbc.Driver").getDeclaredConstructor().newInstance();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
con = DriverManager.getConnection(url, username, password);
}
catch (Exception e)
{
e.printStackTrace();
}
return con ;
}
}
[tomcat@server33fedora classes]$ cat ../src/EmpDao.java
package mypackage.dao ;
import java.util.*;
import java.sql.*;
import mypackage.been.Emp;
import mypackage.dao.DBConnection ;
public class EmpDao {
public static int save(Emp e) {
int status=0;
String INSERT_EMP_SQL = "INSERT INTO emp2021(name,password,email,country) values (?,?,?,?)";
try(Connection con=DBConnection.getConnection(); PreparedStatement ps=con.prepareStatement(INSERT_EMP_SQL))
{
ps.setString(1,e.getName());
ps.setString(2,e.getPassword());
ps.setString(3,e.getEmail());
ps.setString(4,e.getCountry());
status=ps.executeUpdate();
con.close();
} catch(Exception ex) { ex.printStackTrace(); }
return status;
}
public static int update(Emp e){
int status=0;
String UPDATE_EMP_SQL="update emp2021 set name=?,password=?,email=?,country=? where id=?" ;
try(Connection con=DBConnection.getConnection(); PreparedStatement ps=con.prepareStatement(UPDATE_EMP_SQL))
{
ps.setString(1,e.getName());
ps.setString(2,e.getPassword());
ps.setString(3,e.getEmail());
ps.setString(4,e.getCountry());
ps.setInt(5,e.getId());
status=ps.executeUpdate();
con.close();
} catch(Exception ex) { ex.printStackTrace(); }
return status;
}
public static int delete(int id){
int status=0;
String DELETE_EMP_SQL="delete from emp2021 where id=?" ;
try(Connection con=DBConnection.getConnection(); PreparedStatement ps=con.prepareStatement(DELETE_EMP_SQL))
{
ps.setInt(1,id);
status=ps.executeUpdate();
con.close();
} catch(Exception e) { e.printStackTrace(); }
return status;
}
public static Emp getEmployeeById(int id){
Emp e=new Emp();
String SELECT_EMP_SQL="select * from emp2021 where id=?" ; try(Connection con=DBConnection.getConnection(); PreparedStatement ps=con.prepareStatement(SELECT_EMP_SQL))
{
ps.setInt(1,id);
ResultSet rs=ps.executeQuery();
if(rs.next()){
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setPassword(rs.getString(3));
e.setEmail(rs.getString(4));
e.setCountry(rs.getString(5));
}
con.close();
} catch(Exception ex) {ex.printStackTrace();}
return e;
}
public static List<Emp> getAllEmployees() {
List<Emp> list=new ArrayList<Emp>();
String SELECT_ALL_SQL="select * from emp2021" ;
try(Connection con=DBConnection.getConnection(); PreparedStatement ps=con.prepareStatement(SELECT_ALL_SQL))
{
ResultSet rs=ps.executeQuery();
while(rs.next()){
Emp e=new Emp();
e.setId(rs.getInt(1));
e.setName(rs.getString(2));
e.setPassword(rs.getString(3));
e.setEmail(rs.getString(4));
e.setCountry(rs.getString(5));
list.add(e);
}
con.close();
} catch(Exception e) { e.printStackTrace(); }
return list;
}
}
package mypackage.code ;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
mport javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import mypackage.dao.EmpDao ;
import mypackage.bean.Emp ;
@WebServlet("/ViewServlet")
public class ViewServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("<a href='index.html'>Add New Employee</a>");
out.println("<h1>Employees List</h1>");
List<Emp> list=EmpDao.getAllEmployees();
out.print("<body bgcolor='C0C0C0'><table border='1' width='100%'");
out.print("<tr><th>Id</th><th>Name</th><th>Password</th><th>Email</th><th>Country</th><th>Edit</th><th>Delete</th></tr>");
for(Emp e:list) {
out.print("<tr><td>"+e.getId()+"</td><td>"+e.getName()+"</td><td>"+e.getPassword()+"</td><td>"+e.getEmail()+"</td><td>"+e.getCountry()+"</td><td><a href='EditServlet?id="+e.getId()+"'>edit</a></td><td><a href='DeleteServlet?id="+e.getId()+"'>delete</a></td></tr>");
}
out.print("</table></body>");
out.close();
}
}
tomcat@server33fedora src]$ cat EditServlet.java
package mypackage.code ;
import java.io.IOException;
import java.io.PrintWriter;
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 mypackage.dao.EmpDao ;
import mypackage.bean.Emp ;
@WebServlet("/EditServlet")
public class EditServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
// out.print("<html><body='C0C0C0'>");
out.println("<h1>Update Employee</h1>");
String sid=request.getParameter("id");
int id=Integer.parseInt(sid);
Emp e=EmpDao.getEmployeeById(id);
out.print("<form action='EditServlet2' method='post'>");
out.print("<table>");
out.print("<tr><td></td><td><input type='hidden' name='id' value='"+e.getId()+"'/></td></tr>");
out.print("<tr><td>Name:</td><td><input type='text' name='name' value='"+e.getName()+"'/></td></tr>");
out.print("<tr><td>Password:</td><td><input type='password' name='password' value='"+e.getPassword()+"'/></td></tr>");
out.print("<tr><td>Email:</td><td><input type='email' name='email' value='"+e.getEmail()+"'/></td></tr>");
out.print("<tr><td>Country:</td><td>");
out.print("<select name='country' style='width:150px'>");
out.print("<option>India</option>");
out.print("<option>USA</option>");
out.print("<option>UK</option>");
out.print("<option>Other</option>");
out.print("</select>");
out.print("</td></tr>");
out.print("<tr><td colspan='2'><input type='submit' value='Edit & Save '/></td></tr>");
out.print("</table>");
out.print("</form>");
out.print("</html>");
out.close();
}
}
[tomcat@server33fedora src]$ cat EditServlet2.java
package mypackage.code ;
import java.io.IOException;
import java.io.PrintWriter;
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 mypackage.dao.EmpDao ;
import mypackage.bean.Emp ;
@WebServlet("/EditServlet2")
public class EditServlet2 extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String sid=request.getParameter("id");
int id=Integer.parseInt(sid);
String name=request.getParameter("name");
String password=request.getParameter("password");
String email=request.getParameter("email");
String country=request.getParameter("country");
Emp e=new Emp();
e.setId(id);
e.setName(name);
e.setPassword(password);
e.setEmail(email);
e.setCountry(country);
int status=EmpDao.update(e);
if(status>0){
response.sendRedirect("ViewServlet");
} else {
out.println("Sorry! unable to update record");
}
out.close();
}
}
[tomcat@server33fedora src]$ cat DeleteServlet.java
package mypackage.code ;
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 mypackage.dao.EmpDao ;
@WebServlet("/DeleteServlet")
public class DeleteServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String sid=request.getParameter("id");
int id=Integer.parseInt(sid);
EmpDao.delete(id);
response.sendRedirect("ViewServlet");
}
}
[tomcat@server33fedora src]$ cat SaveServlet.java
package mypackage.code ;
import java.io.IOException;
import java.io.PrintWriter;
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 mypackage.dao.EmpDao ;
import mypackage.bean.Emp ;
@WebServlet("/SaveServlet")
public class SaveServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String name=request.getParameter("name");
String password=request.getParameter("password");
String email=request.getParameter("email");
String country=request.getParameter("country");
Emp e=new Emp();
e.setName(name);
e.setPassword(password);
e.setEmail(email);
e.setCountry(country);
int status=EmpDao.save(e);
if(status>0){
out.print("<p>Record saved successfully!</p>");
request.getRequestDispatcher("index.html").include(request, response);
} else {
out.println("Sorry! unable to save record");
}
out.close();
}
}
[tomcat@server33fedora src]$ cat Emp.java
package mypackage.bean ;
public class Emp {
private int id;
private String name,password,email,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 setPassword(String password) {
this.password = password;
}
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;
}
}
Building ( I have some issues with Eclipse installed via snap and will make attempt to follow recent post at Fedora Magazine at my earliest convenience )
javac -cp .:$CLASSPATH ../src/DBConnection.java -d .
javac -cp .:$CLASSPATH ../src/EmpDao.java -d .
javac -cp .:$CLASSPATH ../src/DeleteServlet.java -d .
javac -cp .:$CLASSPATH ../src/EditServlet.java -d .
javac -cp .:$CLASSPATH ../src/EditServlet2.java -d .
javac -cp .:$CLASSPATH ../src/SaveServlet.java -d .
javac -cp .:$CLASSPATH ../src/DeleteServlet.java -d .
javac -cp .:$CLASSPATH ../src/ViewServlet.java -d .
*************************************
Files layout under WEB-INF/classes/
*************************************
$ cd /opt/tomcat/latest/webapps/ServletCRUD0121/WEB-INF/src
[tomcat@server33fedora src]$ ll
total 32
-rw-r--r--. 1 tomcat tomcat 764 Jan 13 14:56 DBConnection.java
-rw-r-----. 1 tomcat tomcat 713 Jan 13 15:18 DeleteServlet.java
-rw-r-----. 1 tomcat tomcat 1462 Jan 13 15:23 EditServlet2.java
-rw-r-----. 1 tomcat tomcat 2113 Jan 13 15:24 EditServlet.java
-rw-r-----. 1 tomcat tomcat 3478 Jan 13 15:05 EmpDao.java
-rw-r-----. 1 tomcat tomcat 727 Jan 13 14:42 Emp.java
-rw-r-----. 1 tomcat tomcat 1439 Jan 13 15:23 SaveServlet.java
-rw-r-----. 1 tomcat tomcat 1511 Jan 13 15:23 ViewServlet.java
tomcat@server33fedora classes]$ ls -CR
.:
mypackage
./mypackage:
bean code dao
./mypackage/bean:
Emp.class
./mypackage/code:
DeleteServlet.class EditServlet2.class EditServlet.class SaveServlet.class ViewServlet.class
./mypackage/dao:
DBConnection.class EmpDao.class
Mysql 8.0.22 table creation script :-
create database data_demo ;
CREATE TABLE emp2021 (
id int NOT NULL AUTO_INCREMENT,
name varchar(20) ,
password varchar(20) ,
email varchar(20) ,
country varchar(20) ,
PRIMARY KEY (id) );
Appreciate you sharing, great article.Much thanks again. Really Cool.
ReplyDeleteSAP Secrity training
oracle sql plsql training
go langaunage training
azure training