这个JavaWeb小案例主要实现的主要功能如下:
- 增加联系人信息
- 删除联系人信息
- 修改联系人信息
- 查询联系人信息
- 分页查询联系人
- 另外也对分页查询功能实现了小优化以及对servlet处理也实现了一些小优化
前言
案例效果显示:
(1)主界面(比较简陋):
(2)增加删除修改页面:
(3)分页展示联系人页面:
一、技术分析
传统方式的开发一个请求对应一个Servlet:这样的话会导致一个模块的Servlet过多,导致整个项目的Servlet都会很多. 能不能让一个模块用一个Servlet处理请求. 当前是联系人模块, 就创建一个LinkManServlet
-
传统方式
查询所有的联系人 :http://localhost:8080/day27/findAll
添加联系人: :http://localhost:8080/day27/add
删除联系人 :http://localhost:8080/day27/delete
-
以模块为单位创建Servlet分析
查询所有的联系人 :http://localhost:8080/day27/linkManServlet?action=findAll
添加联系人: :http://localhost:8080/day27/linkManServlet?action=add
删除联系人 :http://localhost:8080/day27/linkManServlet?action=delete
- 以模块为单位:
@WebServlet("/linkman")
public class LinkManServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//1.获得method请求参数
String action = request.getParameter("action");
//2.判断
if("findAll".equals(action)){
findAll(request,response);
}
if("add".equals(action)){
add(request,response);
}
if("delete".equals(action)){
delete(request,response);
}
}
//删除联系人
public void delete(HttpServletRequest request,HttpServletResponse response){
}
//查询所有的联系人
public void findAll(HttpServletRequest request,HttpServletResponse response){
}
//添加联系人
public void add(HttpServletRequest request,HttpServletResponse response){
}
}
二、思路分析图示
(1)显示所有联系人:
(2)删除联系人:
(3)添加联系人:
(4)修改联系人:
三、准备工作
- 数据库的创建
CREATE TABLE linkman (
id int primary key auto_increment,
name varchar(50),
sex varchar(50),
age int,
address varchar(50),
qq varchar(50),
email varchar(50)
);
INSERT INTO `linkman` (`id`, `name`, `sex`, `age`, `address`, `qq`, `email`) VALUES
(null, '张三', '男', 11, '广东', '766335435', '766335435@qq.com'),
(null, '李四', '男', 12, '广东', '243424242', '243424242@qq.com'),
(null, '王五', '女', 13, '广东', '474574574', '474574574@qq.com'),
(null, '赵六', '女', 18, '广东', '77777777', '77777777@qq.com'),
(null, '钱七', '女', 15, '湖南', '412132145', '412132145@qq.com'),
(null, '王八', '男', 25, '广西', '412132775', '412132995@qq.com');
- JavaBean的创建
package com.DJL.pojo;
import java.io.Serializable;
public class LinkMan implements Serializable {
private Integer id;
private String name;
private String sex;
private Integer age;
private String address;
private String qq;
private String email;
@Override
public String toString() {
return "LinkMan{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", address='" + address + '\'' +
", qq='" + qq + '\'' +
", email='" + email + '\'' +
'}';
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
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;
}
}
- 需要用到的jar包以及前端页面:
这里我放在了百度网盘,自取即可
链接:资料
提取码:lzdj
四、完整代码:
- 项目的完整结构目录:
druid.properties:
# 数据库连接参数
url=jdbc:mysql://localhost:3306/day29?charcterEncoding=utf8
username=root
password=123456
driverClassName=com.mysql.jdbc.Driver
# 连接池的参数
initialSize=10
maxActive=10
maxWait=2000
LinkManDao:
package com.DJL.dao;
import com.DJL.pojo.LinkMan;
import com.DJL.utils.DruidUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.SQLException;
import java.util.List;
/**
* @author DJL
* @create 2021-11-07 23:19
*/
public class LinkManDao {
private QueryRunner qr = new QueryRunner(DruidUtil.getDataSource());
public List<LinkMan> findAll() throws Exception {
String sql = "select * from linkman";
List<LinkMan> list = qr.query(sql, new BeanListHandler<LinkMan>(LinkMan.class));
return list;
}
public void add(LinkMan linkMan) throws SQLException {
String sql = "insert into linkman values(null,?,?,?,?,?,?)";
qr.update(sql,linkMan.getName(),linkMan.getSex(),linkMan.getAge(),linkMan.getAddress(),linkMan.getQq(),linkMan.getAddress());
}
public void deleteById(int id) throws Exception {
String sql = "delete from linkman where id=?";
qr.update(sql,id);
}
public LinkMan findOne(int id) throws Exception {
String sql = "select * from linkman where id=?";
LinkMan linkMan = qr.query(sql, new BeanHandler<LinkMan>(LinkMan.class), id);
return linkMan;
}
public void update(LinkMan linkMan) throws Exception {
String sql = "update linkman set name=?,sex=?,age=?,address=?,qq=?,email=? where id=?";
qr.update(sql,linkMan.getName(),linkMan.getSex(),linkMan.getAge(),linkMan.getAddress(),linkMan.getQq(),linkMan.getEmail(),linkMan.getId());
}
public Long findTotalSize() throws Exception {
String sql = "select count(*) from linkman";
Long totalSize = (Long) qr.query(sql, new ScalarHandler());
return totalSize;
}
public List<LinkMan> findPageList(Long currentPage, Integer pageSize) throws Exception {
String sql = "select * from linkman limit ?,?";
List<LinkMan> linkManList = qr.query(sql, new BeanListHandler<LinkMan>(LinkMan.class),(currentPage-1)*pageSize,pageSize);
return linkManList;
}
}
LinkMan:
package com.DJL.pojo;
import java.io.Serializable;
public class LinkMan implements Serializable {
private Integer id;
private String name;
private String sex;
private Integer age;
private String address;
private String qq;
private String email;
@Override
public String toString() {
return "LinkMan{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", age=" + age +
", address='" + address + '\'' +
", qq='" + qq + '\'' +
", email='" + email + '\'' +
'}';
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
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;
}
}
PageBean:
package com.DJL.pojo;
import java.io.Serializable;
import java.util.List;
/**
* @author DJL
* @create 2021-11-10 13:40
*/
public class PageBean<T> implements Serializable {
//总条数
private Long totalSize;
//总页数
private Long totalPage;
//当前页数
private Long currentPage;
//每页条数
private Integer pageSize;
//当前页的数据集合
private List<T> list;
public Long getTotalSize() {
return totalSize;
}
public Long getTotalPage() {
return totalPage;
}
public Long getCurrentPage() {
return currentPage;
}
public Integer getPageSize() {
return pageSize;
}
public List<T> getList() {
return list;
}
public void setTotalSize(Long totalSize) {
this.totalSize = totalSize;
}
public void setTotalPage(Long totalPage) {
this.totalPage = totalPage;
}
public void setCurrentPage(Long currentPage) {
this.currentPage = currentPage;
}
public void setPageSize(Integer pageSize) {
this.pageSize = pageSize;
}
public void setList(List<T> list) {
this.list = list;
}
@Override
public String toString() {
return "PageBean{" +
"totalSize=" + totalSize +
", totalPage=" + totalPage +
", currentPage=" + currentPage +
", pageSize=" + pageSize +
", list=" + list +
'}';
}
}
LinkManService:
package com.DJL.service;
import com.DJL.dao.LinkManDao;
import com.DJL.pojo.LinkMan;
import com.DJL.pojo.PageBean;
import java.util.List;
public class LinkManService{
private LinkManDao linkManDao = new LinkManDao();
public List<LinkMan> findAll() throws Exception {
return linkManDao.findAll();
}
public void add(LinkMan linkMan) throws Exception {
linkManDao.add(linkMan);
}
public void deleteById(int id) throws Exception {
linkManDao.deleteById(id);
}
public LinkMan findOne(int id) throws Exception {
return linkManDao.findOne(id);
}
public void update(LinkMan linkMan) throws Exception {
linkManDao.update(linkMan);
}
public PageBean<LinkMan> findByPage(Long currentPage, Integer pageSize) throws Exception {
//1.创建一个pageBean对象
PageBean<LinkMan> pageBean = new PageBean<>();
//2.设置pageBean的五个属性
//3.设置currentPage
pageBean.setCurrentPage(currentPage);
//4.设置pageSize
pageBean.setPageSize(pageSize);
//5.设置总条数,调用dao层方法,获取联系人总条数
Long totalSize = linkManDao.findTotalSize();
pageBean.setTotalSize(totalSize);
//6.设置总页数
Long totalPage = totalSize%pageSize==0 ? (totalSize/pageSize):(totalSize/pageSize)+1;
pageBean.setTotalPage(totalPage);
//7.设置list
List<LinkMan> list = linkManDao.findPageList(currentPage,pageSize);
pageBean.setList(list);
return pageBean;
}
}
LinkManServlet:
package com.DJL.web.servlet;
import com.DJL.pojo.LinkMan;
import com.DJL.pojo.PageBean;
import com.DJL.service.LinkManService;
import com.sun.org.glassfish.gmbal.Description;
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.lang.reflect.Method;
import java.util.List;
import java.util.Map;
@WebServlet("/linkman")
public class LinkManServlet extends HttpServlet {
private LinkManService linkManService = new LinkManService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String action = req.getParameter("action");
/**
改进之前的代码
if ("findAll".equals(action)) {
findAll(req,resp);
}
if("add".equals(action)){
add(req,resp);
}
if("findOne".equals(action)){
findOne(req,resp);
}
if("delete".equals(action)){
deleteById(req,resp);
}
if("update".equals(action)){
update(req,resp);
}
if("findByPage".equals(action)){
findByPage(req,resp);
}
*/
//通过反射改进之后的代码
try {
//根据方法名获取方法
Method method = this.getClass().getDeclaredMethod(action, HttpServletRequest.class, HttpServletResponse.class);
//执行方法
method.invoke(this,req,resp);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
/***
* @description: 分页查询联系人
* @param: [req, resp]
* @return: void
*/
private void findByPage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
//1.前端页面的currentPage和pageSzize的值
Long currentPage = Long.valueOf(req.getParameter("currentPage"));
Integer pageSize = Integer.valueOf(req.getParameter("pageSize"));
//2.调用业务层方法,查询当前页的pageBean
PageBean<LinkMan> pageBean = linkManService.findByPage(currentPage,pageSize);
System.out.println(pageBean);
//3.将pageBean对象存进request域对象中
req.setAttribute("pageBean",pageBean);
} catch (Exception e) {
e.printStackTrace();
}
//4.跳转到list_page.jsp
req.getRequestDispatcher("list_page.jsp").forward(req,resp);
}
/***
* @description: 修改联系人
* @param: [req, resp]
* @return: void
*/
private void update(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
Map<String, String[]> parameterMap = req.getParameterMap();
LinkMan linkMan = new LinkMan();
BeanUtils.populate(linkMan,parameterMap);
linkManService.update(linkMan);
} catch (Exception e) {
e.printStackTrace();
}
resp.sendRedirect("linkman?action=findAll");
}
/***
* @description: 通过id删除联系人
* @param: [req, resp]
* @return: void
*/
private void deleteById(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
int id = Integer.valueOf(req.getParameter("id"));
linkManService.deleteById(id);
resp.sendRedirect("linkman?action=findAll");
} catch (Exception e) {
e.printStackTrace();
resp.getWriter().write("删除失败");
}
}
/***
* @description: 查询一个联系人
* @param: [req, resp]
* @return: void
*/
private void findOne(HttpServletRequest req, HttpServletResponse resp){
try {
int id = Integer.valueOf(req.getParameter("id"));
LinkMan linkMan = linkManService.findOne(id);
req.setAttribute("linkMan",linkMan);
req.getRequestDispatcher("update.jsp").forward(req,resp);
} catch (Exception e) {
e.printStackTrace();
}
}
/***
* @description:删除联系人
* @param: [req, resp]
* @return: void
*/
private void add(HttpServletRequest req, HttpServletResponse resp) throws IOException {
try {
Map<String, String[]> parameterMap = req.getParameterMap();
LinkMan linkMan = new LinkMan();
BeanUtils.populate(linkMan, parameterMap);
linkManService.add(linkMan);
resp.sendRedirect("linkman?action=findAll");
} catch (Exception e) {
e.printStackTrace();
resp.getWriter().write("添加失败");
}
}
/***
* @description: 查询所有联系人
* @param: [req, resp]
* @return: void
*/
private void findAll(HttpServletRequest req,HttpServletResponse resp) throws ServletException, IOException {
try {
//1.调用业务层方法,查询所有联系人信息
List<LinkMan> listMan = null;
listMan = linkManService.findAll();
//2.将lisMan存入到request域对象当中
req.setAttribute("list",listMan);
//3.请求转发跳到list.jsp页面进行展示
req.getRequestDispatcher("list.jsp").forward(req,resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
DruidUtil:
package com.DJL.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.InputStream;
import java.util.Properties;
public class DruidUtil {
private static DataSource dataSource;
static {
try {
//1. 创建Properties对象
Properties properties = new Properties();
//2. 将配置文件转换成字节输入流
InputStream is = DruidUtil.class.getClassLoader().getResourceAsStream("druid.properties");
//3. 使用properties对象加载is
properties.load(is);
//druid底层是使用的工厂设计模式,去加载配置文件,创建DruidDataSource对象
dataSource = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static DataSource getDataSource(){
return dataSource;
}
}
EncodingFilter:
package com.DJL.web.filter;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebFilter("/*")
public class EncodingFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
//req就是服务器创建的请求对象,resp就是服务器创建的响应对象
//先将req和resp对象进行强转
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
//使用request和response对象进行解决乱码的操作
request.setCharacterEncoding("UTF-8");
if (!request.getRequestURI().contains(".css")) {
response.setContentType("text/html;charset=UTF-8");
}
chain.doFilter(request, response);
}
@Override
public void init(FilterConfig config) throws ServletException {
}
}
项目完整代码压缩包(百度网盘自取):
链接:项目
提取码:lzdj