2021-04-21 08:34  阅读(81)
文章分类:Servlet 简单教程 文章标签:Servlet
©  原文作者:一点教程 原文地址:http://www.yiidian.com/servlet/

任何项目开发,CRUD(增加,查询,更新和删除)应用程序都是最基础最核心的功能。在Servlet中,我们可以轻松创建CRUD应用程序。

1 创建表和准备数据

1)在MySQL的test数据库,使用以下SQL创建customer表:

    
    CREATE TABLE `customer` (
       `id` int(11) NOT NULL AUTO_INCREMENT,
       `name` varchar(50) DEFAULT NULL,
       `gender` varchar(20) DEFAULT NULL,
       `telephone` varchar(100) DEFAULT NULL,
       `address` varchar(100) DEFAULT NULL,
       PRIMARY KEY (`id`)
     ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8

注意:id采用MySQL的自增长策略,所以我们程序不用维护id值。

2)插入一些测试数据,如下:

20210421083115_1.png

2 编写index.jsp

编写index.jsp页面,该页面是应用的主页面,可以添加客户,也可以点击查询所有客户。

    
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>一点教程网-使用Session完成增删改成(CRUD)</title>
    </head>
    <body>
    <h1>添加客户</h1>
    <form action="SaveServlet" method="post">
        | 客户名称:||
| :-----: | :-----: | 
| 客户名称: |  | 
| 性别: | 男女 | 
| 联系电话: |  | 
| 地址: |  | 
|  | 

    </form>
    
    <br/>
    <a href="ViewServlet">查询客户</a>
    </body>
    </html>

3 编写实体类

创建Customer实体类,用于封装表数据:

    
    package com.yiidian.domain;
    
    /**
     *一点教程网 - http://www.yiidian.com
     */
    public class Customer {
        private Integer id;
        private String name;
        private String gender;
        private String telephone;
        private String address;
    
        public Integer getId() {
            return id;
        }
    
        public void setId(Integer 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 getTelephone() {
            return telephone;
        }
    
        public void setTelephone(String telephone) {
            this.telephone = telephone;
        }
    
        public String getAddress() {
            return address;
        }
    
        public void setAddress(String address) {
            this.address = address;
        }
    }
    

4 编写CustomerDao

CustomerDao提供了增删改查的方法:

    
    package com.yiidian.dao;
    
    import com.yiidian.domain.Customer;
    
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.PreparedStatement;
    import java.sql.ResultSet;
    import java.util.ArrayList;
    import java.util.List;
    
    /**
     * 一点教程网 - http://www.yiidian.com
     */
    public class CustomerDao {
        public static Connection getConnection(){
            Connection con=null;
            try{
                Class.forName("com.mysql.jdbc.Driver");
                con= DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
            }catch(Exception e){System.out.println(e);}
            return con;
        }
    
      
        public static int save(Customer customer){
            int status=0;
            try{
                Connection con=CustomerDao.getConnection();
                PreparedStatement ps=con.prepareStatement(
                        "insert into customer(name,gender,telephone,address) values (?,?,?,?)");
                ps.setString(1,customer.getName());
                ps.setString(2,customer.getGender());
                ps.setString(3,customer.getTelephone());
                ps.setString(4,customer.getAddress());
    
                status=ps.executeUpdate();
    
                con.close();
            }catch(Exception ex){ex.printStackTrace();}
    
            return status;
        }
        public static int update(Customer customer){
            int status=0;
            try{
                Connection con=CustomerDao.getConnection();
                PreparedStatement ps=con.prepareStatement(
                        "update customer set name=?,gender=?,telephone=?,address=? where id=?");
                ps.setString(1,customer.getName());
                ps.setString(2,customer.getGender());
                ps.setString(3,customer.getTelephone());
                ps.setString(4,customer.getAddress());
                ps.setInt(5,customer.getId());
    
                status=ps.executeUpdate();
    
                con.close();
            }catch(Exception ex){ex.printStackTrace();}
    
            return status;
        }
        public static int delete(int id){
            int status=0;
            try{
                Connection con=CustomerDao.getConnection();
                PreparedStatement ps=con.prepareStatement("delete from customer where id=?");
                ps.setInt(1,id);
                status=ps.executeUpdate();
    
                con.close();
            }catch(Exception e){e.printStackTrace();}
    
            return status;
        }
        public static Customer getEmployeeById(int id){
            Customer e=new Customer();
    
            try{
                Connection con=CustomerDao.getConnection();
                PreparedStatement ps=con.prepareStatement("select * from customer where id=?");
                ps.setInt(1,id);
                ResultSet rs=ps.executeQuery();
                if(rs.next()){
                    e.setId(rs.getInt(1));
                    e.setName(rs.getString(2));
                    e.setGender(rs.getString(3));
                    e.setTelephone(rs.getString(4));
                    e.setAddress(rs.getString(5));
                }
                con.close();
            }catch(Exception ex){ex.printStackTrace();}
    
            return e;
        }
        public static List<Customer> getAllEmployees(){
            List<Customer> list=new ArrayList<Customer>();
    
            try{
                Connection con=CustomerDao.getConnection();
                PreparedStatement ps=con.prepareStatement("select * from customer");
                ResultSet rs=ps.executeQuery();
                while(rs.next()){
                    Customer e=new Customer();
                    e.setId(rs.getInt(1));
                    e.setName(rs.getString(2));
                    e.setGender(rs.getString(3));
                    e.setTelephone(rs.getString(4));
                    e.setAddress(rs.getString(5));
                    list.add(e);
                }
                con.close();
            }catch(Exception e){e.printStackTrace();}
    
            return list;
        }
    }
    

5 编写SaveServlet

SaveServlet用于保存客户:

    
    package com.yiidian.servlet;
    
    import com.yiidian.dao.CustomerDao;
    import com.yiidian.domain.Customer;
    
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.*;
    
    /**
     * 一点教程网 - http://www.yiidian.com
     */
    @WebServlet("/SaveServlet")
    public class SaveServlet extends HttpServlet {
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            //设置请求参数的编码
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out=response.getWriter();
    
            String name=request.getParameter("name");
            String gender=request.getParameter("gender");
            String telephone=request.getParameter("telephone");
            String address=request.getParameter("address");
    
            Customer e=new Customer();
            e.setName(name);
            e.setGender(gender);
            e.setTelephone(telephone);
            e.setAddress(address);
    
            int status= CustomerDao.save(e);
            if(status>0){
                out.print("<p>客户保存成功!</p>");
                request.getRequestDispatcher("index.jsp").include(request, response);
            }else{
                out.println("抱歉!保存失败");
            }
    
            out.close();
        }
    }

