Performing CRUD Operations Using Servlet / JSP

I am doing CRUD operations using Servlet and JSP. The following class is used to retrieve a connection from a server-maintained connection pool (Tomcat).

public final class DatabaseConnection {

    private static final DataSource dataSource;

    static {
        try {
            Context initContext = new InitialContext();
            Context context = (Context) initContext.lookup("java:/comp/env");
            dataSource = (DataSource) context.lookup("jdbc/assignment_db");
        } catch (NamingException e) {
            Logger.getLogger(DatabaseConnection.class.getName()).log(Level.SEVERE, null, e);
            throw new ExceptionInInitializerError("DataSource not initialized.");
        }
    }

    public static Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }
}

And the methods from the next class (DAO) perform CRUD operations.

public final class CountryDao {

    public Long getCurrentRow(Long id) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DatabaseConnection.getConnection();
            preparedStatement = connection.prepareStatement("select rownum from (select @rownum:=@rownum+1 as rownum, tbl.country_id from country_tbl tbl, (select @rownum:=0)t order by tbl.country_id desc)t where country_id=?");
            preparedStatement.setLong(1, id);
            resultSet = preparedStatement.executeQuery();
            return resultSet.next() ? resultSet.getLong("rownum") : 1;
        } finally {
            if (connection != null) {connection.close();}
            if (resultSet != null) {resultSet.close();}
            if (preparedStatement != null) {preparedStatement.close();}
        }
    }

    public Long rowCount() throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            connection = DatabaseConnection.getConnection();
            preparedStatement = connection.prepareStatement("select count(*) as cnt from country_tbl");
            resultSet = preparedStatement.executeQuery();
            resultSet.next();
            return resultSet.getLong("cnt");
        } finally {
            if (connection != null) {connection.close();}
            if (resultSet != null) {resultSet.close();}
            if (preparedStatement != null) {preparedStatement.close();}
        }
    }

    public List<CountryBean> getData(Long currentPage, Long pageSize) throws SQLException {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        List<CountryBean> countryBeans = new ArrayList<CountryBean>();

        try {
            connection = DatabaseConnection.getConnection();
            preparedStatement = connection.prepareStatement("select * from country_tbl order by country_id desc limit ?,?");

            //preparedStatement.setMaxRows(pageSize);
            preparedStatement.setLong(1, currentPage);
            preparedStatement.setLong(2, pageSize);
            resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                CountryBean countryBean = new CountryBean();
                countryBean.setCountryId(resultSet.getLong("country_id"));
                countryBean.setCountryName(resultSet.getString("country_name"));
                countryBean.setCountryCode(resultSet.getString("country_code"));
                countryBeans.add(countryBean);
            }
        } finally {
            if (connection != null) {connection.close();}
            if (resultSet != null) {resultSet.close();}
            if (preparedStatement != null) {preparedStatement.close();}
        }

        return countryBeans;
    }

    public boolean delete(Long id) throws SQLException {
        boolean status = false;
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DatabaseConnection.getConnection();
            preparedStatement = connection.prepareStatement("delete from country_tbl where country_id=?");
            preparedStatement.setLong(1, id);

            if (preparedStatement.executeUpdate() == 1) {
                status = true;
            }
        } finally {
            if (connection != null) {connection.close();}
            if (preparedStatement != null) {preparedStatement.close();}
        }
        return status;
    }

    public boolean delete(Long[] ids) throws SQLException {
        boolean status = false;
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DatabaseConnection.getConnection();
            connection.setAutoCommit(false);
            preparedStatement = connection.prepareStatement("delete from country_tbl where country_id=?");
            int len = ids.length;

            for (int i = 0; i < len; i++) {
                preparedStatement.setLong(1, ids[i]);
                preparedStatement.addBatch();
            }

            preparedStatement.executeBatch();
            connection.commit();
            status = true;
        } finally {
            if (connection != null) {connection.close();}
            if (preparedStatement != null) {preparedStatement.close();}
        }
        return status;
    }

    public boolean insert(String countryName, String countryCode) throws SQLException {
        boolean status = false;
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DatabaseConnection.getConnection();
            preparedStatement = connection.prepareStatement("insert into country_tbl(country_name, country_code)values(?,?)");
            preparedStatement.setString(1, countryName);
            preparedStatement.setString(2, countryCode);
            preparedStatement.executeUpdate();
            status = true;
        } finally {
            if (connection != null) {connection.close();}
            if (preparedStatement != null) {preparedStatement.close();}
        }
        return status;
    }

    public boolean update(Long countryId, String countryName, String countryCode) throws SQLException {
        boolean status = false;
        Connection connection = null;
        PreparedStatement preparedStatement = null;

        try {
            connection = DatabaseConnection.getConnection();
            preparedStatement = connection.prepareStatement("update country_tbl set country_name=?, country_code=? where country_id=?");
            preparedStatement.setString(1, countryName);
            preparedStatement.setString(2, countryCode);
            preparedStatement.setLong(3, countryId);
            preparedStatement.executeUpdate();
            status = true;
        } finally {
            if (connection != null) {connection.close();}
            if (preparedStatement != null) {preparedStatement.close();}
        }

        return status;
    }
}

These methods are named appropriately from the servlet after validation. The servlet, in turn, interacts with the JSP (along with JSTL / EL).

There is only one question. Kerry connection, preparedStatementand resultSetare all local variables for specific methods .

Can I declare them in only one place as members of a class (instance variables)? Can this maintain a consistent state?

. , : MVC:)

+3
9

( )?

, . , , . , , init() doXxx(). threadlocal (, doXxx()). javadoc. , , downunsafe DAO . (, , JPA;)).


