Servlet(六):连接数据库,完整的CRUD

2018-06-21 06:54:33来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

Servlet的知识点大致讲完了,今天补充下与之相关的一些小知识,然后做一个完整的小例子。

一、MVC设计模式

1、MVC设计模式是什么?

在了解MVC之前,先聊聊Model1、Model2开发模式。

Model1开发模式中,使用jsp页面嵌套一些java代码、代码块,既处理请求,又处理数据,将java代码和html代码高度耦合在一起,对于后期的维护和拓展非常不便,这就是Model1开发模式。

Model2开发模式,引入了分层思想,即MVC模式,将代码进行了分层,降低了耦合度,方便后期的维护和扩展。

MVC模式,其中M是Model的缩写,表示模型,在应用中包含业务处理层和数据访问层。数据访问层主要是对数据库的一些操作的封装。业务处理层应用JavaBean构建, JavaBean主要是用作将从View层获取的数据和数据库的数据进行桥接。

V是View的缩写,表示视图,视图提供了可交互的用户界面,向用户显示模型数据,通常使用jsp和HTML搭建。

C是Controller的缩写,表示控制层,负责调度,是模型和视图的桥梁。

2、为什么要用MVC设计模式?

一是程序耦合度较低,方便修改和维护;二是可扩展性高,方便后期的业务扩展;三是可重用性高,可以重复使用已有的控制层,减少重复代码。

二、完整的CRUD

1、新建一个Maven项目,建好目录结构

项目结构使用了上面提到的MVC分层结构,如下图所示

 

2、配置web.xml和pom.xml文件

web.xml文件是配置servlet的,pom.xml是配置所需要的jar包。

  <servlet>
      <servlet-name>servlet</servlet-name>
      <servlet-class>web.EmployeeServlet</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>servlet</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <dependencies>
      <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>5.1.8</version>
    </dependency>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit</artifactId>
        <version>4.12</version>
        <scope>test</scope>
    </dependency> 
  </dependencies>

3、连接数据库

先建库,再建表,然后插入原始数据。

CREATE TABLE employee(
    id varchar(36) NOT NULL,
    name varchar(50),
    gender varchar(4),
    birthday DATE,
    email varchar(20),
    salary varchar(20),
    remark varchar(200),
    PRIMARY KEY (`id`)  
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
insert into employee values ('5476cbc52c084d56a8d2492a372450a3','小川94','','2000-05-25','1340059045@qq.com','10000','');

编写DBUtil类,连接数据库

/**
 * 管理数据库连接
 * @author 小川94
 * @date 2018年6月11日
 */
public class DBUtil {
    
    private static String user ="";
    private static String password = "";
    private static String url = "";
    private static String driver = "";
    private static Connection conn = null;
    
    /**
     * 获取数据库连接
     * @return Connection
     */
    public static Connection getConnection(){
        try{
            // 读取配置文件
            user = ConfigUtil.getConfigValue("jdbc.user");
            password = ConfigUtil.getConfigValue("jdbc.password");
            url = ConfigUtil.getConfigValue("jdbc.jdbcUrl");
            driver = ConfigUtil.getConfigValue("jdbc.driverClass");
            // 加载驱动
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);
        }catch(Exception e){
            System.out.println("数据库连接异常");
            e.printStackTrace();
        }
        return conn;
    }
    
    /**
     * 关闭数据库连接
     * @param conn
     */
    public static void closeConnection(Connection conn){
        if(conn != null){
            try{
                conn.close();
            }catch(SQLException e){
                System.out.println("数据库关闭异常");
                e.printStackTrace();
            }
        }
    }
    
}

其中使用了读取配置文件的ConfigUtil类

/**
 * 读取配置文件
 * @author 小川94
 * @date 2018年6月11日
 */
public class ConfigUtil {

    public static String getConfigValue(String tagName) {
        String tagValue = null;
        Properties prop = new Properties();
        try {
            ClassLoader classLoader = ConfigUtil.class.getClassLoader(); 
            // 读取配置文件dbconfig.properties
            InputStream in = classLoader.getResourceAsStream("dbconfig.properties");
            prop.load(in); // 加载属性列表
            Iterator<String> it = prop.stringPropertyNames().iterator();
            while (it.hasNext()) {
                if (it.next().equals(tagName)) {
                    tagValue = prop.getProperty(tagName);
                }
            }
            in.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return tagValue;
    }
    
}

4、编写实体类

/**
 * 实体类
 * @author 小川94
 * @date 2018年6月11日
 */
public class Employee {
    
