Jsp+Servlet实现员工的增删改查

Jsp+Servlet实现员工的增删改查

收获:

  • 用一个Servlet和字符串匹配处理所有请求
  • 转发是一件事情未做完,调用另外一个组件继续做;而重定向是一件事情已经做完,再做另外一件事情。
  • 转发过程中涉及到的所有Web组件共享同一个request对象和response对象,数据的传递和共享就依赖request对象。

实体类Employee.java

package entity;

public class Employee {
    private int id;
    private String name;        //姓名
    private double salary;      //薪水
    private int age;            //年龄

    public Employee() {
        super();
    }

    public Employee(int id, String name, double salary, int age) {
        super();
        this.id = id;
        this.name = name;
        this.salary = salary;
        this.age = 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;
    }


    @Override
    public String toString() {
        return "ID为:"+id+",name:"+name+",salary:"+salary+",age:"+age;
    }




}

dao层
DBUtil.java

package dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtil {
    public static Connection getConnection() throws ClassNotFoundException, SQLException{
        Class.forName("com.mysql.jdbc.Driver");
        Connection con=DriverManager.getConnection("jdbc:mysql:///emp","root","123456");
        return con;
    }

    public static void close(Connection con) throws SQLException{
        if(con!=null){
            con.close();
        }
    }

    /*public static void main(String[] args) throws ClassNotFoundException, SQLException{
        System.out.println(DBUtil.getConnection());
    }*/
}

EmployeeDao.java

package dao;

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


import entity.Employee;

public class EmployeeDao {
    /**
     * 查询所有
     * @return
     * @throws ClassNotFoundException
     * @throws SQLException
     */
    public List findAll() throws ClassNotFoundException, SQLException{
        ArrayList emps=new ArrayList();
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;

        con=DBUtil.getConnection();
        ps=con.prepareStatement("select * from t_emp");
        rs=ps.executeQuery();

        while(rs.next()){
            Employee emp=new Employee(rs.getInt("id"),
                    rs.getString("name"),rs.getDouble("salary"),rs.getInt("age"));
            emps.add(emp);
            //System.out.println(emp);
        }

        DBUtil.close(con);
        return emps;
    }


    //增加员工
    public void save(Employee emp) throws ClassNotFoundException, SQLException{
        Connection con=null;
        PreparedStatement ps=null;

        con=DBUtil.getConnection();
        ps=con.prepareStatement("insert into t_emp(name,salary,age) values(?,?,?)");

        ps.setString(1, emp.getName());
        ps.setDouble(2, emp.getSalary());
        ps.setInt(3, emp.getAge());
        ps.executeUpdate();

        DBUtil.close(con);

    }

    //删除员工
    public void delete(int id) throws ClassNotFoundException, SQLException{
        Connection con=null;
        PreparedStatement ps=null;
        con=DBUtil.getConnection();
        String sql="delete from t_emp where id=?";
        ps=con.prepareStatement(sql);
        ps.setInt(1,id);
        ps.executeUpdate();
        DBUtil.close(con);
    }


    //修改员工信息
    public void modify(Employee emp) throws ClassNotFoundException, SQLException{
        Connection con=null;
        PreparedStatement ps=null;

        con=DBUtil.getConnection(); 
        String sql="update t_emp set name=?,salary=?,age=? where id=?";
        ps=con.prepareStatement(sql);
        ps.setString(1, emp.getName());
        ps.setDouble(2, emp.getSalary());
        ps.setInt(3, emp.getAge());
        ps.setInt(4, emp.getId());
        ps.executeUpdate();

        DBUtil.close(con);

    }

    //根据id查询员工
    public Employee findById(int id) throws ClassNotFoundException, SQLException{
        Connection con=null;
        PreparedStatement ps=null;
        ResultSet rs=null;
        Employee emp=null;

        con=DBUtil.getConnection();
        String sql="select * from t_emp where id=?";
        ps=con.prepareStatement(sql);
        ps.setInt(1, id);
        rs=ps.executeQuery();
        if(rs.next()){
            emp=new Employee(rs.getInt("id"),
                    rs.getString("name"),rs.getDouble("salary"),rs.getInt("age"));
        }
        DBUtil.close(con);
        return emp;

    }
}

ActionServlet .java

package web;

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

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

import dao.EmployeeDao;
import entity.Employee;

public class ActionServlet extends HttpServlet {