6 编写EditServlet

EditServlet用于回显客户信息:

    
    package com.yiidian.servlet;
    
    import com.yiidian.dao.CustomerDao;
    import com.yiidian.domain.Customer;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    /**
     * 一点教程网 - http://www.yiidian.com
     */
    @WebServlet("/EditServlet")
    public class EditServlet extends HttpServlet {
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out=response.getWriter();
            out.println("<h1>编辑客户</h1>");
            String sid=request.getParameter("id");
            int id=Integer.parseInt(sid);
    
            Customer e= CustomerDao.getEmployeeById(id);
    
            out.print("<form action='EditServlet2' method='post'>");
            out.print("| ||
| :-----: | :-----: | 
|  |  | 
| 客户名称: |  | 
| 性别: | ");if(e.getGender().equals("男")){out.print("男");}else{out.print("男");}if(e.getGender().equals("女")){out.print("女");}else{out.print("女");}out.print(" | 
| 联系电话: |  | 
| 地址: |  | 
|  | 
");
            out.print("</form>");
    
            out.close();
        }
    }

7 编写EditServlet2

EditServlet2用于保存编辑后的客户数据:

    
    package com.yiidian.servlet;
    
    import com.yiidian.dao.CustomerDao;
    import com.yiidian.domain.Customer;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    /**
     * 一点教程网 - http://www.yiidian.com
     */
    @WebServlet("/EditServlet2")
    public class EditServlet2 extends HttpServlet {
    
        protected void doPost(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            request.setCharacterEncoding("utf-8");
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out=response.getWriter();
    
            String sid=request.getParameter("id");
            int id=Integer.parseInt(sid);
            String name=request.getParameter("name");
            String gender=request.getParameter("gender");
            String telephone=request.getParameter("telephone");
            String address=request.getParameter("address");
    
            Customer e=new Customer();
            e.setId(id);
            e.setName(name);
            e.setGender(gender);
            e.setTelephone(telephone);
            e.setAddress(address);
    
            int status=CustomerDao.update(e);
            if(status>0){
                response.sendRedirect("ViewServlet");
            }else{
                out.println("抱歉!更新失败");
            }
    
            out.close();
        }
    }

8 编写DeleteServlet

DeleteServlet用于删除客户:

    
    package com.yiidian.servlet;
    
    import com.yiidian.dao.CustomerDao;
    import com.yiidian.domain.Customer;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    
    /**
     * 一点教程网 - http://www.yiidian.com
     */
    @WebServlet("/DeleteServlet")
    public class DeleteServlet extends HttpServlet {
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            String sid=request.getParameter("id");
            int id=Integer.parseInt(sid);
            CustomerDao.delete(id);
            response.sendRedirect("ViewServlet");
        }
    }

9 编写ViewServlet

ViewServlet用于查询显示所有客户数据:

    
    package com.yiidian.servlet;
    
    import com.yiidian.dao.CustomerDao;
    import com.yiidian.domain.Customer;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.List;
    
    /**
     * 一点教程网 - http://www.yiidian.com
     */
    @WebServlet("/ViewServlet")
    public class ViewServlet extends HttpServlet {
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response)
                throws ServletException, IOException {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter out=response.getWriter();
            out.println("<a href='index.jsp'>添加客户</a>");
            out.println("<h1>客户列表</h1>");
    
            List<Customer> list=CustomerDao.getAllEmployees();
    
            out.print("| Id|客户名称|性别|联系电话|地址|编辑|删除|
| :-----: | :-----: | :-----: | :-----: | :-----: | :-----: | :-----: | 
| "+e.getId()+" | "+e.getName()+" | "+e.getGender()+" | "+e.getTelephone()+" | "+e.getAddress()+" | 编辑 | 删除 | 
");
    
            out.close();
        }
    }

10 运行测试

1)访问主页面,http://localhost:8080/,如下:

20210421083111_2.png2)输入客户数据,然后点击保存

2021042108315_3.png

202104210838_4.png

3)点击查询客户,展示所有客户数据

202104210836_5.png4)点击“编辑”,进入客户编辑页面

202104210836_6.png

5)修改客户数据,点击“编辑保存”

202104210836_7.png6)保存编辑后,回到客户列表,点击“删除”

202104210834_8.png


本案例需要在lib目录导入mysql驱动程序,点击下面链接下载:

下载mysql-connector-java-5.1.40.jar

点赞(0)
版权归原创作者所有,任何形式转载请联系作者; Java 技术驿站 >> 使用Servlet完成CRUD
上一篇
使用Session完成登录注销案例
下一篇
使用Servlet完成分页