JavaWeb JDBC + MySql 通讯录实现简单的增删改查功能案例详解

本文实例讲述了JavaWeb JDBC + MySql 通讯录实现简单的增删改查功能。分享给大家供大家参考,具体如下:

开发工具:Eclipse + Navicat

项目源码:Github:https://github.com/Sunjinhang/JavaWeb

一、新建项目

在Eclipse中新建一个Web项目,至于如何新建Web项目以及如何添加Tomcat服务器的就不赘述了,项目的目录如下

最终实现的效果如下所示:

点击新增可以进行联系人的新增,点击修改/删除可以进行 联系人的修改和删除

部分代码如下

数据库连接:在测试数据库连接时,需要注意mysql 时区的设置,安装mysql时默认的时区时美国时间,与本地相差8个小时,所以如果不修改则在链接数据库时会报错。

package pers.contact.dao;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class BaseDao {
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    public static final String URL = "jdbc:mysql://localhost:3306/demo?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf8&allowMultiQueries=true&serverTimezone=GMT%2B8";
    public static final String USER = "root";
    public static final String PASSWORD = "sasa";
    Connection conn = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    public void getConnection() {
        try {
            // 加载数据库驱动
            Class.forName(DRIVER);
            // 获得数据库连接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public int executeUpdate(String sql, Object... obj) {
        int num = 0;
        getConnection();
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < obj.length; i++) {
                pstmt.setObject(i + 1, obj[i]);
            }
            num = pstmt.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            closeAll();
        }
        return num;
    }
    public ResultSet executeQuery(String sql, Object... obj) {
        getConnection();
        try {
            PreparedStatement pstmt = conn.prepareStatement(sql);
            for (int i = 0; i < obj.length; i++) {
                pstmt.setObject(i + 1, obj[i]);
            }
            rs = pstmt.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
    public void closeAll() {
        try {
            rs.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            pstmt.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

联系人:

package pers.contact.entity;
import java.util.Date;
public class Contact {
    public Contact(int id, String name, int age, String phone, Date date, String favorite) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.phone = phone;
        this.date = date;
        this.favorite = favorite;
    }
    private int id;
    private String name;
    private int age;
    private String phone;
    private Date date;
    private String favorite;
    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 int getAge() {
        return age;
    }
    public void setAge(int age) {
        this.age = age;
    }
    public String getPhone() {
        return phone;
    }
    public void setPhone(String phone) {
        this.phone = phone;
    }
    public Date getDate() {
        return date;
    }
    public void setDate(Date date) {
        this.date = date;
    }
    public String getFavorite() {
        return favorite;
    }
    public void setFavorite(String favorite) {
        this.favorite = favorite;
    }
}

增删改查的实现:

package pers.contact.service;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import pers.contact.entity.Contact;
import pers.contact.dao.BaseDao;;
public class ContactService extends BaseDao {
    ResultSet rs = null;
    public List<Contact> GetAllContact(){
        List<Contact> list = new ArrayList();
        String sql = "select * from contact";
        rs = executeQuery(sql);
        try {
            while (rs.next()) {
                Contact f = new Contact(rs.getInt(1), rs.getString(2),
                        rs.getInt(3), rs.getString(4), rs.getDate(5),
                        rs.getString(6));
                list.add(f);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
    public int AddContact(Contact contact)
    {
        int num = 0;
        String sql = "insert into contact(name,age,phone,date,favorite) values(?,?,?,?,?)";
        try {
            num = executeUpdate(sql, contact.getName(), contact.getAge(), contact.getPhone(),
                    contact.getDate(), contact.getFavorite());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return num;
    }
    public int DeleteContact(int id)
    {
        int num = 0;
        String sql = "delete from contact where id = ?";
        try {
            num = executeUpdate(sql, id);
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
        return num;
    }
    public Contact GetContact(int id) {
        String sql = "select * from contact where id = ?";
        Contact contact = null;
        rs = executeQuery(sql, id);
        try {
            while(rs.next()) {
                contact = new Contact(rs.getInt(1),rs.getString(2),rs.getInt(3),rs.getString(4),rs.getDate(5),rs.getString(6));
            }
        }
        catch(SQLException ex){
            ex.printStackTrace();
        }
        return contact;
    }
    public int UpdateContact(Contact contact) {
        int num = 0;
        String sql = "update contact set name = ?,age = ?,phone = ?,date = ?,favorite = ? where id = ?";
        try {
            num = executeUpdate(sql, contact.getName(),contact.getAge(),contact.getPhone(),contact.getDate(),contact.getFavorite(),contact.getId());
        }
        catch(Exception ex) {
            ex.printStackTrace();
        }
        return num;
    }
}

Servlet:

package pers.contact.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
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 pers.contact.entity.Contact;
import pers.contact.service.ContactService;
/**
 * Servlet implementation class ContactServlet
 */
@WebServlet("/ContactServlet")
public class ContactServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
  /**
   * @see HttpServlet#HttpServlet()
   */
  public ContactServlet() {
    super();
    // TODO Auto-generated constructor stub
  }
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        request.setCharacterEncoding("utf-8");
        HttpSession session = request.getSession();
        PrintWriter out = response.getWriter();
        ContactService ud = new ContactService();
        // 获得do属性
        String dos = request.getParameter("do");
        if (dos == null || dos.equals("")) {
            dos = "index";
        }
        // 主页
        if (dos.equals("index")) {
            List<Contact> ulist = ud.GetAllContact();
            request.setAttribute("ulist", ulist);
            request.getRequestDispatcher("/index.jsp").forward(request, response);
            return;
        }
        if(dos.equals("add")) {
            String name = request.getParameter("name");
            int age = Integer.parseInt(request.getParameter("age"));
            String phone = request.getParameter("phone");
            String dates = request.getParameter("date");
            SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
            Date date = null;
            try {
                date = (Date)sdf.parse(dates);
            } catch (ParseException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //爱好获取
            String favorite = request.getParameter("favorite");
            Contact contact = new Contact(0,name,age,phone,date,favorite);
            ud.AddContact(contact);
            out.print("<script>alert('新增成功!');window.location='ContactServlet?do=index';</script>");
        }
        if(dos.equals("del")) {
            String ids = request.getParameter("id");
            int id = Integer.parseInt(ids);
            ud.DeleteContact(id);
            out.print("<script>alert('删除成功!');window.location='ContactServlet?do=index';</script>");
        }
        if(dos.equals("editbefore")) {
            int id = Integer.parseInt(request.getParameter("id"));
            Contact f = ud.GetContact(id);
            session.setAttribute("edituser", f);
            response.sendRedirect("edit.jsp");
            return;
        }
        if(dos.equals("edit")) {
            try {
                int id = Integer.parseInt(request.getParameter("id"));
                String name = request.getParameter("name");
                int age = Integer.parseInt(request.getParameter("age"));
                String phone = request.getParameter("phone");
                String dates = request.getParameter("date");
                SimpleDateFormat sdf = new SimpleDateFormat("yy-MM-dd");
                Date date = null;
                date = (Date)sdf.parse(dates);
                String favorite = request.getParameter("favorite");
                Contact contact = new Contact(id,name,age,phone,date,favorite);
                ud.UpdateContact(contact);
                out.print("<script>alert('修改成功!');window.location='ContactServlet?do=index';</script>");
            }
            catch(ParseException ex) {
                ex.printStackTrace();
            }
        }
    }
}

JSP页面

index 页面,此页面需要添加 jstl.jar 和standard.jar ,否则无法引用 taglib

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="pers.contact.entity.Contact"%>
<%@ page import="pers.contact.service.ContactService"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
    //下面的语句初始为初始化页面,如果不加下面语句访问主页不会显示数据库中保存的数据
    ContactService ud = new ContactService();
    List<Contact> ulist = ud.GetAllContact();
    request.setAttribute("ulist", ulist);
%>
<!DOCTYPE html>
<html>
<head>
<base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<meta charset="ISO-8859-1">
<link rel="stylesheet"
    href="https://cdn.bootcss.com/foundation/5.5.3/css/foundation.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script
    src="https://cdn.bootcss.com/foundation/5.5.3/js/foundation.min.js"></script>
<script
    src="https://cdn.bootcss.com/foundation/5.5.3/js/vendor/modernizr.js"></script>
<style type="text/css">
table {
    margin: auto;
}
td {
    text-align: center;
}
h1 {
    margin-left: 40%;
}
a#add {
    margin-left: 45%;
}
</style>
<title>Insert title here</title>
</head>
<body style="padding:20px;">
    <h1>通讯录主页</h1>
    <a id="add" href="add.jsp" rel="external nofollow" >新增小伙伴</a>
    <table>
        <thead>
            <tr>
                <th>序号</th>
                <th>姓名</th>
                <th>年龄</th>
                <th>电话</th>
                <th>生日</th>
                <th>爱好</th>
                <th>操作</th>
            </tr>
            <c:forEach var="U" items="${ulist}">
            <tr>
                <th>${U.id}</th>
                <th>${U.name}</th>
                <th>${U.age}</th>
                <th>${U.phone}</th>
                <th>${U.date}</th>
                <th>${U.favorite}</th>
                <th><a href="ContactServlet?do=editbefore&id=${U.id}" rel="external nofollow" >修改</a> <a href="ContactServlet?do=del&id=${U.id}" rel="external nofollow" >删除</a> </th>
            </tr>
            </c:forEach>
        </thead>
        <%--<c:forEach/>标签遍历List--%>
    </table>
</body>
</html>

Add页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<title>My JSP 'add.jsp' starting page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
    href="https://cdn.bootcss.com/foundation/5.5.3/css/foundation.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script
    src="https://cdn.bootcss.com/foundation/5.5.3/js/foundation.min.js"></script>
<script
    src="https://cdn.bootcss.com/foundation/5.5.3/js/vendor/modernizr.js"></script>
</head>
<body>
    <h1>新增页面</h1>
<form action="ContactServlet?do=add" method="post" style="width:50%;">
  <fieldset>
  <label>姓名 <input type="text" placeholder="name" required="required" name="name" /> </label>
  <label>年龄 <input type="number" placeholder="age" required="required" min="1" max="133" name="age" /> </label>
  <label>电话<input type="text" placeholder="phonenum" required="required" name="phone" /> </label>
  <label>生日<input type="date" placeholder="date" required="required" name="date" /> </label>
  <label>爱好<input type="text" placeholder="favorite" required="required" name="favorite" /> </label>
  <input type="submit" value="新增" class="button" />
  <input type="reset" class="button" />
  </fieldset>
 </form>
</body>
</html>

Edit页面

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme() + "://"
            + request.getServerName() + ":" + request.getServerPort()
            + path + "/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<title>My JSP 'add.jsp' starting page</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet"
    href="https://cdn.bootcss.com/foundation/5.5.3/css/foundation.min.css" rel="external nofollow" rel="external nofollow" rel="external nofollow" >
<script src="https://cdn.bootcss.com/jquery/2.1.1/jquery.min.js"></script>
<script
    src="https://cdn.bootcss.com/foundation/5.5.3/js/foundation.min.js"></script>
<script
    src="https://cdn.bootcss.com/foundation/5.5.3/js/vendor/modernizr.js"></script>
</head>
<body>
    <h1>修改页面</h1>
    <form action="ContactServlet?do=edit&id=${edituser.id}" method="post" style="width:50%">
        <fieldset>
            <label>姓名 <input type="text" placeholder="name" name="name" value = "${edituser.name}">
            </label>
            <label>年龄 <input type="text" placeholder="age" name="age" value = "${edituser.age}">
            </label>
            <label>电话<input type="text" placeholder="phone" name="phone" value = "${edituser.phone}">
            </label>
            <label>生日<input type="date" placeholder="date" name="date" value = "${edituser.date}">
            </label>
            <label>爱好<input type="text" placeholder="favorite" name="favorite" value = "${edituser.favorite}">
            </label>
            <input type="submit" value="修改" class="button"> <input type="reset" class="button">
        </fieldset>
    </form>
</body>
</html>

更多java相关内容感兴趣的读者可查看本站专题:《Java面向对象程序设计入门与进阶教程》、《Java数据结构与算法教程》、《Java操作DOM节点技巧总结》、《Java文件与目录操作技巧汇总》和《Java缓存操作技巧汇总》

希望本文所述对大家java程序设计有所帮助。

(0)

相关推荐

  • 解决idea中javaweb的mysql8.0.15配置问题

    mysql8.0.x以后的版本在连接数据库的时候有些不同. 首先: Class.forName("com.mysql.cj.jdbc.Driver"); 其次: DriverManager.getConnection("jdbc:mysql://localhost:3306/java?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC", "

  • javaweb中mysql数据库连接步骤方法及其实例

    一.直接连接,不封装到工具类中,主要步骤: 先导包:mysql-connector-java-5.0.8-bin.jar(点击跳转到下载界面),放在WebRoot/WEB-INF/lib/下 1.加载驱动//com.MySQL.jdbc.Driver 2.获取连接 Connection对象 3.获取用于向数据库发送SQL的Statement对象 4.执行sql,获取数据,解析数据 5.关闭连接,释放资源 /*协议:子协议://主机:端口/数据库名*/ Stringurl="jdbc:mysql:

  • JavaWeb实现用户登录注册功能实例代码(基于Servlet+JSP+JavaBean模式)

    下面通过通过图文并茂的方式给大家介绍JavaWeb实现用户登录注册功能实例代码,一起看看吧. 一.Servlet+JSP+JavaBean开发模式(MVC)介绍 Servlet+JSP+JavaBean模式(MVC)适合开发复杂的web应用,在这种模式下,servlet负责处理用户请求,jsp负责数据显示,javabean负责封装数据. Servlet+JSP+JavaBean模式程序各个模块之间层次清晰,web开发推荐采用此种模式. 这里以一个最常用的用户登录注册程序来讲解Servlet+JS

  • JAVAWEB实现简单的商城项目(一)实例代码解析

     一.项目功能结构 1.功能 2.实体 3.对应sql语句 CREATE DATABASE shop; use shop; create table user( id int(11) primary key auto_increment, username varchar(100), password varchar(100), nickname varchar(100), type int(5) ); INSERT INTO user VALUES (null,'admin','7946521

  • JavaWeb连接数据库MySQL的操作技巧

    数据库是编程中重要的一部分,它囊括了数据操作,数据持久化等各方面.在每一门编程语言中都占有相当大的比例. 本次,我以MySQL为例,使用MVC编程思想(请参阅我之前的博客).简单演示一下JavaWeb对数据库的操作. 1:我们需要掌握简单的SQL语句,并且会简单操作图形化的数据库.我们在数据库建一个表(Users)可以在里面随便添加几条数据. 2:接下来,我们获得驱动并连接到MySQL. package com.joker.web.db; import java.sql.Connection;

  • JavaWeb应用实例:用servlet实现oracle 基本增删改查

    很久没有写博客了,可能是太懒散,不愿意把时间花在这上面,可是我心里还是知道写博客的重要性的 ,所以从今天开始 ,我将与大家分享一下我学Java WEB写的一些小实例  ,我个人是不太喜欢书本上的晦涩的概念的,所以我花了更多的时间在一些应用实例上,我觉得这样的学习方式很适合我,由简到繁,由浅入深 废话不多话,开始我们的第一个实例:  servlet实现Oracle 基本增删改查 开发环境:JDK7 +Myeclipse10+tomcat7.0+oracle 11g 首先附上数据库创建脚本: cre

  • javaweb学习总结——使用JDBC处理MySQL大数据

    BLOB (binary large object),二进制大对象,是一个可以存储二进制文件的容器.在计算机中,BLOB常常是数据库中用来存储二进制文件的字段类型,BLOB是一个大文件,典型的BLOB是一张图片或一个声音文件,由于它们的尺寸,必须使用特殊的方式来处理(例如:上传.下载或者存放到一个数据库). 一.基本概念 在实际开发中,有时是需要用程序把大文本或二进制数据直接保存到数据库中进行储存的. 对MySQL而言只有blob,而没有clob,mysql存储大文本采用的是Text,Text和

  • JavaWeb 网上书店 注册和登陆功能案例详解

    本文实例讲述了JavaWeb 网上书店 注册和登陆功能.分享给大家供大家参考,具体如下: 工具:Eclipse + Navicat 源码地址:https://github.com/Sunjinhang/JavaWeb 用户实体:简简单单的六个属性,编号.姓名.密码.电话.邮箱.地址. package Entity; public class User { public User(String id, String userName, String password, String phone,

  • 使用JavaWeb webSocket实现简易的点对点聊天功能实例代码

    首先给大家声明一点:需要 jdk 7 , tomcat需要支持websocket的版本  1.InitServlet 该类主要是用来初始化构造将来存储用户身份信息的map仓库,利用其初始化方法Init 初始化仓库, 利用其静态方法getSocketList 获得对应的用户身份信息. webSocket ,我认为MessageInbound 用来识别登录人的信息,用它来找到对应的人,推送消息.每次登录都会产生一个MessageInbound. 这里的 HashMap<String,MessageI

  • JavaWeb基于Session实现的用户登陆注销方法示例

    前言 Cookie:cookie是客户端技术,程序把每个用户的数据以cookie的形式写给用户各自的浏览器. 当用户使用浏览器再去访问服务器中的web资源时,就会带着各自的数据区,这样,web资源处理的就是各自的数据了. Session:session是服务器端技术,利用session技术,服务器在运行时可以为每一个用户的浏览器创建其独享的session对象,由于session为用户浏览器独享,所以用户在访问服务器的web资源时,可以把各自的数据放在session中,当用户再次去访问服务器中的其

随机推荐