    private String id; // 主键
    private String name; // 姓名
    private String gender; // 性别
    private String email; // 邮箱
    private String salary; // 薪水
    private String remark; // 备注
    private Date birthday; // 出生日期
    
    public Employee(){
        
    }
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getGender() {
        return gender;
    }
    public void setGender(String gender) {
        this.gender = gender;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public String getSalary() {
        return salary;
    }
    public void setSalary(String salary) {
        this.salary = salary;
    }
    public String getRemark() {
        return remark;
    }
    public void setRemark(String remark) {
        this.remark = remark;
    }
    public Date getBirthday() {
        return birthday;
    }
    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }
    
    /**
     * 重写toString方法,方便junit测试
     */
    @Override
    public String toString() {
        return "Employee [id=" + id + ", name=" + name + ", gender=" + gender +  ", birthday=" + birthday 
                +", salary=" + salary + ", email=" + email + ", remark=" + remark + "]";
    }
    
}

5、查询数据

查询数据功能,一是查询出所有数据,二是需要考虑页面的查询条件,需要两者结合考虑。

控制层使用了反射机制,使用一个Servlet处理多个请求,减少代码重复。

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取请求的URI地址信息
        String url = request.getRequestURI();
        // 截取其中的方法名
        String methodName = url.substring(url.lastIndexOf("/")+1, url.lastIndexOf("."));
        Method method = null;
        try {
            // 使用反射机制获取在本类中声明了的方法
            method = getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            // 执行方法
            method.invoke(this, request, response);
        } catch (Exception e) {
            throw new RuntimeException("调用方法出错!");
        }
    }
    /**
     * 查询employee表中的所有数据
     * @return List<Employee> 包含所有员工信息的list
     */
    public List<Employee> queryAllEmployee(String name, String salary, String salary2) {
        Connection conn = null;
        List<Employee> employees = new ArrayList<Employee>();
        try{
            // 连接数据库
            conn = DBUtil.getConnection();
            if (StringUtil.isEmpty(conn)) {
                throw new Exception("数据库连接失败");
            }
            // 编写sql语句
            String sql = "SELECT * FROM EMPLOYEE";
            String str = "";
            if(StringUtil.isNotEmpty(name) || StringUtil.isNotEmpty(salary) || StringUtil.isNotEmpty(salary2)){
                if(StringUtil.isNotEmpty(name)){
                    str = " WHERE NAME LIKE '%"+name+"%'";
                }
                if(StringUtil.isNotEmpty(salary)){
                    if(str.length() == 0){
                        str = " WHERE SALARY > " + salary;
                    }else{
                        str = str + " AND SALARY > " + salary;
                    }
                }
                if(StringUtil.isNotEmpty(salary2)){
                    if(str.length() == 0){
                        str = " WHERE SALARY < " + salary2;
                    }else{
                        str = str + " AND SALARY < " + salary2;
                    }
                }
            }
            // 创建一个 PreparedStatement 对象,初始化sql语句
            PreparedStatement ps = conn.prepareStatement(sql+str);
            // 获取执行sql语句后的结果集
            ResultSet rs = ps.executeQuery();
            Employee emp = null;
            // 遍历结果集,添加到list中
            while (rs.next()) {
                emp = new Employee();
                emp.setId(rs.getString("id"));
                emp.setName(rs.getString("name"));
                emp.setGender(rs.getString("gender"));
                emp.setEmail(rs.getString("email"));
                emp.setBirthday(rs.getDate("birthday"));
                emp.setRemark(rs.getString("remark"));
                emp.setSalary(rs.getString("salary"));
                employees.add(emp);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            if (StringUtil.isNotEmpty(conn)) {
                DBUtil.closeConnection(conn);
            }
        }
        return employees;
    }

编写控制层代码

    private void queryEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EmployeeDao dao = new EmployeeDao();
        request.setCharacterEncoding("utf-8");
        String name = request.getParameter("name");
        String salary = request.getParameter("salary");
        String salary2 = request.getParameter("salary2");
        List<Employee> employees = dao.queryAllEmployee(name, salary, salary2);
        request.setAttribute("employees", employees);
        request.getRequestDispatcher("queryList.jsp").forward(request, response);
    }

6、新增数据

