欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Servlet+JSP实现简单的员工CRUD(附源码)

程序员文章站 2022-07-15 08:05:10
...

Servlet+JSP实现简单的员工CRUD(附源码)

源码链接

链接:https://pan.baidu.com/s/1spZBEvrrWp4SwuQrR2WVwg 密码:65i7

环境搭建

JDK1.8以上
Tomcat 9
Mysql
Eclipse

运行效果截图

由于我们的重点放在Java后端,所以页面简陋点,能看就行
Servlet+JSP实现简单的员工CRUD(附源码)

前言

这里我们只设计一张数据表,项目虽然简单,但对Servlet+JSP和MVC设计模式有深刻的认识。在练习完该项目后,我还为大家准备了该项目的SpringMVC+Mybatis的实现版,SpringMVC+MyBatis是目前最流行的框架

项目结构

这里我用的是Maven构建的项目结构,大家也可以直接新建动态web项目。
Servlet+JSP实现简单的员工CRUD(附源码)

数据表

CREATE TABLE emp (
id int(10) NOT NULL AUTO_INCREMENT,
name varchar(255) DEFAULT NULL,
salary double DEFAULT NULL,
age int(10) DEFAULT NULL,
PRIMARY KEY (id)
)

实体类

   public class EmpEntity {
    private int id;
    private String name;
    private double salary;
    private int age;
    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 double getSalary() {
        return salary;
    }
    public void setSalary(double salary) {
        this.salary = salary;
    }
    public int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
}

DBUtil类

public class DBUtil {

//设置数据库和连接池变量
final String driver = "com.mysql.jdbc.Driver";
final String url = "jdbc:mysql://localhost:3306/emp?useUnicode=true&characterEncoding=utf8&useSSL=false" ;
final String user = "root" ;
final String password = "" ;

/**
 * 专门负责加载数据库驱动的方法
 */
public void load() {
    try {
        Class.forName( driver ) ;
        System.out.println( "数据库驱动[ " + driver + "] 加载成功." );
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
        System.out.println( "数据库驱动[ " + driver + "] 加载失败" );
    }
}

/**
 * 专门负责获得数据库连接的方法
 * @return
 */
public Connection getConnection() {

    load();

    Connection conn = null ;

    try {
        conn = DriverManager.getConnection(url, user, password);
        return conn ; 
    } catch (SQLException e) {
        throw new RuntimeException( "连接数据库失败" , e );
    }

}
//关闭连接
public void closeConnection(Connection con,PreparedStatement ps,ResultSet rs) throws SQLException{
    if(rs!=null){
        rs.close();
    }
    if(ps!=null){
        ps.close();
    }
    if(con!=null){
        con.close();
    }
}

}

EmpDao类

