使用JSP完成CRUD

本文讲解在JSP中轻松创建CRUD示例。我们将使用Dao访问数据库,将使用JSTL遍历数据库记录。

1 下载jstl包和mysql驱动包

下载jstl包

下载mysql驱动包

2 创建表和插入测试数据

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)插入一些测试数据,如下:

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

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=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();
        }catch(Exception e){System.out.println(e);}
        return status;
    }

    public static int update(Customer customer){
        int status=0;
        try{
            Connection con=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();
        }catch(Exception e){System.out.println(e);}
        return status;
    }

    public static int delete(Customer customer){
        int status=0;
        try{
            Connection con=getConnection();
            PreparedStatement ps=con.prepareStatement("delete from customer where id=?");
            ps.setInt(1,customer.getId());
            status=ps.executeUpdate();
        }catch(Exception e){System.out.println(e);}

        return status;
    }
    public static List<Customer> getAllRecords(){
        List<Customer> list=new ArrayList<Customer>();

        try{
            Connection con=getConnection();
            PreparedStatement ps=con.prepareStatement("select * from customer");
            ResultSet rs=ps.executeQuery();
            while(rs.next()){
                Customer customer=new Customer();
                customer.setId(rs.getInt("id"));
                customer.setName(rs.getString("name"));
                customer.setGender(rs.getString("gender"));
                customer.setTelephone(rs.getString("telephone"));
                customer.setAddress(rs.getString("address"));
                list.add(customer);
            }
        }catch(Exception e){
            System.out.println(e);
        }
        return list;
    }
    public static Customer getRecordById(int id){
        Customer customer=null;
        try{
            Connection con=getConnection();
            PreparedStatement ps=con.prepareStatement("select * from customer where id=?");
            ps.setInt(1,id);
            ResultSet rs=ps.executeQuery();
            while(rs.next()){
                customer=new Customer();
                customer.setId(rs.getInt("id"));
                customer.setName(rs.getString("name"));
                customer.setGender(rs.getString("gender"));
                customer.setTelephone(rs.getString("telephone"));
                customer.setAddress(rs.getString("address"));
            }
        }catch(Exception e){
            System.out.println(e);
        }
        return customer;
    }
}

5 编写index.jsp

<%@ page language="java" contentType="text/html;charset=utf-8" %>
<html>
<html>
<head>
    <meta charset="utf-8">
    <title>一点教程网-使用JSP完成CRUD</title>
</head>
<body>

<h1>使用JSP完成CRUD</h1>
<a href="addcustform.jsp">添加客户</a>
<a href="viewcusts.jsp">查看客户</a>

</body>
</html>

6 编写addcustform.jsp

<%@ page language="java" contentType="text/html;charset=utf-8" %>
<html>
<html>
<head>
    <meta charset="utf-8">
    <title>一点教程网-使用JSP完成CRUD</title>
</head>
<body>

<h1>使用JSP完成CRUD</h1>
<a href="addcustform.jsp">添加客户</a>
<a href="viewcusts.jsp">查看客户</a>

</body>
</html>

7 编写addcust.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="com.yiidian.dao.CustomerDao"%>
<html>
<head>
    <title>一点教程网-使用JSP完成CRUD</title>
</head>
<body>
<%
    //设置参数的中文编码
    request.setCharacterEncoding("utf-8");
%>
<jsp:useBean id="customer" class="com.yiidian.domain.Customer"></jsp:useBean>
<jsp:setProperty property="*" name="customer"/>

<%
    int i= CustomerDao.save(customer);
    if(i>0){
        response.sendRedirect("addcust-success.jsp");
    }else{
        response.sendRedirect("addcust-error.jsp");
    }
%>

</body>
</html>

8 编写addcust-success.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>一点教程网-使用JSP完成CRUD</title>
</head>
<body>
<p>客户保存成功!</p>
<a href="viewcusts.jsp">客户列表</a>
</body>
</html>

9 编写addcust-error.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>一点教程网-使用JSP完成CRUD</title>
</head>
<body>
<p>抱歉, 保存失败!</p>
</body>
</html>

10 编写viewcusts.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="com.yiidian.dao.CustomerDao,com.yiidian.domain.*,java.util.*"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>一点教程网-使用JSP完成CRUD</title>
</head>
<body>
<h1>客户列表</h1>

<%
    List<Customer> list=CustomerDao.getAllRecords();
    request.setAttribute("list",list);
%>

<table border="1" width="90%">
    <tr><th>编号</th><th>名称</th><th>性别</th><th>联系电话</th>
        <th>住址</th><th>编辑</th><th>删除</th></tr>
    <c:forEach items="${list}" var="cust">
        <tr><td>${cust.id}</td><td>${cust.name}</td><td>${cust.gender}</td>
            <td>${cust.telephone}</td><td>${cust.address}</td>
            <td><a href="editform.jsp?id=${cust.id}">编辑</a></td>
            <td><a href="deletecust.jsp?id=${cust.id}">删除</a></td></tr>
    </c:forEach>
</table>
<br/><a href="addcustform.jsp">添加客户</a>
</body>
</html>

11 编写editform.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.yiidian.dao.CustomerDao,com.yiidian.domain.Customer"%>
<html>
<head>
    <title>一点教程网-使用JSP完成CRUD</title>
</head>
<body>

<%
    String id=request.getParameter("id");
    Customer customer=CustomerDao.getRecordById(Integer.parseInt(id));
%>

<h1>编辑客户</h1>
<form action="editcust.jsp" method="post">
    <input type="hidden" name="id" value="<%=customer.getId() %>"/>
    <table>
        <tr><td>名称:</td><td><input type="text" name="name" value="<%=customer.getName() %>"/></td></tr>
        <tr><td>性别:</td><td>
            <input type="radio" name="gender" value="男" <% if(customer.getGender().equals("男")){%>checked<%}%>/>男
            <input type="radio" name="gender" value="女" <% if(customer.getGender().equals("女")){%>checked<%}%>/>女
        </td></tr>
        <tr><td>联系电话:</td><td><input type="text" name="telephone" value="<%=customer.getTelephone() %>"/></td></tr>
        <tr><td>住址:</td><td>
            <input type="text" name="address" value="<%=customer.getAddress() %>"/>
        </td></tr>
        <tr><td colspan="2"><input type="submit" value="编辑客户"/></td></tr>
    </table>
</form>

</body>
</html>

12 编写editcust.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="com.yiidian.dao.CustomerDao"%>
<html>
<head>
    <title>一点教程网-使用JSP完成CRUD</title>
</head>
<body>
<%
    //设置参数的中文编码
    request.setCharacterEncoding("utf-8");
%>
<jsp:useBean id="customer" class="com.yiidian.domain.Customer"></jsp:useBean>
<jsp:setProperty property="*" name="customer"/>

<%
    int i= CustomerDao.update(customer);
    response.sendRedirect("viewcusts.jsp");
%>

</body>
</html>

13 编写deletecust.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="com.yiidian.dao.CustomerDao"%>
<html>
<head>
    <title>一点教程网-使用JSP完成CRUD</title>
</head>
<body>
<jsp:useBean id="customer" class="com.yiidian.domain.Customer"></jsp:useBean>
<jsp:setProperty property="*" name="customer"/>
<%
    CustomerDao.delete(customer);
    response.sendRedirect("viewcusts.jsp");
%>
</body>
</html>

14 运行测试

 

热门文章

优秀文章