本质是提交表单数据到后台,通过Model层处理数据。

    /**
     * 新增员工信息
     * @param emp
     */
    public int addEmployee(Employee emp){
        if(StringUtil.isEmpty(emp)){
            throw new RuntimeException("参数为空!");
        }
        Connection conn = null;
        int result = 0;
        try{
            conn = DBUtil.getConnection();
            if(StringUtil.isEmpty(conn)){
                throw new Exception("数据库连接失败!");
            }
            String sql = "INSERT INTO EMPLOYEE VALUES (?,?,?,?,?,?,?) ";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, StringUtil.getUUID());
            ps.setString(2, emp.getName());
            ps.setString(3, emp.getGender());
            ps.setDate(4, emp.getBirthday());
            ps.setString(5, emp.getEmail());
            ps.setString(6, emp.getSalary());
            ps.setString(7, emp.getRemark());
            result = ps.executeUpdate();
        }catch(Exception e){
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            if (StringUtil.isNotEmpty(conn)) {
                DBUtil.closeConnection(conn);
            }
        }
        return result;
    }
    /**
     * 新增(修改)员工信息,根据id是否为空判断新增操作、修改操作
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException
     */
    private void addEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EmployeeDao dao = new EmployeeDao();
        request.setCharacterEncoding("utf-8");
        Employee emp = new Employee();
        String id = request.getParameter("id");
        if (StringUtil.isEmpty(id) || "null".equals(id)) {
            try {
                emp.setId(StringUtil.getUUID());
                emp.setName(request.getParameter("name"));
                emp.setGender(request.getParameter("gender"));
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                java.util.Date date =  sdf.parse(request.getParameter("birthday"));
                java.sql.Date birthday = new java.sql.Date(date.getTime());
                emp.setBirthday(birthday);
                emp.setEmail(request.getParameter("email"));
                emp.setSalary(request.getParameter("salary"));
                emp.setRemark(request.getParameter("remark"));
            } catch (Exception e) {
                e.printStackTrace();
            }
            dao.addEmployee(emp);
            response.sendRedirect("queryList.jsp");
        } else {
            modifyEmpInfo(request, response);
        }
    }

7、修改数据

修改数据,我们共用了新增数据的jsp页面,使用了js方法来控制页面的数据展示和可修改性,同时后台需要对新增和修改的数据处理逻辑拆分。

    /**
     * 根据员工信息id来修改相关内容
     * @param id
     * @return
     */
    public boolean modifyEmployeeById(Employee emp){
        if(StringUtil.isEmpty(emp)){
            throw new RuntimeException("参数为空!");
        }
        Connection conn = null;
        boolean flag = false;
        try{
            conn = DBUtil.getConnection();
            if(StringUtil.isEmpty(conn)){
                throw new Exception("数据库连接失败!");
            }
            String sql = "UPDATE EMPLOYEE SET EMAIL=? , SALARY=? , REMARK=? WHERE ID=? ";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, emp.getEmail());
            ps.setString(2, emp.getSalary());
            ps.setString(3, emp.getRemark());
            ps.setString(4, emp.getId());
            int result = ps.executeUpdate();
            if (result == 1) {
                flag = true;
            }
        } catch(Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            if (StringUtil.isNotEmpty(conn)) {
                DBUtil.closeConnection(conn);
            }
        }
        return flag;
    }

编写控制层代码

    private void modifyEmpInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
        request.setCharacterEncoding("utf-8");
        EmployeeDao dao = new EmployeeDao();
        Employee emp = new Employee();
        try{
            emp.setId(request.getParameter("id"));
            emp.setName(request.getParameter("name"));
            emp.setGender(request.getParameter("gender"));
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            java.util.Date date =  sdf.parse(request.getParameter("birthday"));
            java.sql.Date birthday = new java.sql.Date(date.getTime());
            emp.setBirthday(birthday);
            emp.setEmail(request.getParameter("email"));
            emp.setSalary(request.getParameter("salary"));
            emp.setRemark(request.getParameter("remark"));
        }catch(Exception e){
            e.printStackTrace();
        }
        boolean flag = dao.modifyEmployeeById(emp);
        if(!flag){
            request.setAttribute("msg", "修改员工信息失败!");
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }else{
            response.sendRedirect("queryList.jsp");
        }
    }

8、删除数据

