欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

jsp+servlet+jdbc+mysql通讯录管理系统

程序员文章站 2022-06-18 11:19:43
...

一天做了个简单增删该查的小项目,内容不算充盈,但是麻雀虽小五脏俱全。
下面附图:

主页面:
jsp+servlet+jdbc+mysql通讯录管理系统
添加页面:
jsp+servlet+jdbc+mysql通讯录管理系统
删除和修改都在主页面进行。

javaWeb结构图:
jsp+servlet+jdbc+mysql通讯录管理系统
数据库结构图:
jsp+servlet+jdbc+mysql通讯录管理系统
先附2个jsp页面代码:
主页面:addressListSys.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>    
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="UTF-8">
<title>通讯录管理系统</title>
	</head>
	<body>
	<c:if test="${list==null }">
		<jsp:forward page="ShowServlet"></jsp:forward>
	</c:if>
		<h2 style="text-align: center;">通讯录管理系统</h2>
		<p style="text-align: center;"><a href="addFriends.jsp">添加好友</a>&nbsp;&nbsp;<a href="ShowServlet">查询好友</a>&nbsp;&nbsp;<a href="#">高级搜索</a><p/>
			
		<hr />
		<br /><br />
		
	<center>
		<div id="wbk">
			
				<table border="1" >
					<tr>
						<td>序号</td>
						<td>姓名</td>
						<td>性别</td>
						<td>年龄</td>
						<td>电话</td>
						<td>邮箱</td>
						<td>地址</td>
						<td>操作</td>
					</tr>
					<c:forEach items="${list}" var="list">
					<form method="post" name="myForm${list.id}" action="UpdateServlet?id=${list.id}">
						<tr>
							<td>${list.id}</td>
							<td><input type="text" value="${list.name}" style="border:none" name="name"/></td>
							<td><input type="text" value="${list.sex}" style="border:none" name="sex"/></td>
							<td><input type="text" value="${list.age}" style="border:none" name="age"/></td>
							<td><input type="text" value="${list.tel}" style="border:none" name="tel"/></td>
							<td><input type="text" value="${list.email}" style="border:none" name="email"/></td>
							<td><input type="text" value="${list.address}" style="border:none" name="address"/></td>
							<td><a href="javascript:document.myForm${list.id}.submit();">修改
								</a>&nbsp;&nbsp;&nbsp;&nbsp;<a href="DeleteServlet?id=${list.id}">删除</td>
						</tr>
				  </form>
					</c:forEach>
				</table>
			
		</div>
	</center>	
	</body>
</html>

添加页面:addFriends.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>

	<h2 style="text-align: center;">通讯录管理系统</h2>
	<p style="text-align: center;">
		<a href="addFriends.jsp">添加好友</a>&nbsp;&nbsp;<a href="ShowServlet">查询好友</a>&nbsp;&nbsp;<a
			href="#">高级搜索</a>
	<p />

	<hr />
	<br />
	<br />
	<center>
		<div id="wbk">
			<form action="AddServlet" method="post">
				<table border="1">
					<tr>
						<td>序号:</td>
						<td><input type="text" name="addId" /></td>
					</tr>
					<tr>
						<td>姓名:</td>
						<td><input type="text" name="addName" /></td>
					</tr>
					<tr>
						<td>性别:</td>
						<td><input type="text" name="addSex" /></td>
					</tr>
					<tr>
						<td>年龄:</td>
						<td><input type="text" name="addAge" /></td>
					</tr>
					<tr>
						<td>电话:</td>
						<td><input type="text" name="addTel" /></td>
					</tr>
					<tr>
						<td>邮箱:</td>
						<td><input type="text" name="addEmail" /></td>
					</tr>
					<tr>
						<td>地址:</td>
						<td><input type="text" name="addAddr" /></td>
					</tr>
				</table>
				<br />
				<br /> <input type="submit" value="保存" /> <a
					href="addressListSys.jsp">取消</a>
			</form>
		</div>
	</center>
</body>
</html>

dao:
BaseDao页面:

package dao;

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

/**
 * 数据访问层基础数据访问类
 * @author Think
 *
 */
public class BaseDao {
	private static final String  URL = "jdbc:mysql://localhost:3306/addresslistsys?useSSL=false&serverTimezone=UTC&characterEncoding=utf-8";
	private static final String USER = "root";
	private static final String PASSWORD ="";
	protected static Connection conn;
	protected PreparedStatement preStmt = null;
	protected ResultSet rs = null;
	
