CRUD SERVLET

CRUD SERVLET

How to create a crud servlet?

View Answers

January 2, 2012 at 12:40 AM

Helper Class

package com.nsep.user.helper;
import java.sql.*;
import java.util.logging.Logger;

public class DataBaseUtil {

    Logger logger=Logger.getLogger("Logging");
    Connection conn;
    public DataBaseUtil()
    {
        try
        {//initializing the credentials
         Class.forName("oracle.jdbc.driver.OracleDriver");
         String serverName = "172.24.137.30";
         String portNumber = "1521";
         String sid = "ora10g";
         String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
         String username="e533336";
         String password="evWXebidv";
         conn =DriverManager.getConnection( url, username, password );
         logger.info("Connection");

        }

        catch ( SQLException sqlex ) 
        {
            logger.info("SQL Exception !! " +sqlex);            
            sqlex.printStackTrace();
        }
        catch (Exception ex)
        {
            logger.info("Exception has occured "+ex);
        }
    }
    public Connection getConn()
    {
        return conn;//returning the connection object 
    }
}

January 2, 2012 at 12:40 AM

Helper Class

package com.nsep.user.helper;
import java.sql.*;
import java.util.logging.Logger;

public class DataBaseUtil {

    Logger logger=Logger.getLogger("Logging");
    Connection conn;
    public DataBaseUtil()
    {
        try
        {//initializing the credentials
         Class.forName("oracle.jdbc.driver.OracleDriver");
         String serverName = "172.24.137.30";
         String portNumber = "1521";
         String sid = "ora10g";
         String url = "jdbc:oracle:thin:@" + serverName + ":" + portNumber + ":" + sid;
         String username="e533336";
         String password="evWXebidv";
         conn =DriverManager.getConnection( url, username, password );
         logger.info("Connection");

        }

        catch ( SQLException sqlex ) 
        {
            logger.info("SQL Exception !! " +sqlex);            
            sqlex.printStackTrace();
        }
        catch (Exception ex)
        {
            logger.info("Exception has occured "+ex);
        }
    }
    public Connection getConn()
    {
        return conn;//returning the connection object 
    }
}

January 2, 2012 at 12:42 AM

package com.nsep.user.model;
public class EmployeeBean {
    int employee_id;
    String employee_name;
    String employee_role;
    long employee_phnum;
    String password;
    //the setters to set the attributes
        public void setEmployeeName(String employee_name)
        {
            this.employee_name=employee_name;
        }
        public void setPassword(String password)
        {
            this.password=password;
        }
        public void setEmployeeRole(String employee_role)
        {
            this.employee_role=employee_role;
        }
        public void setEmployeePhone(long employee_phnum)
        {
            this.employee_phnum=employee_phnum;
        }
        public void setEmployeeId(int emp_id )
        {
            this.employee_id=emp_id;
        }
    //getters to get the attributes
        public int getEmployeeId()
        {

            return employee_id;
        }
        public String getPassword()
        {
            return password;
        }
        public String getEmployeeName()
        {
            return employee_name;
        }
        public String getEmployeeRole()
        {
            return employee_role;
        }
        public long getEmployeePhone()
        {
            return employee_phnum;
        }

January 2, 2012 at 12:44 AM

package com.nsep.user.controller;

import java.io.IOException;



import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Logger;

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




import com.nsep.user.dao.EmployeeDAO;
import com.nsep.user.model.EmployeeBean;

/**
 * Servlet implementation class EmployeeServlet
 */
public class EmployeeServlet extends HttpServlet {
     Logger logger=Logger.getLogger("Logging");
    private static final long serialVersionUID = 1L;


    /**
     * @see HttpServlet#HttpServlet()
     */
    public EmployeeServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

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


    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub

        //method to insert value to the database
        EmployeeBean eb= new EmployeeBean();
        EmployeeDAO ed= new EmployeeDAO();
        HttpSession session=request.getSession(true);