删除数据,我们需要拿到所要删除数据的id。

    /**
     * 根据员工信息的id删除数据
     * @param id
     * @return
     */
    public boolean deleteEmployeeById(String id){
        if(StringUtil.isEmpty(id)){
            throw new RuntimeException("参数为空!");
        }
        Connection conn = null;
        boolean flag = false;
        try{
            conn = DBUtil.getConnection();
            if(StringUtil.isEmpty(conn)){
                throw new Exception("连接数据库失败!");
            }
            String sql = "DELETE FROM EMPLOYEE WHERE ID = ?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, id);
            int result = ps.executeUpdate();
            if(result == 1){
                flag = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            if (StringUtil.isNotEmpty(conn)) {
                DBUtil.closeConnection(conn);
            }
        }
        return flag;
    }

编写控制层代码

    private void deleteEmp(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EmployeeDao dao = new EmployeeDao();
        request.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");
        boolean flag = dao.deleteEmployeeById(id);
        if(!flag){
            request.setAttribute("msg", "删除员工信息失败!");
            request.getRequestDispatcher("error.jsp").forward(request, response);
        }else{
            request.getRequestDispatcher("queryList.jsp").forward(request, response);
        }
    }

9、查看数据

查看数据的本质是将数据查询出来,回显到页面。

    /**
     * 根据员工信息id查询完整员工信息
     * @param id
     * @return
     */
    public Employee queryEmpById(String id) {
        if (StringUtil.isEmpty(id)) {
            throw new RuntimeException("参数为空!");
        }
        Connection conn = null;
        Employee emp = new Employee();
        try {
            conn = DBUtil.getConnection();
            if (StringUtil.isEmpty(conn)) {
                throw new RuntimeException("数据库连接失败!");
            }
            String sql = "SELECT * FROM EMPLOYEE WHERE ID=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, id);
            ResultSet rs = ps.executeQuery();
            if(StringUtil.isEmpty(rs)){
                throw new RuntimeException("查询信息失败!");
            }
            while (rs.next()) {
                emp.setId(rs.getString("id"));
                emp.setName(rs.getString("name"));
                emp.setGender(rs.getString("gender"));
                emp.setEmail(rs.getString("email"));
                emp.setBirthday(rs.getDate("birthday"));
                emp.setRemark(rs.getString("remark"));
                emp.setSalary(rs.getString("salary"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭数据库连接
            if (StringUtil.isNotEmpty(conn)) {
                DBUtil.closeConnection(conn);
            }
        }
        return emp;
    }

编写控制层代码

    private void queryEmpInfo(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        EmployeeDao dao = new EmployeeDao();
        request.setCharacterEncoding("utf-8");
        String id = request.getParameter("id");
        Employee emp = dao.queryEmpById(id);
        request.getSession().setAttribute("Emp", emp);
        request.getRequestDispatcher("empInfo.jsp").forward(request, response);
    }

10、单元测试

使用Junit包,来完成相应的功能方法测试。

public class TestSample extends TestCase {

    private long startTime;
    private long endTime;
    
    @Before
    public void setUp() throws Exception {
        this.startTime= System.currentTimeMillis();
        System.out.println("=========开始测试===========");
    }
    
    @After
    public void tearDown() throws Exception {
        this.endTime = System.currentTimeMillis();
        System.out.println("测试用时:"+(endTime-startTime));
        System.out.println("=========测试结束===========");
    }
    
    /**
     * 测试数据库连接
     */
    @Test
    public void testDBConnection(){
        Connection conn = DBUtil.getConnection();
        if(StringUtil.isEmpty(conn)){
            System.out.println("数据库连接失败!");
        }else{
            System.out.println("数据库连接成功!");
            DBUtil.closeConnection(conn);
        }
    }
    
    /**
     * 测试EmployeeDao中的 queryAllEmployee 方法
     */
    @Test
    public void testQueryAllEmployee(){
        EmployeeDao dao = new EmployeeDao();
        List<Employee> list = dao.queryAllEmployee("张","","");
        if(StringUtil.isEmpty(list)){
            System.out.println("查询员工信息失败");
        }else{
            for(Employee emp : list){
                System.out.println(emp.toString());
            }
        }
    }
    
    /**
     * 测试EmployeeDao中的 addEmployee 方法
     */
    @Test
    public void testAddEmployee(){
        EmployeeDao dao = new EmployeeDao();
        Employee emp = new Employee();
        emp.setId(StringUtil.getUUID());
        emp.setName("张三");
        emp.setGender("男");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            java.util.Date d = sdf.parse("1987-09-23");
            java.sql.Date birthday = new java.sql.Date(d.getTime());
            emp.setBirthday(birthday);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        emp.setEmail("152612@qq.com");
        emp.setSalary("10500");
        emp.setRemark("新入职员工");
        int result = dao.addEmployee(emp);
        if(result == 1){
            System.out.println("新增成功");
        }else{
            System.out.println("新增失败");
        }
    }
    
    /**
     * 测试EmployeeDao中的 deleteEmployeeById 方法
     */
    @Test
    public void testDeleteEmployeeById(){
        EmployeeDao dao = new EmployeeDao();
        String id = "8926a2e7-4cf1-4370-abdd-1141f8f6412d";
        boolean flag = dao.deleteEmployeeById(id);
        if(!flag){
            System.out.println("删除员工信息失败!");
        }else{
            System.out.println("删除成功!");
        }
    }
    
    /**
     * 测试EmployeeDao中的 queryEmpById 方法
     */
    @Test
    public void testQueryEmpById(){
        String id = "0a100fb2-a619-40b5-a667-dba96fae8b49";
        EmployeeDao dao = new EmployeeDao();
        Employee emp = dao.queryEmpById(id);
        System.out.println(emp.toString());
    }
}
View Code

11、编写View层

查询页面jsp编写

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.*,entity.*,dao.*" %>    
<!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=UTF-8">
<title>员工信息查询列表</title>
<script type="text/javascript">
    function searchList(){
        var name = document.getElementById("name").value;
        var salary = document.getElementById("salary").value;
        var salary2 = document.getElementById("salary2").value;
        var url = "queryEmp.do";
        var str = "";
        if (name || salary || salary2) {
            if(name){
                str = "?name=" + name + "";
            }
            if(salary){
                if(str.length == 0){
                    str = "?salary=" + salary + "";
                }else{
                    str = str + "&salary=" + salary + "";
                }
            }
            if(salary2){
                if(str.length == 0){
                    str = "?salary2=" + salary2 + "";
                }else{
                    str = str + "&salary2=" + salary2 + "";
                }
            }
        } 
        window.location.href = url+str;
    }
    
    function addEmp(){
        window.location.href = "addEmp.jsp";
    }
    
    function myreset(){
        document.getElementById("name").value = "";
        document.getElementById("salary").value = "";
        document.getElementById("salary2").value = "";
    }
</script>
</head>
<body>
    <div style="height:100px;">
        <div style="">
            <div style="float:left;">
                <span style="margin-left:150px;">姓名</span>
                <% 
                    String name = request.getParameter("name");
                    if(name == null || name == ""){
                        name = "";
                    }
                    String salary = request.getParameter("salary");
                    if(salary == null || salary == ""){
                        salary = "";
                    }
                    String salary2 = request.getParameter("salary2");
                    if(salary2 == null || salary2 == ""){
                        salary2 = "";
                    }
                %>
                <input id="name" style="width:150px;height:20px;" type="text" name="name" value="<%=name %>">
            </div>
            <div style="float:left;">
                <span style="margin-left:50px;">薪水</span>
                <input id="salary" style="width:120px;height:20px;" type="text" value="<%=salary %>" name="salary">&nbsp;至
                <input id="salary2" style="width:120px;height:20px;" type="text" value="<%=salary2 %>" name="salary2">
            </div>
        </div>
        <div style="margin-top:40px;" align="center">
            <input style="height:30px;font-size:16px;margin-right:20px;" type="button" onclick="searchList()" value="查询">
            <input style="height:30px;font-size:16px;margin-right:20px;" type="button" onclick="myreset()" value="重置">
            <input style="height:30px;font-size:16px;" type="button" onclick="addEmp()" value="新增">
        </div>
    </div>
    <div align="center">
        <table onload="searchList()" cellpadding="0" cellspacing="0" border="1px black solid">
            <thead>
                <tr style="height:40px;">
                    <th style="width:80px;text-align: center;">序号</th>
                    <th style="width:120px;text-align: center;">姓名</th>
                    <th style="width:100px;text-align: center;">性别</th>
                    <th style="width:150px;text-align: center;">出生日期</th>
                    <th style="width:120px;text-align: center;">薪水</th>
                    <th style="width:180px;text-align: center;">邮箱</th>
                    <th style="width:150px;text-align: center;">备注</th>
                    <th style="width:150px;text-align: center;">操作</th>
                </tr>
            </thead>
            <tbody>
                <%
                    List<Employee> employees = (List<Employee>)request.getAttribute("employees");
                    if(employees != null){
                        for(int i=0; i<employees.size(); i++){
                            Employee e = employees.get(i);
                %>
                <tr style="height:35px;">
                    <td style="text-align:center;"><%=i+1 %></td>
                    <td style="text-align:center;"><a href="queryEmpInfo.do?id=<%=e.getId() %>" style="text-decoration:none;color:blue"><%=e.getName() %></a></td>
                    <td style="text-align:center;"><%=e.getGender() %></td>
                    <td style="text-align:center;"><%=e.getBirthday() %></td>
                    <td style="text-align:center;"><%=e.getSalary() %></td>
                    <td style="text-align:center;"><%=e.getEmail() %></td>
                    <td style="text-align:center;"><%=e.getRemark() %></td>
                    <td style="text-align:center;">
                    <a href="openModifyEmpInfo.do?id=<%=e.getId()  %>" style="text-decoration:none;color:blue">修改</a>&nbsp;
                    <a href="deleteEmp.do?id=<%=e.getId()  %>" style="text-decoration:none;color:blue">删除</a>
                    </td>
                </tr>
                <%         
                        }
                    }
                %>
            </tbody>
        </table>
    </div>
    
    
</body>
</html>
View Code

新增(修改)jsp页面编写

<%@page import="jdk.nashorn.internal.runtime.Undefined"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="java.util.*,java.text.*,entity.Employee" %>
<!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=UTF-8">
<title>新增员工信息</title>    
</head>
<body onload="myload()">
    
    <%
        String id = request.getParameter("id");
        Employee emp = (Employee)request.getSession().getAttribute("Emp");
        String name = "";
        String gender = "";
        String birthday = "";
        String email = "";
        String salary = "";
        String remark = "";
        if (emp!= null) {
            name = emp.getName();
            gender = emp.getGender();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            if(emp.getBirthday() != null){
                java.sql.Date d = emp.getBirthday();
                java.util.Date date = new java.util.Date(d.getTime());
                birthday = sdf.format(date);
            }
            email = emp.getEmail();
            salary = emp.getSalary();
            remark = emp.getRemark();
        }
    %>
    
    <div style="padding-top: 60px;" align="center">
        <form action="addEmp.do?id=<%=id %>" method="post">
            <table cellpadding="0" cellspacing="0" border="1px black solid">
                <tr style="height:40px;">
                    <td style="font-size:18px;text-align: right;width:100px;">姓名&nbsp;</td>
                    <td style="width:400px;">
                        <input id="name" style="width:350px;height:20px;margin-left:10px;" type="text" name="name">
                    </td>
                </tr>
                <tr style="height:40px;">
                    <td style="font-size:18px;text-align: right;width:100px;">性别&nbsp;</td>
                    <td>
                        <input id="boy" style="width:30px;height:20px;margin-left:10px;" type="radio" name="gender" value="男"><input id="gril" style="width:30px;height:20px;margin-left:10px;" type="radio" name="gender" value="女"></td>
                </tr>
                <tr style="height:40px;">
                    <td style="font-size:18px;text-align: right;width:100px;">出生日期&nbsp;</td>
                    <td>
                        <input id="birthday" style="height:20px;margin-left:10px;" type="date" name="birthday">
                    </td>
                </tr>
                <tr style="height:40px;">
                    <td style="font-size:18px;text-align: right;width:100px;">邮箱&nbsp;</td>
                    <td>
                        <input id="email" style="width:350px;height:20px;margin-left:10px;" type="text" name="email">
                    </td>
                </tr>
                <tr style="height:40px;">
                    <td style="font-size:18px;text-align: right;width:100px;">薪水&nbsp;</td>
                    <td>
                        <input id="salary" style="width:350px;height:20px;margin-left:10px;" type="text" name="salary">
                    </td>
                </tr>
                <tr style="height:40px;">
                    <td style="font-size:18px;text-align: right;width:100px;">备注&nbsp;</td>
                    <td>
                        <textarea id="remark" style="margin:10px;"  rows="6" cols="47" name="remark"></textarea>
                    </td>
                </tr>
            </table>
            <div style="margin:20px;">
                <input style="height:30px;font-size:16px;margin-right:20px;" type="submit" value="提交"/>
                <input style="height:30px;font-size:16px;" type="reset" value="重置"/>
            </div>
        </form>
    </div>
    
    <script type="text/javascript">
        var idstr = "<%=id %>";
        function myload() {
            if (idstr != null && idstr != undefined && idstr != "null") {
                document.getElementById("name").value = "<%=name %>";
                var gender = "<%=gender %>";
                if(gender == "男"){
                    document.getElementById("boy").checked = true;
                    document.getElementById("girl").disabled = "disabled";
                } else {
                    document.getElementById("gril").checked = true;
                    document.getElementById("boy").disabled = "disabled";
                }
                document.getElementById("birthday").value = "<%=birthday %>";
                document.getElementById("email").value = "<%=email %>";
                document.getElementById("salary").value = "<%=salary %>";
                document.getElementById("remark").value = "<%=remark %>";
                // 设置只读
                document.getElementById("name").readOnly = true;
                document.getElementById("gril").readOnly = true;
                document.getElementById("birthday").readOnly = true;
            } else {
                document.getElementById("name").readOnly = false;
                document.getElementById("boy").readOnly = false;
                document.getElementById("gril").readOnly = false;
                document.getElementById("birthday").readOnly = false;
            }
        }
    </script>
    
</body>
</html>
View Code

查看信息jsp页面编写

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ page import="entity.Employee" %>
<!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=UTF-8">
<title>员工信息</title>
</head>
<body>
    
    <jsp:useBean id="Emp" class="entity.Employee" scope="session"></jsp:useBean>
    <div style="padding-top: 60px;" align="center">
        <form>
            <h4>员工信息</h4>
            <table cellpadding="0" cellspacing="0" border="1px black solid">
                <tr style="height:40px;">
                    <td style="font-size:18px;text-align: right;width:100px;">姓名&nbsp;</td>
                    <td style="width:300px;">
                        &nbsp;&nbsp;<jsp:getProperty property="name" name="Emp"/>
                    </td>
                </tr>
                <tr style="height:40px;">
                    <td style="font-size:18px;text-align: right;width:100px;">性别&nbsp;</td>
                    <td style="width:300px;">
                        &nbsp;&nbsp;<jsp:getProperty property="gender" name="Emp"/>
                    </td>
                </tr>
                <tr style="height:40px;">
                    <td style="font-size:18px;text-align: right;width:100px;">出生日期&nbsp;</td>
                    <td style="width:300px;">
                        &nbsp;&nbsp;<jsp:getProperty property="birthday" name="Emp"/>
                    </td>
                </tr>
                <tr style="height:40px;">
                    <td style="font-size:18px;text-align: right;width:100px;">邮箱&nbsp;</td>
                    <td style="width:300px;">
                        &nbsp;&nbsp;<jsp:getProperty property="email" name="Emp"/>
                    </td>
                </tr>
                <tr style="height:40px;">
                    <td style="font-size:18px;text-align: right;width:100px;">薪水&nbsp;</td>
                    <td style="width:300px;">
                        &nbsp;&nbsp;<jsp:getProperty property="salary" name="Emp"/>
                    </td>
                </tr>
                <tr style="height:40px;">
                    <td style="font-size:18px;text-align: right;width:100px;">备注&nbsp;</td>
                    <td style="width:300px;">
                        &nbsp;&nbsp;<jsp:getProperty property="remark" name="Emp"/>    
                    </td>
                </tr>
            </table>
            <div style="margin:20px;">
                <input style="height:30px;font-size:16px;margin-right:20px;" type="button" onclick="history.back()" value="返回"/>
            </div>
        </form>
    </div>
</body>
</html>
View Code

错误信息jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>错误提示信息</title>
</head>
<body>
    <h1 style="margin:200px;">:( 您的上一步操作发生了错误!
        <br>
        错误信息:<%=request.getParameter("msg") %>
    </h1>
    
</body>
</html>
View Code

三、测试

测试结果如下图所示,对于分页展示数据的问题,下次再单独处理。

 

 

文章首发于我的个人公众号:悦乐书。喜欢分享一路上听过的歌,看过的电影,读过的书,敲过的代码,深夜的沉思。期待你的关注!

公众号后台输入关键字“Java学习电子书”,即可获得12本Java学习相关的电子书资源,如果经济能力允许,还请支持图书作者的纸质正版书籍,创作不易。

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:Java虚拟机--虚拟机类加载机制

下一篇:java 中 关于抽象类和接口的一些知识