Skip to main content

Simple Java Project with DB

Hi Guys.. Recently I have got question from my friend who is preparing for java test. He asked me to develop simple Java database project to retrieve and display table records from a particular table. Here I have used MySql as the DB and used JSTL as well. To run this project java mysql driver and jstl jar files should be available in the WEB-INF/lib folder. Here is DAO class
package tc.com.dao;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import tc.com.db.ConnectionFactory;
import tc.com.dto.Employee;

public class EmployeeDAOImpl {
    Connection connection;
    Statement stmt;
 
    public EmployeeDAOImpl() { }
 
    private static Connection getConnection()
            throws SQLException,
                ClassNotFoundException
    {
        Connection con = ConnectionFactory.
                getInstance().getConnection();
        return con;
    }
 
    public List viewAllEmployees(){
        String query = "select SQL_CALC_FOUND_ROWS * from employee ";
        List list = new ArrayList();
        Employee employee = null;
        try {
            connection = getConnection();
            stmt = connection.createStatement();
            ResultSet rs = stmt.executeQuery(query);
            while (rs.next()) {
                employee = new Employee();
                employee.setEmployeeId(rs.getInt("emp_id"));
                employee.setEmployeeName(rs.getString("emp_name"));
                employee.setSalary(rs.getDouble("salary"));
                employee.setDeptName(rs.getString("dept_name"));
                list.add(employee);
            }
            rs.close();
 
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }finally
        {
            try {
                if(stmt != null)
                    stmt.close();
                if(connection != null)
                    connection.close();
                } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        return list;
    }
 
}
Here is Connection Factory class
package tc.com.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
 
public class ConnectionFactory {
    //static reference to itself
    private static ConnectionFactory instance = new ConnectionFactory();
    String url = "jdbc:mysql://localhost/tc";
    String user = "root";
    String password = "root";
    String driverClass = "com.mysql.jdbc.Driver";
 
    //private constructor
    private ConnectionFactory() {
        try {
            Class.forName(driverClass);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
 
    public static ConnectionFactory getInstance()   {
        return instance;
    }
 
    public Connection getConnection() throws SQLException,
    ClassNotFoundException {
        Connection connection =
            DriverManager.getConnection(url, user, password);
        return connection;
    }
}
Here is Employee DTO class
package tc.com.dto;

public class Employee {
    private int employeeId;
    private String employeeName;
    private double salary;
    private String deptName;
 
    public int getEmployeeId() {
        return employeeId;
    }
    public void setEmployeeId(int employeeId) {
        this.employeeId = employeeId;
    }
    public String getEmployeeName() {
        return employeeName;
    }
    public void setEmployeeName(String employeeName) {
        this.employeeName = employeeName;
    }
    public double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    public String getDeptName() {
        return deptName;
    }
    public void setDeptName(String deptName) {
        this.deptName = deptName;
    }
}
Here is EmployeeServlet class
package tc.com.servlets;

import java.io.IOException;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import tc.com.dao.EmployeeDAOImpl;
import tc.com.dto.Employee;

/**
 * Servlet implementation class EmployeeServlet
 */
public class EmployeeServlet extends HttpServlet {
 private static final long serialVersionUID = 1L;
       
   
 /**
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  EmployeeDAOImpl dao = new EmployeeDAOImpl();
        List list = dao.viewAllEmployees();
        //int noOfRecords = dao.getNoOfRecords();
        //int noOfPages = (int) Math.ceil(noOfRecords * 1.0 / recordsPerPage);
        request.setAttribute("employeeList", list);
        //request.setAttribute("noOfPages", noOfPages);
        //request.setAttribute("currentPage", page);
        RequestDispatcher view = request.getRequestDispatcher("WEB-INF/jsp/displayEmployee.jsp");
        view.forward(request, response);
 }

 /**
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
 }

}
WebContent/index.jsp file
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<p><a href="employee.do">Show Employees</a></p>
</body>
</html>

WEB-INF/jsp/displayEmployee.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
        "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Employees</title>
</head>
<body>
    <table border="1" cellpadding="5" cellspacing="5">
        <tr>
            <th>Emp ID</th>
            <th>Emp Name</th>
            <th>Salary</th>
            <th>Dept Name</th>
        </tr>

        <c:forEach var="employee" items="${employeeList}">
            <tr>
                <td>${employee.employeeId}</td>
                <td>${employee.employeeName}</td>
                <td>${employee.salary}</td>
                <td>${employee.deptName}</td>
            </tr>
        </c:forEach>
    </table>
</body>
</html>

Finally the Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>DataShow</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <servlet>
    <description></description>
    <display-name>EmployeeServlet</display-name>
    <servlet-name>EmployeeServlet</servlet-name>
    <servlet-class>tc.interview3.servlets.EmployeeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>EmployeeServlet</servlet-name>
    <url-pattern>/employee.do</url-pattern>
  </servlet-mapping>
</web-app>

Comments

Popular posts from this blog

Upload CSV file using opencsv with Play 2.0.2, Scala and MongoDB

Hi Everyone... Today I'm going to explain you that how we could upload a CSV file with list of products to the MongoDB table. The way I'm describing here might me inefficient but still it is useful. We know that Scala is running on JVM and so that we can use any java library with Scala . I will use OpenCSV as a CSV parser for this program. OpenCSV is a CSV parser library for Java. No matter it is for java here we will use it with Scala. First we should have MongoDB up and running. Include following opencsv dependency in your build file. I'm using SBT as building tool. "net.sf.opencsv" % "opencsv" % "2.1" Here next I will create view file. Name of this file will be 'index.scala.html'. @(message: String)(implicit request: RequestHeader, flash:Flash, l: Lang=Lang("en")) @import play.api.i18n._ @import views.html.helper._ @main(message, null) { //print messages @if(flash.data.contains("message")){ ...

How to save Large html(data) content with Play framewrok, MongoDB and Scala

Hi all, While I was working on a project I had to save large content of data from text area filed in a form. I'm using Play Framework 2.0.2 as a web framework and using scala html templates as views. I have text area filed in my form to add html data (Actually here I'm using ace.js   that is high quality code editor. Ill give brief introduction to ace later). Ok Here I do not post form binding with model class but just think that there is a simple model class lets say Page. Most important thing is the saving part of this program. Here I have posted my save definition(function). def save = Action(parse.urlFormEncoded(maxLength = 1024 * 1000))  { implicit request =           //More code goes here.. I have not posted           Page.save(pageForm)           Redirect(Pages.show(        ...

Feedburner depricated.

Hi guys, Today I faced a big problem with Google's feedburner API. Yes that is true that Google has announced that feedburner API is deprecated. http://code.google.com/apis/feedburner/ . But I think it should not mean that its existing way of doing is not stopped. I was using feedburner from couple of months before to feed some rss feeds to a twitter account. From the feedburner they have given excellent API to do this. Actually this was excellent. It functioned really well till 2012-02-22. But today I wanted to modify some of my feeds and logged into my feedburner account and found Socialize menu was missed from the Publicize menu. I could not do anything. I did not try to get support from google becase this post. http://groups.google.com/group/feedburner-statistics/browse_thread/thread/6d5c8d8131ba0936 Only I have to do is finding another good API like feedburner.