public class EmpDao {
DBUtil dbu=new DBUtil();
// 查找所有员工
public List<Emp> findAll() {
    List<Emp> empList = new ArrayList<Emp>();
    Connection con = null;
    PreparedStatement ps = null;
    ResultSet rs = null;
    try {
        con = dbu.getConnection();
        String sql = "SELECT id,name,salary,age FROM emp";
        ps = con.prepareStatement(sql);
        rs = ps.executeQuery();
        while (rs.next()) {
            Emp emp = new Emp();
            emp.setId(rs.getInt("id"));
            emp.setName(rs.getString("name"));
            emp.setSalary(rs.getDouble("salary"));
            emp.setAge(rs.getInt("age"));
            empList.add(emp);
        }
    } catch (SQLException e) {
        e.printStackTrace();
        ;
    } finally {
        try {
            dbu.closeConnection(con, ps, rs);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    return empList;
}

public void addEmp(Emp emp){
    Connection con=null;
    PreparedStatement ps=null;
    String sql="INSERT INTO emp(name,salary,age) values(?,?,?)";
    try {

        con = dbu.getConnection();
        ps=con.prepareStatement(sql);
        ps.setString(1, emp.getName());
        ps.setDouble(2, emp.getSalary());
        ps.setInt(3, emp.getAge());
        int flag=ps.executeUpdate();
        if(flag>0) {
            System.out.println("添加员工成功!");
        }

    }catch(SQLException e) {
        e.printStackTrace();
    }finally {
        try {
            dbu.closeConnection(con, ps, null);
        }catch(SQLException e) {
            e.printStackTrace();
        }
    }       
}
public void deleteEmp(int id) {
    Connection con=null;
    PreparedStatement ps=null;
    String sql="DELETE FROM emp WHERE id=?";
    try {
        con=dbu.getConnection();
        ps=con.prepareStatement(sql);
        ps.setInt(1, id);
        int flag=ps.executeUpdate();
        if(flag>0) {
            System.out.println("删除员工成功!");
        }
    }catch(SQLException e) {
        e.printStackTrace();
    }finally {
        try {
            dbu.closeConnection(con, ps, null);
        }catch(SQLException e) {
            e.printStackTrace();
        }
    }
}
public Emp loadEmp(int id){
    Emp emp = null;
    Connection con=null;
    PreparedStatement ps=null;
    ResultSet rs=null;
    try {
        con=dbu.getConnection();
        String sql="select * from emp where id =?";
        ps=con.prepareStatement(sql);
        ps.setInt(1, id);
        rs=ps.executeQuery();
        while(rs.next()){
            emp=new Emp();
            emp.setId(rs.getInt("id"));
            emp.setName(rs.getString("name"));
            emp.setSalary(rs.getDouble("salary"));
            emp.setAge(rs.getInt("age"));
        }
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        try {
            dbu.closeConnection(con, ps, null);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return emp;
}   

public void updateEmp(Emp emp) {
    Connection con=null;
    PreparedStatement ps=null;
    String sql="UPDATE emp SET name=?,salary=?,age=? where id=?";
    try {
        con=dbu.getConnection();
        ps=con.prepareStatement(sql);
        ps.setString(1, emp.getName());
        ps.setDouble(2, emp.getSalary());
        ps.setInt(3, emp.getAge());
        ps.setInt(4, emp.getId());
        int flag=ps.executeUpdate();
        if(flag>0) {
            System.out.println("更新成功!");
        }
    }catch(SQLException e) {
        e.printStackTrace();
    }finally {
        try {
            dbu.closeConnection(con, ps, null);
        }catch(SQLException e) {
            e.printStackTrace();
        }
    }
}

}

EmpServlet类

public class EmpServlet extends HttpServlet {
private EmpDao empDao = new EmpDao();
private static final long serialVersionUID = 1L;

public EmpServlet() {
    super();
}

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

}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    request.setCharacterEncoding("utf-8");
    response.setContentType("text/html;charset=utf-8");
    String url = request.getRequestURI();
    String action = request.getRequestURI().substring(url.lastIndexOf('/') + 1, url.lastIndexOf('.'));
    if ("list".equals(action)) {
        List<Emp> listEmp = empDao.findAll();
        request.setAttribute("listEmp", listEmp);
        request.getRequestDispatcher("listEmp.jsp").forward(request, response);
    } else if ("add".equals(action)) {
        Emp emp = new Emp();
        emp.setName(request.getParameter("name"));
        emp.setSalary(Double.parseDouble(request.getParameter("salary")));
        emp.setAge(Integer.parseInt(request.getParameter("age")));
        empDao.addEmp(emp);
        response.sendRedirect("list.do");
    } else if ("delete".equals(action)) {
        int id = Integer.parseInt(request.getParameter("id"));
        empDao.deleteEmp(id);
        response.sendRedirect("list.do");
    } else if ("load".equals(action)) {
        Emp emp = empDao.loadEmp(Integer.parseInt(request.getParameter("id")));
        request.setAttribute("emp", emp);
        request.getRequestDispatcher("empInfo.jsp").forward(request, response);
    } else if ("update".equals(action)) {
        Emp emp = new Emp();
        emp.setId(Integer.parseInt(request.getParameter("id")));
        emp.setName(request.getParameter("name"));
        emp.setSalary(Double.parseDouble(request.getParameter("salary")));
        emp.setAge(Integer.parseInt(request.getParameter("age")));
        empDao.updateEmp(emp);
        response.sendRedirect("list.do");
    }

}

}

前台页面

这里就不复制过来了,直接参照源码
链接:https://pan.baidu.com/s/1spZBEvrrWp4SwuQrR2WVwg 密码:65i7

相关标签: a's'f' a's'f'd'