	/**
	 * 获取连接方法
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public static Connection getConn() throws ClassNotFoundException, SQLException {
		try {
			Class.forName("com.mysql.cj.jdbc.Driver");
//			Class.forName("com.mysql.jdbc.Driver");
			conn = DriverManager.getConnection(URL,USER,PASSWORD);
		} catch (ClassNotFoundException e) {
			throw e;
		} catch (SQLException e) {
			throw e;
		}
		return conn;
	}
	/**
	 * 创建预编译的语句集对象
	 * @param sql
	 * @return
	 * @throws ClassNotFoundException
	 * @throws SQLException
	 */
	public PreparedStatement createPreStmt(String sql) throws ClassNotFoundException, SQLException {
		try {
			preStmt = getConn().prepareStatement(sql);
		} catch (ClassNotFoundException e) {
			throw e;
		} catch (SQLException e) {
			throw e;
		}
		return preStmt;
	}
	
	/**
	 * 释放数据库连接相关对象
	 * @throws SQLException 
	 */
	public void close() throws SQLException {
		try {
			if(rs!=null) {
				rs.close();
			}
			if(preStmt!=null) {
				preStmt.close();
			}
			if(conn!=null) {
				conn.close();
			}
		} catch (SQLException e) {
			throw e;
		} finally {
			rs = null;
			preStmt =null;
			conn = null;
		}
	}
}

增删改查的dao:addrDao

package dao;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import vo.addr;
/**
 * * <p>Title: addrDao</p>
* <p>Description: 数据访问层</p>
* @author 与其终
* @date 下午2:47:26
 */
public class addrDao extends BaseDao{
//	添加
	public boolean insertAddr(int addId, String addName, String addSex, int addAge, String addTel, String addEmail,
			String addAddr) throws ClassNotFoundException, SQLException {
		String sql = "insert into addr values(?,?,?,?,?,?,?)";
		boolean flag = false;
		int i= 0;
		preStmt = this.createPreStmt(sql);
		// 设置参数
		preStmt.setInt(1, addId);
		preStmt.setString(2, addName);
		preStmt.setString(3, addSex);
		preStmt.setInt(4, addAge);
		preStmt.setString(5, addTel);
		preStmt.setString(6, addEmail);
		preStmt.setString(7, addAddr);
		
		// 发送sql语句到sql引擎执行
		i = preStmt.executeUpdate();
		if(i>0){
			flag = true;
		}
		this.close();
		return flag;
	}
//	删除一条
	public int deleteAddr(int id) throws ClassNotFoundException, SQLException {
		String sql = "delete from addr where id = ?";
		preStmt = this.createPreStmt(sql);
		// 设置参数
		preStmt.setInt(1, id);
		
		int i = 0;
		i = preStmt.executeUpdate();
		this.close();
		return i;
	}
//	查询所有
	public List<addr> findAll() throws ClassNotFoundException, SQLException {
		List<addr> list = null;
		String sql = "select * from addr";

		preStmt = this.createPreStmt(sql); 
		// 接受查询语句返回的结果集
		rs = preStmt.executeQuery();
		list = new ArrayList<addr>();

		while (rs.next()) {
			addr a = new addr();
			a.setId(rs.getInt("id"));
			a.setName(rs.getString("name"));     
			a.setSex(rs.getString("sex"));
			a.setAge(rs.getInt("age"));
			a.setTel(rs.getString("tel"));
			a.setEmail(rs.getString("email"));
			a.setAddress(rs.getString("address"));
			
			list.add(a);
			System.out.println("-----------addrDao:"+a);
		}
		this.close();
		return list;
	}
//	//删除所有
//	public Boolean deleteAll() throws ClassNotFoundException, SQLException {
//		String sql = "delete from store";
//		boolean flag=false;
//		preStmt=this.createPreStmt(sql);
//		int i = preStmt.executeUpdate();
//		if(i>0) {
//			flag = true;
//			System.out.println("删除成功");
////			conn.commit();
//		}else{
//			flag = false;
//			System.out.println("删除失败");
////			conn.rollback();
//		}
//		this.close();
//		return flag;
//	}
//	

//	修改
	public void updateAddr(int id, String name,String sex,int age,String tel,String email, String address) throws ClassNotFoundException, SQLException{
		String sql = "update addr set id = ?,name = ?,sex = ?,age = ?,tel = ?,email = ?,address = ? where id = ?";
		preStmt = this.createPreStmt(sql);

		preStmt.setInt(1, id);
		preStmt.setString(2, name);
		preStmt.setString(3, sex);
		preStmt.setInt(4, age);
		preStmt.setString(5, tel);
		preStmt.setString(6, email);
		preStmt.setString(7, address);
		preStmt.setInt(8, id);
		
		boolean flag=false;
		int i = preStmt.executeUpdate();
		System.out.println(i);
		if(i>0) {
			flag = true;
			System.out.println("修改成功");
		}else{
			flag = false;
			System.out.println("修改失败");
		}
		this.close();
	}
//		查询单个商品
		public addr findAddrById(int id) throws ClassNotFoundException, SQLException {
			addr a = new addr();
			String sql = "select * from addr where id = ?";

			preStmt = this.createPreStmt(sql); 
			preStmt.setInt(1, id);
			// 接受查询语句返回的结果集
			rs = preStmt.executeQuery();

			while (rs.next()) {
				a.setId(rs.getInt("id"));
				a.setName(rs.getString("name"));     
				a.setSex(rs.getString("sex"));
				a.setAge(rs.getInt("age"));
				a.setTel(rs.getString("tel"));
				a.setEmail(rs.getString("email"));
				a.setAddress(rs.getString("address"));
			}
			System.out.println("findAddrById-----"+a);
			this.close();
			return a;
		}
}

