Example with Source Code: A simple database-driven Java web application (CRUD) implementing JSP and Servlets

You can study and implement the following examples to create a simple Java-based database-driven web application which makes use of JSP and Servlets applying a MVC (model-view-controller) principle.

Create the following files:

DatabaseConnection.java

package sample;
import java.sql.*;

public class DatabaseConnection {

    public static Connection getConnection() {
    Connection con = null;
    try {
        // change the following line to your jdbc driver
        Class.forName("com.borland.datastore.jdbc.DataStoreDriver");
        // change this to "your database url", "username", "password"
        con = DriverManager.getConnection("jdbc:borland:dslocal:C:\\a.jds","Sample","");
        System.out.println(con);
        }
        catch (Exception ex) {
        ex.printStackTrace();
        }
    return con;
    }
}

DataBean.java

package sample;

import java.util.*;
import java.sql.*;

public class DataBean {

    // Constructor:
    public DataBean() {
    }

    public Vector listAll() {
    Vector result = new Vector();
    try {
        Connection con = DatabaseConnection.getConnection();
        Statement stmt = con.createStatement();
        System.out.println(stmt);
        ResultSet rs = stmt.executeQuery("select * from table1");
        while (rs.next()) {
            Table1Bean bean = new Table1Bean();
            bean.setId(rs.getInt("id"));
            bean.setName(rs.getString("name"));
            result.add(bean);
        }
    }
        catch (SQLException ex) {
        ex.printStackTrace();
    }
    return result;
    }
}

Table1Bean.java

package sample;

public class Table1Bean {

    private int id;
    private String name;

    public Table1Bean() {
    }

    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;
    }

}

display.jsp

 <%@ page contentType="text/html; charset=UTF-8" language="java" errorPage="" %>
 <%@ page import="sample.*"%>
 <%@ page import="java.util.*"%>
 <%
    DataBean dataBean = new DataBean();
    Vector list = dataBean.listAll();
 %>
 <html>
 <head>
    <title>Display Data</title>
 </head>
 <body bgcolor="#ffffff">
    <table border="1">
       <tr>
          <th>ID</th>
          <th>NAME</th>
       </tr>
       <%
          for(int i=0; i<list.size(); i++) {
             Table1Bean bean = (Table1Bean)list.elementAt(i);
       %>
       <tr>
          <td><%=bean.getId()%></td>
          <td><%=bean.getName()%></td>
       </tr>
       <%
          }
        %>
    </table>
 </body>
 </html>

Leave a Reply

Your email address will not be published. Required fields are marked *