    private static final long serialVersionUID = 1L;

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        String uri=request.getRequestURI();
        String action=uri.substring(uri.lastIndexOf("/")+1,uri.lastIndexOf("."));
        EmployeeDao dao=new EmployeeDao();
        if(action.equals("list")){
            try {

                List emps = dao.findAll();
                request.setAttribute("emps", emps);

                //转发
                request.getRequestDispatcher("listEmp1.jsp").forward(request, response);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else if(action.equals("add")){
            String name=request.getParameter("name");
            double salary=Double.valueOf(request.getParameter("salary"));
            int age=Integer.valueOf(request.getParameter("age"));
            Employee emp=new Employee();
            emp.setName(name);
            emp.setSalary(salary);
            emp.setAge(age);
            try {
                dao.save(emp);

                //重定向
                response.sendRedirect("list.do");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }else if(action.equals("delete")){
            int id = Integer.valueOf(request.getParameter("id"));
            try {
                dao.delete(id);
                response.sendRedirect("list.do");
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }else if(action.equals("load")){
            int id=Integer.valueOf(request.getParameter("id"));

            try {
                Employee emp = dao.findById(id);
                request.setAttribute("emp", emp);
                request.getRequestDispatcher("updateEmp.jsp").forward(request, response);
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
            }


        }else if(action.equals("update")){
            int id=Integer.valueOf(request.getParameter("id"));
            String name=request.getParameter("name");
            double salary=Double.valueOf(request.getParameter("salary"));
            int age=Integer.valueOf(request.getParameter("age"));
            Employee emp=new Employee(id,name,salary,age);
            try {
                dao.modify(emp);
                response.sendRedirect("list.do");
            } catch (ClassNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }

}

listEmp1.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="dao.*,entity.*,java.util.*" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title heretitle>
<style>
    .row1{
        background-color:#E4E4E4;   
    }

    .row2{
        background-color:#FBD10A;   
    }
style>
head>
<body>
    <table border="1" cellpadding="0">
        <caption>员工信息caption>
        <tr>
            <td>编号td>
            <td>姓名td>
            <td>薪水td>
            <td>年龄td>
            <td>操作td>
        tr>
        <%
        EmployeeDao dao=new EmployeeDao();
        List emps=dao.findAll();
        for(int i=0;iget(i);

        %>
        <tr class="row<%=i%2+1%>">
            <td><%=emp.getId() %>td>
            <td><%=emp.getName() %>td>
            <td><%=emp.getSalary() %>td>
            <td><%=emp.getAge() %>td>
            <td>
                <a href="delete.do?id=<%=emp.getId() %>" onclick="return confirm('是否确认删除<%=emp.getName() %>信息')">删除a>
                 <a href="load.do?id=<%=emp.getId()%>">修改a>
            td>
        tr>
        <%} %>
    table>
    <p>
        <input type="button" value="增加员工" onclick="location='addEmp.jsp'"/>
    p>
body>
html>

addEmp.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>添加员工title>
head>
<body>
    <form action="add.do">
        姓名:<input type="text" name="name"/><br/>
        薪水:<input type="text" name="salary"/><br/>
        年龄:<input type="text" name="age"/><br/>
        <input type="submit" value="增加"/>
    form>
body>
html>

updateEmp.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="dao.*,entity.*,java.util.*" %>

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>修改员工信息title>
head>
<body>
    <%
        Employee emp=(Employee)request.getAttribute("emp");
    %>
    <form action="update.do?id=<%=emp.getId()%>" method="post">
        <table border="1px">
            <tr>
                <td>编号td>
                <td>
                    <input type="text" name="id" value="<%=emp.getId()%>"/>
                td>

            tr>
            <tr>
                <td>姓名td>
                <td>
                    <input type="text" name="name" value="<%=emp.getName()%>"/>
                td>

            tr>
            <tr>
                <td>薪水td>
                <td>
                    <input type="text" name="salary" value="<%=emp.getSalary()%>"/>
                td>

            tr>
            <tr>
                <td>年龄td>
                <td>
                    <input type="text" name="age" value="<%=emp.getAge()%>"/>
                td>

            tr>
        table>
        <p>
            <input type="submit" value="修改"/>
        p>

    form>
body>
html>

web.xml


<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Jsp01display-name>
  <welcome-file-list>
    <welcome-file>listEmp1.jspwelcome-file>
  welcome-file-list>

  <servlet>
      <servlet-name>actionServletservlet-name>
      <servlet-class>web.ActionServletservlet-class>
  servlet>
  <servlet-mapping>
      <servlet-name>actionServletservlet-name>
      <url-pattern>*.dourl-pattern>
  servlet-mapping>
web-app>

你可能感兴趣的:(java,web)