Servlet:
增:AddServlet

package servlet;

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

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 dao.addrDao;

/**
 * Servlet implementation class AddServlet
 */
@WebServlet("/AddServlet")
public class AddServlet extends HttpServlet {
	private static final long serialVersionUID = 6739203285919462536L;

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
		request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        
//		PrintWriter out = response.getWriter();
        int addId = Integer.parseInt(request.getParameter("addId"));
        String addName = request.getParameter("addName");
        String addSex = request.getParameter("addSex");
        int addAge = Integer.parseInt(request.getParameter("addAge"));
        String addTel = request.getParameter("addTel");
        String addEmail = request.getParameter("addEmail");
        String addAddr = request.getParameter("addAddr");
       
        addrDao dao = new addrDao();
        boolean flag;
		try {
			flag = dao.insertAddr(addId,addName,addSex,addAge,addTel,addEmail,addAddr);
			if(flag){
				request.getRequestDispatcher("addressListSys.jsp").forward(request, response);
	        	System.out.println("添加成功");
//	            response.sendRedirect(request.getContextPath() + "/addressListSys.jsp");

	        }else{
	            System.out.println("添加失败");
//	            response.sendRedirect(request.getContextPath() + "/addFriends.jsp");
	            request.getRequestDispatcher("addFriends.jsp").forward(request, response);
	        }
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}       
	}
}

删:DeleteServlet

package servlet;

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

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 dao.addrDao;

/**
 * Servlet implementation class DeleteServlet
 */
@WebServlet("/DeleteServlet")
public class DeleteServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		int id = Integer.parseInt(request.getParameter("id"));
		int i;
		addrDao dao = new addrDao();
		try {
			i = dao.deleteAddr(id);
			if(i>0){				request.getRequestDispatcher("addressListSys.jsp").forward(request, response);
				System.out.println("删除成功");
			}else{
				System.out.println("删除失败");
			}
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

改:UpdateServlet

package servlet;

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

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 dao.addrDao;
import vo.addr;

/**
 * Servlet implementation class UpdateServlet
 */
@WebServlet("/UpdateServlet")
public class UpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		request.setCharacterEncoding("utf-8");
		
		int id = Integer.parseInt(request.getParameter("id"));
		System.out.println("更新前得到的id为:**************"+id);
		
		String name = request.getParameter("name");
		String sex = request.getParameter("sex");
		int age = Integer.parseInt(request.getParameter("age"));
		String tel = request.getParameter("tel");
		String email = request.getParameter("email");
		String address = request.getParameter("address");
		
		System.out.println("更新后得到的tel+emai+addrss为:**************"+age+tel+email+address);
		addr a = new addr();
		addrDao dao = new addrDao();
		try {
			dao.updateAddr(id,name,sex,age,tel,email,address);
			System.out.println("dao.updateAddr跑完了——————————————————————————");
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		request.getRequestDispatcher("addressListSys.jsp").forward(request, response);		
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

查:ShowServlet

package servlet;

import java.io.IOException;
import java.sql.SQLException;
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 dao.addrDao;
import vo.addr;

/**
 * Servlet implementation class ShowServlet
 */
@WebServlet("/ShowServlet")
public class ShowServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
    public ShowServlet() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		addrDao dao = new addrDao();
		
		List<addr> list;
		try {
			list = dao.findAll();
			System.out.println("-----------ShowServlet:"+list);
			request.setAttribute("list", list);
		} catch (ClassNotFoundException | SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		request.getRequestDispatcher("addressListSys.jsp").forward(request, response);
		
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doGet(request, response);
	}
}

以上就是完整的项目了。

我是与其终,一个风起云涌的女孩子。
很高兴你能看到我的博客,希望能对你有所帮助。
jsp+servlet+jdbc+mysql通讯录管理系统