完成联系人页面的增删该查。
点击首页的添加联系人按钮跳转到add.jsp页面
点击首页中的联系人的修改按钮,先到后台查询联系人的信息,携带参数为联系人的id。
后台servlet会把联系人信息添加到request域中,转发到update.jsp页面。(后面会详解贴出代码)
表的字段和实体类的字段要一一对应
实体类
package com.zmysna.entity;
public class Contact{
private int id;
private String name;
private String gender;
private int age;
private String location;
private String qq;
private String email;
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 String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public String getQq() {
return qq;
}
public void setQq(String qq) {
this.qq = qq;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
本案例采用三层架构,最关键的是servlet层,服务层和数据访问层基本只有一句代码。这里贴出服务层和数据库访问层的代码。
这里使用JDBCTemplate进行数据库的增删改查操作。
JDBCTemplate构造函数需要一个数据库连接池,通过一个工具类DruidUtils获得数据库连接池。
package com.zmysna.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class DruidUtils {
private static DataSource dataSource;
static {
//创建配置文件对象
Properties pro = new Properties();
//加载src目录下的druid.properties文件获得一个输入流对象
InputStream in = DruidUtils.class.getResourceAsStream("/druid.properties");
try {
//加载输入流中的配置文件信息
pro.load(in);
//使用连接池工厂的静态方法获得一个数据连接池对象
dataSource = DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获得一个数据库连接对象
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
/**
* 获得数据库连接池对象
* @return
*/
public static DataSource getDataSource() {
return dataSource;
}
}
工具类所需要的配置文件druid.properties
#db1是数据库名
url=jdbc:mysql://localhost:3306/db1
username=root
password=root
driverClassName=com.mysql.jdbc.Driver
Dao层代码
package com.zmysna.dao;
import com.zmysna.entity.Contact;
import com.zmysna.utils.DruidUtils;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
/**
* 联系人:数据访问层
*/
public class ContactDao {
private JdbcTemplate jdbcTemplate = new JdbcTemplate(DruidUtils.getDataSource());
/**
* 查询所有联系人
* @return
*/
public List<Contact> selectAll() {
return jdbcTemplate.query("select * from contact", new BeanPropertyRowMapper<>(Contact.class));
}
/**
* 更新联系人
* @param contact
* @return
*/
public int updateContact(Contact contact) {
return jdbcTemplate.update("update contact SET name=?, gender=?, age=?, location=?, qq=?, email=? where id=?",
contact.getName(),contact.getGender(),contact.getAge(),contact.getLocation(),contact.getQq(),contact.getEmail(),contact.getId());
}
/**
* 添加联系人
* @param contact
* @return
*/
public int saveContact(Contact contact) {
return jdbcTemplate.update("INSERT INTO contact VALUES(null,?,?,?,?,?,?)",
contact.getName(),contact.getGender(),contact.getAge(),contact.getLocation(),contact.getQq(),contact.getEmail());
}
/**
* 删除联系人
* @param id
* @return
*/
public int deleteContact(int id) {
return jdbcTemplate.update("DELETE FROM contact WHERE id=?",id);
}
/**
* 根据ID查询联系人
* @param id
* @return
*/
public Contact queryById(int id) {
try {
return jdbcTemplate.queryForObject("SELECT * FROM contact WHERE id = ?", new BeanPropertyRowMapper<>(Contact.class), id);
} catch (DataAccessException e) {
e.printStackTrace();
return null;
}
}
}
这里服务层完全是为了三层架构而三层架构,完全可以省去
package com.zmysna.service;
import com.zmysna.dao.ContactDao;
import com.zmysna.entity.Contact;
import java.util.List;
/**
* 联系人:服务层
*/
public class ContactService {
//注入ContactDao
private ContactDao contactDao = new ContactDao();
/**
* 显示所有联系人
* @return
*/
public List<Contact> showAll() {
return contactDao.selectAll();
}
/**
* 更新联系人
* @return
*/
public int updateContact(Contact contact) {
return contactDao.updateContact(contact);
}
/**
* 添加联系人
* @param contact
* @return
*/
public int addContact(Contact contact) {
return contactDao.saveContact(contact);
}
/**
* 删除联系人
* @param id
* @return
*/
public int deleteContact(int id) {
return contactDao.deleteContact(id);
}
/**
* 根据ID查询联系人
* @param id
* @return
*/
public Contact queryById(int id){
return contactDao.queryById(id);
}
}
开启服务器键入localhost:8080/index.jsp,首页直接转发到/show
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
$Title$
<%-- 转发到路径'/show' --%>
服务器通过访问路径/show找到ShowContactsServlet
package com.zmysna.servlet;
import com.zmysna.entity.Contact;
import com.zmysna.service.ContactService;
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.util.List;
/**
* 查询所有的联系人
*/
@WebServlet("/show")
public class ShowContactsServlet extends HttpServlet {
//创建一个联系人服务
private ContactService contactService = new ContactService();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//调用服务层的方法
List<Contact> contacts = contactService.showAll();
//将得到的联系人放在request域中
request.setAttribute("contacts", contacts);
//将请求转发到list.jsp页面
request.getRequestDispatcher("list.jsp").forward(request,response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
list.jsp用EL表达式和JSTL标签库显示所有联系人
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
Bootstrap模板
在list.jsp中点击添加联系人按钮。跳转到add.jsp页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
添加用户
添加联系人页面
add.jsp点击提交,将表单提交,并向**/add发出post请求,服务器通过/add找到AddContactServlet**
package com.zmysna.servlet;
import com.zmysna.entity.Contact;
import com.zmysna.service.ContactService;
import org.apache.commons.beanutils.BeanUtils;
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.lang.reflect.InvocationTargetException;
import java.util.Map;
@WebServlet("/add")
public class AddContactServlet extends HttpServlet {
private ContactService contactService = new ContactService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置响应和请求的编码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获取请求数据的键值对映射
Map<String, String[]> parameterMap = request.getParameterMap();
//创建一个Contact对象
Contact contact = new Contact();
try {
//将parameterMap中的数据封装的Contact对象中
BeanUtils.populate(contact, parameterMap);
} catch (Exception e) {
e.printStackTrace();
}
//将联系人添加到数据库中
contactService.addContact(contact);
//将请求转发到/show,显示所有联系人。
request.getRequestDispatcher("/show").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
在list.jsp中点击修改按钮。跳转到localhost:8080/query?id=${contact.id}; 携带的参数是本行联系人的id。
<a class="btn btn-default btn-sm" href="query?id=${contact.id}">修改</a>
服务器通过/query找到QueryServlet,Queryservlet通过getParameter(“id”) 获得参数值。
package com.zmysna.servlet;
import com.zmysna.entity.Contact;
import com.zmysna.service.ContactService;
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;
@WebServlet("/query")
public class QueryServlet extends HttpServlet {
private ContactService contactService = new ContactService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//获得参数值
String id = request.getParameter("id");
//到数据库中查询特定的联系人。
Contact contact = contactService.queryById(Integer.parseInt(id));
//把这个联系人添加到request域中
request.setAttribute("contact",contact);
//创建一个地址列表,也添加到request域中
String[] address = {"广东", "湖南", "海南", "河北", "江西", "河南", "江苏", "广西", "上海", "北海道", "二五道"};
request.setAttribute("address",address);
//转发到update.jsp页面
request.getRequestDispatcher("update.jsp").forward(request,response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
}
update.jsp使用EL表达式和JSTL标签库回显要修改联系人的当前信息
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<!-- 网页使用的语言 -->
<html lang="zh-CN">
<head>
<base href="<%=basePath%>"/>
<!-- 指定字符集 -->
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>修改用户</title>
<link href="css/bootstrap.min.css" rel="stylesheet">
<script src="js/jquery-2.1.0.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</head>
<body>
<div class="container" style="width: 400px;">
<h3 style="text-align: center;">修改联系人</h3>
<form action="/update" method="post">
<input type="hidden" name="id" value="${contact.id}">
<div class="form-group">
<label for="name">姓名:</label>
<input type="text" class="form-control" id="name" name="name" readonly="readonly" placeholder="请输入姓名"
value="${contact.name}"/>
</div>
<div class="form-group">
<label>性别:</label>
<input type="radio" name="gender" value="男" ${contact.gender=="男"?"checked='checked'":""} />男
<input type="radio" name="gender" value="女" ${contact.gender=="女"?"checked='checked'":""} />女
</div>
<div class="form-group">
<label for="age">年龄:</label>
<input type="text" class="form-control" id="age" name="age" placeholder="请输入年龄" value="${contact.age}"/>
</div>
<div class="form-group">
<label for="location">籍贯:</label>
<select name="location" class="form-control" id="location" >
<c:forEach items="${address}" var="lc" >
//选中要修改的联系人的地址。
<option value="${lc}" ${contact.location==lc? "selected='selected'":""}>${lc}</option>
</c:forEach>
</select>
</div>
<div class="form-group">
<label for="qq">QQ:</label>
<input type="text" class="form-control" name="qq" id="qq" placeholder="请输入QQ号码" value="${contact.qq}"/>
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="text" class="form-control" name="email" id="email" placeholder="请输入邮箱地址" value="${contact.email}"/>
</div>
<div class="form-group" style="text-align: center">
<input class="btn btn-primary" type="submit" value="提交"/>
<input class="btn btn-default" type="reset" value="重置"/>
<input class="btn btn-default" type="button" value="返回"/>
</div>
</form>
</div>
</body>
</html>
在list.jsp中点击修改按钮。跳转到localhost:8080/delete?id=${contact.id}; 携带的参数是本行联系人的id。
删除
服务器通过/delete找到DeleteContactServlet
package com.zmysna.servlet;
import com.zmysna.service.ContactService;
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.util.Map;
@WebServlet("/delete")
public class DeleteContactServlet extends HttpServlet {
private ContactService contactService = new ContactService();
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//设置请求和响应的编码
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//获得请求数据中id的值,转换为INT类型
String strid = request.getParameter("id");
int id = Integer.parseInt(strid);
//在数据库中删除指定的联系人
contactService.deleteContact(id);
//重定向到首页
response.sendRedirect("index.jsp");
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
}
链接:https://pan.baidu.com/s/1mTJkSBP6uRzZKbJVsVEhgw
提取码:cp4a