        if(request.getParameter("Operation").equals("Insert"))
        {
            String password=request.getParameter("password");
            eb.setPassword(password);
        String employee_name=request.getParameter("emp_name");
        eb.setEmployeeName(employee_name);
        String employee_role=request.getParameter("emp_role");
        eb.setEmployeeRole(employee_role);
        long employee_phnum=Long.parseLong(request.getParameter("emp_ph_num"));
        eb.setEmployeePhone(employee_phnum);

        try
        {
        //ed.insert(eb);

        int employee_id=ed.insert(eb);

        response.sendRedirect("../jsp/Employee_Registration.jsp?id="+employee_id+"&name="+employee_name+"&role="+employee_role+"&phone="+employee_phnum);

        }
        catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }





    }

        //method to Retrieve records in database


        else if(request.getParameter("Operation").equals("Update"))
        {if(session.getAttribute("id")==null)
        {
            session.removeAttribute("id");
            session.removeAttribute("name");
            session.removeAttribute("type");
            response.sendRedirect("../Home.jsp?msg=Unauthorized Access");
            logger.info("no session");
        }
        else
        {
            eb.setEmployeeId((Integer)session.getAttribute("id"));//setting the id 
            try {
                eb=ed.select(eb);
                if(eb.getEmployeeName()==null)//If the id does not exist
                {
                    response.sendRedirect("Employee_Invalid.jsp");//hv 2 chnge
                }
                else 
                {
                request.setAttribute("com.nsep.user.model.EmployeeBean", eb);
                //I need to forward the employeeBean  object from here. 
                //session.se

            RequestDispatcher rd = getServletContext().getRequestDispatcher("/jsp/Update_Emp1.jsp");


              rd.forward(request, response);      

                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //response.sendRedirect("Update_Emp.jsp?name="+employee_name+"&role="+employee_role+"&phone="+employee_phnum);
        }
        }

       // method to update records in database


        else if(request.getParameter("Operation").equals("Update2"))
        {   
            String employee_id = request.getParameter("emp_id");
            eb.setEmployeeId(Integer.parseInt(employee_id));
            String employee_name = request.getParameter("emp_name");
            eb.setEmployeeName(employee_name);
         String employee_phnum=request.getParameter("emp_ph_num");

        eb.setEmployeePhone(Long.parseLong(employee_phnum));
            String employee_role= request.getParameter("emp_role");
            eb.setEmployeeRole(employee_role);

         try {
                eb=ed.update(eb);
                request.setAttribute("com.nsep.user.model.EmployeeBean", eb);
                // to forward the eb object from here. 
                //session.se

                RequestDispatcher rd = getServletContext().getRequestDispatcher("/jsp/Update_Emp.jsp");

                rd.forward(request, response);    


            }catch (NullPointerException nlex)
            {
                nlex.printStackTrace();
            } 
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        //method to delete record 


        else if(request.getParameter("Operation").equals("Delete"))
        {
            eb.setEmployeeId(Integer.parseInt(request.getParameter("emp_id")));//setting the id 
            try {
                eb=ed.select(eb);
                if(eb.getEmployeeName()==null)//If the id does not exist
                {
                    response.sendRedirect("Employee_Invalid.jsp");
                }
                else
                {
                request.setAttribute("com.nsep.user.model.EmployeeBean", eb);
                //I need to forward the employeebean object from here. 
                //session.se

            RequestDispatcher rd = getServletContext().getRequestDispatcher("/jsp/Delete_Emp2.jsp");


              rd.forward(request, response);      
                }

            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //response.sendRedirect("Update_Emp.jsp?name="+employee_name+"&role="+employee_role+"&phone="+employee_phnum);
        }



        //*block for updating the the status as Inactive*/


        else if(request.getParameter("Operation").equals("Delete2"))
        {
            String employee_id = request.getParameter("emp_id");
            logger.info(employee_id);
            eb.setEmployeeId(Integer.parseInt(employee_id));
            try {
                eb=ed.delete(eb);
                request.setAttribute("com.nsep.user.model.EmployeeBean", eb);
                RequestDispatcher rd = getServletContext().getRequestDispatcher("/jsp/Delete_Emp.jsp");

                rd.forward(request, response);  
            }
            catch (NullPointerException nlex)
            {
                nlex.printStackTrace();
            } 
            catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        //method to search a particular record in database



        else if(request.getParameter("Operation").equals("Search"))
        {
            eb.setEmployeeId(Integer.parseInt(request.getParameter("emp_id")));//setting the id in college bean
            try {
                eb=ed.select(eb);
                if(eb.getEmployeeName()==null)//If the id does not exist
                {
                    response.sendRedirect("Employee_Invalid.jsp");//hv 2 chnge
                }
                else
                {
                request.setAttribute("com.nsep.user.model.EmployeeBean", eb);
                // to forward the employeeBean object from here. 
                //session.se

              RequestDispatcher rd = getServletContext().getRequestDispatcher("/jsp/Search_Emp.jsp");

              rd.forward(request, response);      

                }
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }




        /* block to list all the records*/

        //method to list all the records



        else if(request.getParameter("Operation").equals("searchall"))
        {   
            ArrayList<EmployeeBean> all_records=new ArrayList<EmployeeBean>();
            try {

                all_records=ed.getAllDetails();
                 logger.info(""+all_records.size());
            request.setAttribute("page", 1);
                request.setAttribute("EmployeeBean_list", all_records);
                RequestDispatcher rd = getServletContext().getRequestDispatcher("/jsp/List.jsp?page=1");

                rd.forward(request, response);  
            }
            catch (NullPointerException nlex)
            {
                nlex.printStackTrace();
            } 
            catch (SQLException e) {
            // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

    }

January 2, 2012 at 12:46 AM

DAO EXAMPLE

package com.nsep.user.dao;
import java.sql.*; 
import java.util.ArrayList;
import java.util.logging.Logger;

import com.nsep.user.helper.DataBaseUtil;

import com.nsep.user.model.EmployeeBean;
//import com.sun.corba.se.pept.transport.Connection;

public class EmployeeDAO {
    Connection conn;
    PreparedStatement statement;
    ResultSet rs;
    Logger logger=Logger.getLogger("Logging");
    public ArrayList<EmployeeBean> getAllDetails() throws SQLException
    {
        ArrayList<EmployeeBean> ar_id=new ArrayList<EmployeeBean>();
        try
        {                       
            conn =new DataBaseUtil().getConn();
            statement = conn.prepareStatement("select * from employees where empstatus='ACTIVE'");
            rs=statement.executeQuery();
            while(rs.next())
            {

                EmployeeBean eb=new EmployeeBean();;
                eb.setEmployeeId(rs.getInt(1));
                eb.setEmployeeName(rs.getString(2));
                eb.setEmployeeRole(rs.getString(3));
                eb.setEmployeePhone(rs.getLong(4));
                ar_id.add(eb);

            }

        }
        catch ( SQLException sqlex ) 
        {
            logger.info("SQL Exception !! " +sqlex);            
            sqlex.printStackTrace();
        }
        finally
        {
            statement.close();
            conn.close();
        }
        return ar_id;

    }


    //To insert values...


    public int insert(EmployeeBean eb) throws SQLException
    {   
        int employee_id=0;

        try
        {
            conn =new DataBaseUtil().getConn();
            PreparedStatement stmt=conn.prepareStatement("select seq_Employees.nextVal from dual"); 

            rs=stmt.executeQuery();
            if(rs.next())
            {
                 employee_id=rs.getInt(1);
            }


        // connect to database using DriverManager


        statement = conn.prepareStatement("INSERT INTO Employees values(?,?,?,?,?)");
        statement.setInt(1,employee_id);

        statement.setString(2,eb.getEmployeeName());
        statement.setString(3, eb.getEmployeeRole());
        statement.setLong(4, eb.getEmployeePhone());
        statement.setString(5, "ACTIVE");
        statement.executeUpdate();
        statement = conn.prepareStatement("INSERT INTO Credentials values(?,?,?,?)");
        statement.setInt(1,employee_id);
        statement.setString(2,eb.getPassword());
        statement.setString(3,eb.getEmployeeRole());
        statement.setString(4,eb.getEmployeeName());
        statement.executeUpdate();  


        }

        catch ( SQLException sqlex ) 
        {
            logger.info("SQL Exception !! " +sqlex);            
            sqlex.printStackTrace();
        }
        catch (Exception ex)
        {
            logger.info("Exception has occured "+ex);
        }
        finally
        {
        //statement.close();
        //conn.close();
        //rs.close();
        }
        return employee_id;

    }

    public EmployeeBean select(EmployeeBean eb) throws SQLException
    {
        conn =new DataBaseUtil().getConn();
        statement=conn.prepareStatement("select * from employees where empid=? and empstatus='ACTIVE'");
        statement.setInt(1, eb.getEmployeeId());
        rs=statement.executeQuery();
        if(rs.next())
        {
            //eb.setEmployeeId(rs.getInt(1));
            eb.setEmployeeName(rs.getString(2));
            eb.setEmployeeRole(rs.getString(3));
            eb.setEmployeePhone(rs.getLong(4));
        }

        return eb;
    }

    public EmployeeBean update(  EmployeeBean eb) throws SQLException
    {

        // connect to db using DriverManager
        conn =new DataBaseUtil().getConn();
         EmployeeBean nw_eb=null;
        // Create a Preparedstatement object
        try
        {
        statement=conn.prepareStatement(" update  Employees set empname=?, emprole=?, empphone=? where empid=? and empstatus='ACTIVE'");
        logger.info("Emp ID:"+eb.getEmployeeId());
        statement.setInt(4,eb.getEmployeeId());
        logger.info("setting the no");
        statement.setString(1,eb.getEmployeeName());
        statement.setString(2, eb.getEmployeeRole());
        statement.setLong(3, eb.getEmployeePhone());
        rs=statement.executeQuery();
        nw_eb=eb;
        }
        catch ( SQLException sqlex ) 
        {
            logger.info("SQL Exception !! " +sqlex);            
            sqlex.printStackTrace();
        }
        catch (Exception ex)
        {
            logger.info("Exception has occured "+ex);
        }
        finally
        {
            statement.close();
            conn.close();
            rs.close();
        }
        return nw_eb;
    }

    /*method to delete*/

    public EmployeeBean delete(EmployeeBean eb) throws SQLException
    {

        // connect to db using DriverManager
        conn =new DataBaseUtil().getConn();
        EmployeeBean nw_eb=null;
        // Create a Preparedstatement object
        try
        {   System.out.print("dfdf");
            statement=conn.prepareStatement("select * from Employees  where empid=?");

            statement.setInt(1,eb.getEmployeeId());
            //logger.info("ghgg");
            rs=statement.executeQuery();
            if(rs.next())
            {
                eb.setEmployeeId(rs.getInt(1));
                eb.setEmployeeName(rs.getString(2));
                eb.setEmployeeRole(rs.getString(3));
                eb.setEmployeePhone(rs.getLong(4));
            }
        statement=conn.prepareStatement(" update Employees set Empstatus='Inactive' where empid=?");
        //logger.info(eb.getCollegeID());
        statement.setInt(1,eb.getEmployeeId());

        rs=statement.executeQuery();

        statement=conn.prepareStatement("delete from credentials where userid=? ");
        statement.setInt(1,eb.getEmployeeId());
        //logger.info(cb.getCollegeID());
        rs=statement.executeQuery();
        nw_eb=eb;
        }
        catch ( SQLException sqlex ) 
        {
            logger.info("SQL Exception !! " +sqlex);            
            sqlex.printStackTrace();
        }
        catch (Exception ex)
        {
            logger.info("Exception has occured "+ex);
        }
        finally
        {
            statement.close();
            conn.close();
            rs.close();
        }
        return nw_eb;
    }

}

Ads









Related Tutorials/Questions & Answers:
CRUD SERVLET
CRUD SERVLET  How to create a crud servlet?   Helper Class package com.nsep.user.helper; import java.sql.*; import... com.nsep.user.dao.EmployeeDAO; import com.nsep.user.model.EmployeeBean; /** * Servlet
crud operations with foreign key constraint.
crud operations with foreign key constraint.  I neeed to know how to perform crud operations in mysql with foreign key constraint using mvc architecture i.e using servlet jsp and bean. please provide all the code so that i can
Advertisements
Servlet
Servlet  how to navigate one servlet page to another servlet page
ModuleNotFoundError: No module named 'crud'
ModuleNotFoundError: No module named 'crud'  Hi, My Python program is throwing following error: ModuleNotFoundError: No module named 'crud' How to remove the ModuleNotFoundError: No module named 'crud' error
CRUD DAO
CRUD DAO  how to create dao for create,read,update and delete?   /* *ConnectionManager * * *Version:1.0 * *Date:25-Nov-2011 * */ package com.student.dao; import java.sql.*; import org.apache.log4j.Logger
servlet
servlet  is there any way to include pdf's in servlet
servlet
servlet  what are the methods and interfaces in the servlet api ?   Servlet Tutorials
servlet
servlet  what are the all necessary configuration to run a servlet
servlet
servlet  how to interact with a servlet from a swing program
servlet
servlet  I designed 1 html form & a servlet but when I click on form I don't get output of servlet Please help
servlet
servlet  I designed 1 html form & a servlet but when I click on form I don't get output of servlet Please help
servlet
servlet  i want to create a login page with servlet using database mysql? only in servlet not in jsp plzz help me out
Servlet
override Service method in the servlet when you extend GenericServlet to create servlet as it is mandatory to override it. But, when you extend HttpServlet to create a servlet then you can't override service method as there is a need to override
servlet
servlet  i want a program for counting the no of times the servlet has been invoked
servlet
servlet  how to create a login form using servlet using submit,edit delete button
servlet
servlet  dear sir servlet and html not run on eclips plz help me
servlet
servlet  can i stoar record in variable which selected from table in servlet
servlet
of the Servlet API. It contains the classes necessary for a standard, protocol-independent servlet. Every servlet must implement the Servlet interface in one
Servlet
Servlet  I want to know the steps to write a simple servlet program... .   Hello Friend, Follow these steps: Put servlet-api.jar inside the lib folder of apache tomcat. 1)create a servlet. import java.io.*; import
Servlet
Servlet  Can a user defined function be included in a servlet? I need information regarding servlet syntax and not JSP.   Yes, you can create user defined function in Servlets. Have a look at the following link: http
servlet
servlet  I want the full coding for uploading a file in local drive D usin jsp,java class and servlet... help me thanks in advance....   ... and servlet please and thanks in advance
Servlet
Servlet  Hi, Can any one please expalin me below topics SERVLET ENGINE 2.WHY SUPER.INIT(); Thanks alot in advance!! Regards: Akash
servlet
servlet   Dear Deepak, is it compulsary to write the sevice() becoz i ve seen some example which does not ve sevice()..is it tue? plz replay me with thanks praveen
servlet
servlet  plz can anyone give me the link of javax library jar file. i badly need that. thanks in advance   Please visit the following link: Download Servlet API
servlet
servlet  I want a fully readymade project on online voting system with code in java servlet and database backend as msaccess.can u plz send me as soon as possible
Servlet
the same error <web-app> <servlet> <servlet-name>InsertServlet</servlet-name> <servlet-class>InsertServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>
SERVLET
to the servlet and if the user id is correct then a new page will be displayed with his... pass to the servlet and all the fields brlongs to that id will be appear... will be done by using jsp and servlet... Plz help me,im really tensed...........  
servlet
servlet  hi sir,this is ashok.i installed tomcat 6.0 and jdk-150.i checked the server it's working but when execute servlet program for the .class file it shows the errors javax.servlet is not exist.what can i do,please tell me
servlet
servlet  How do we define an application level scope for servlet?   Application scope uses a single namespace, which means all your pages should be careful not to duplicate the names of application scope objects
servlet
servlet   try { con=DaoPack.createConnection(); } catch(Exception e) { e.printStackTrace(); } if(request.getParameter("addproduct")!=null) { ProductBean bean=new ProductBean
servlet
servlet   try { con=DaoPack.createConnection(); } catch(Exception e) { e.printStackTrace(); } if(request.getParameter("addproduct")!=null) { ProductBean bean=new ProductBean

Ads