?

! , . . . , , - , . , . , , , , .


, , API- JDBC, / / Java 7 (ARM). DB DAO, SQL- -if any.

+3

. .

E.g -

. , 5 , . ...

+1

, connection, statement resultset -, .

, dao, , , , dao .

, , , dao, , , . , , get reset , .

, @Manjeet , , . , , . , . .

, , . , ,

class Boilerplate{
  private Connection con;
  private PreparedStatement ps;

  public Boilerplate(String query){
   //initialize connection, ps and resultset
   con=DatabaseConnection.getConnection();
   ps=connection.prepareStatement(query);
  }

  destroy void Boilerplate(){
    if(con!=null)
      con.close()
    if(ps!=null)
      ps.close();
  }
}

, , destroy.

+1

:

. -. -, . .

. , , . . :

class Taxes
    {
      int count;
      /*...*/
    }

  class Taxes
    {
      static int count;
      /*...*/
    }
+1

CRUD Servlet/JSP

, CRUD jsp/servlet

...

0
res.setContentType("text/html");

// Ask for a 16K byte response buffer; do not set the content length
res.setBufferSize(16 * 1024);

PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Hello World</TITLE></HEAD>");
out.println("<BODY>");
out.println("<BIG>Less than 16K of response body</BIG>");
out.println("</BODY></HTML>");
-1

. NoInitialContextException, junit . , ? .

public final class DataSourceUtil {                     
  private static Context initCtx;
  private static Context envCtx; 
  private static DataSource dataSource;                 

  static {
    try {                                               
      // Initial a datasource for pooled connections.    
      initCtx = new InitialContext();                   
      envCtx = (Context) initCtx.lookup("java:/comp/env");     
      dataSource = (DataSource) envCtx.lookup("jdbc/ServletDB");                                                 
    } catch (NamingException e) {                       
      Logger.getLogger(DataSourceUtil.class.getName()).log(Level.SEVERE, null, e);                               
      throw new ExceptionInInitializerError("DataSource not initialized.");
  }                                                   
}                                           

  public static Connection getConnection() throws SQLException {
    return dataSource.getConnection();
  }
}

public class ConnectionTest() {
  @Test
  public void connectionTest2() {
  try {

    Connection connection = DataSourceUtil.getConnection();

  } catch (Exception e) {e.printStackTrace();}
}

:

Dec 23, 2015 9:06:46 PM com.wxz.server.dao.DataSourceUtil <clinit>
SEVERE: null
javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file:  java.naming.factory.initial
-1

You can use this Java class and create objects and call these st, con and rs respectively

{
    import java.sql.*;

    public class connectDb {

        public Statement st;
        public Connection con;
        public ResultSet rs;

        public ResultSet rs1;
        public Statement st1;

        public connectDb() {

            try {

                String driver="com.mysql.jdbc.Driver";
                String url="jdbc:mysql://localhost:3306/test1db";
                String username="root";
                String password="";
                Class.forName(driver);


                Connection con=DriverManager.getConnection(url,username,password);
                System.out.println("connected to database");
                 st=con.createStatement();
                st1=con.createStatement();


          }catch(Exception e) {
              System.out.println("ERROR" +e);
          }
      }
    }
}
-1
source
FlightHandler.java
package com.trainee.handler;
import java.io.IOException;

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

import com.trainee.dao.FlightDao;
import com.trainee.flight.Flight;

public class FlightHandler extends HttpServlet {
       private static String INSERT = "/user.jsp";
        private static String Edit = "/edit.jsp";
        private static String FlightRecord = "/listFlight.jsp";
        private FlightDao dao;

        public FlightHandler() {
            super();
            dao = new FlightDao();
        }

        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            String redirect="";
            String Id = request.getParameter("id"); 
            String TotalSeat =  request.getParameter("totalseat");
            String action = request.getParameter("action");
            if(!((Id)== null) && action.equalsIgnoreCase("insert"))
            {
                int id = Integer.parseInt(Id);
                Flight f = new Flight();
                f.setId(id);
                f.setName(request.getParameter("name"));
                int totalseat = Integer.parseInt(TotalSeat);
                f.setTotalSeat(totalseat);
                f.setCity(request.getParameter("city"));
                f.setStatus(request.getParameter("status"));
                dao.addFlight(f);
                redirect = FlightRecord;
                request.setAttribute("users", dao.getAllFlight());    
                System.out.println("Record Added Successfully");
            }



            else if (action.equalsIgnoreCase("delete")){
                String id = request.getParameter("flightId");
                int fid = Integer.parseInt(id);
                dao.removeFlight(fid);
                redirect = FlightRecord;
                request.setAttribute("users", dao.getAllFlight());
                System.out.println("Record Deleted Successfully");
            }

            else if (action.equalsIgnoreCase("editform")){          
                redirect = Edit;            
            } else if (action.equalsIgnoreCase("edit")){
                String fId = request.getParameter("flightId");
                int id = Integer.parseInt(fId);            
                Flight f = new Flight();
                f.setId(id);
                f.setCity(request.getParameter("city"));

                dao.editFlight(f);
                request.setAttribute("user", f);
                redirect = FlightRecord;
                System.out.println("Record updated Successfully");

            }
            else if (action.equalsIgnoreCase("listFlight")){
                redirect = FlightRecord;
                request.setAttribute("users", dao.getAllFlight());
             } else {
                redirect = INSERT;
            }

            RequestDispatcher rd = request.getRequestDispatcher(redirect);
            rd.forward(request, response);
        }

        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            doGet(request, response);
        }
    }
-1
source

All Articles