通过dao设计模式来对汽车管理系统进行增删改查的操作。
本次使用的web服务器为jetty服务器
第一步:依赖配置
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.car</groupId>
<artifactId>car_servlet</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<maven.compiler.source>11</maven.compiler.source>
<maven.compiler.target>11</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.3</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.14</version>
</dependency>
</dependencies>
<build>
<finalName>car</finalName>
<plugins>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.4.11.v20180605</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<httpConnector>
<port>9000</port>
</httpConnector>
<webApp>
<contextPath>/car</contextPath>
</webApp>
</configuration>
</plugin>
</plugins>
</build>
</project>
Dao设计模式,一个javabean,一个dao,一个工具类
action包
AddServlet类
package com.car.action;
import com.car.dao.ICarDao;
import com.car.entity.Car;
import com.car.utils.DaoFactory;
import lombok.SneakyThrows;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class AddServlet extends HttpServlet {
private ICarDao carDao= DaoFactory.getCarDao();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("add.jsp").forward(req,resp);
}
@SneakyThrows
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String CarId1=req.getParameter("CarId");
Long CarId=Long.parseLong(CarId1);
System.out.println(CarId);
String CarBrand=req.getParameter("CarBrand");
String CarCard=req.getParameter("CarCard");
String CarColor=req.getParameter("CarColor");
Car car=new Car();
car.setCarId(CarId);
car.setCarBrand(CarBrand);
car.setCarCard(CarCard);
car.setCarColor(CarColor);
Boolean bb=carDao.add(car);
resp.sendRedirect("show.do");
}
}
ModifyServlet
package com.car.action;
import com.car.dao.ICarDao;
import com.car.entity.Car;
import com.car.utils.DaoFactory;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
public class ModifyServlet extends HttpServlet {
private ICarDao carDao= DaoFactory.getCarDao();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String ss=req.getParameter("id");
Long CarId=Long.parseLong(ss);
try {
Car car=carDao.loadById(CarId);
if (Objects.nonNull(car)){
req.setAttribute("car",car);
req.getRequestDispatcher("edit.jsp").forward(req,resp);
}else {
resp.sendRedirect("show.do");
}
} catch (Exception e) {
throw new ServletException(e);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String oldId=req.getParameter("oldId");
System.out.println(oldId);
String CarId1=req.getParameter("CarId");
System.out.println(CarId1);
String CarBrand=req.getParameter("CarBrand");
System.out.println(CarBrand);
String CarCard=req.getParameter("CarCard");
System.out.println(CarCard);
String CarColor=req.getParameter("CarColor");
System.out.println(CarColor);
//==================================================
Car car=new Car();
Long oldCarId=Long.parseLong(oldId);
Long CarId=Long.parseLong(CarId1);
car.setCarId(CarId);
car.setCarBrand(CarBrand);
car.setCarCard(CarCard);
car.setCarColor(CarColor);
try {
boolean res=carDao.updateById(car,oldCarId);
if (res){
resp.sendRedirect("show.do");
}else {
req.setAttribute("car",car);
req.setAttribute("oldCarId",oldCarId);
req.getRequestDispatcher("edit.jsp").forward(req,resp);
}
}catch (Exception e){
throw new ServletException(e);
}
// resp.sendRedirect("show.do");
}
}
RemoveServlet类
package com.car.action;
import com.car.dao.ICarDao;
import com.car.utils.DaoFactory;
import lombok.SneakyThrows;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class RemoveServlet extends HttpServlet {
private ICarDao carDao= DaoFactory.getCarDao();
@Override
@SneakyThrows
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String ss=req.getParameter("id");
Long CarId=Long.parseLong(ss);
boolean bb=carDao.delete(CarId);
System.out.println(bb?"删除成功":"删除失败");
resp.sendRedirect("show.do");
}
}
ShowServlet
package com.car.action;
import com.car.dao.ICarDao;
import com.car.domain.PageBean;
import com.car.entity.Car;
import com.car.utils.DaoFactory;
import lombok.SneakyThrows;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
public class ShowServlet extends HttpServlet {
private ICarDao carDao= DaoFactory.getCarDao();
private int rows=15;
@Override
public void init() throws ServletException {
String ss=getServletConfig().getInitParameter("rows");
try {
rows=Integer.parseInt(ss.trim());
}catch (Exception e){
rows=2;
}
}
@SneakyThrows
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PageBean pages=new PageBean();
Car car=new Car();
pages.setRowsPerPage(rows);
String spage=req.getParameter("page");
int page=0;
try {
page=Integer.parseInt(spage.trim());
}catch (Exception e){
page=1;
}
pages.setPageNum(page);
List<Car> carList=carDao.selectByExample(car, pages);
// System.out.println(carList);
req.setAttribute("carList",carList);
req.setAttribute("pages",pages);
req.getRequestDispatcher("show.jsp").forward(req,resp);
}
}
Dao包
CaoDaoImpl实现类
package com.car.dao;
import com.car.domain.PageBean;
import com.car.entity.Car;
import com.car.utils.ConnectionManagers;
import com.car.utils.StringUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
public class CarDaoImpl implements ICarDao{
/**
*
* @param example:查询相关条件
* @param pages:分页相关参数
* @return:返回满足条件的汽车信息
* @throws Exception
*/
@Override
public List<Car> selectByExample(Car example, PageBean pages) throws Exception {
Connection connection=null;
ResultSet resultSet=null;
StringBuilder sb1=new StringBuilder("select * from tb_car where 1=1 ");
List<Car> res=new ArrayList<>();
try {
connection= ConnectionManagers.getConnection();
if (Objects.nonNull(pages)&&pages.getRowsPerPage()>0){
if (pages.getPageNum()<1)
pages.setPageNum(1);
if (pages.getMaxPage()<1){
int rowsNum=0;//设置总行数为0
String ss=" select count(1) from tb_car where 1=1";
resultSet=ConnectionManagers.executeQuerry(connection,ss,null);
if (resultSet.next())
rowsNum=resultSet.getInt(1);
if (rowsNum<1)
return res;
int maxPage=rowsNum/pages.getRowsPerPage();
if (rowsNum%pages.getRowsPerPage()!=0)
maxPage++;
pages.setMaxPage(maxPage);//设置最大页码值
pages.setRowsNum(rowsNum);//设置总行数
}
if (pages.getPageNum()> pages.getMaxPage())
pages.setPageNum(pages.getMaxPage());
int begin=(pages.getPageNum()-1)* pages.getRowsPerPage();
sb1.append(" limit ").append(begin).append(",").append(pages.getRowsPerPage());
}
resultSet=ConnectionManagers.executeQuerry(connection,sb1.toString(),null);
while (resultSet.next()){
Car c=new Car();
c.setCarId(resultSet.getLong("CarId"));
c.setCarBrand(resultSet.getString("CarBrand"));
c.setCarCard(resultSet.getString("CarCard"));
c.setCarColor(resultSet.getString("CarColor"));
res.add(c);
// System.out.println(res);
}
}finally {
ConnectionManagers.close(resultSet,null,connection);
}
return res;
}
@Override
public Car loadById(Long CarId) throws Exception {
if (Objects.isNull(CarId)) {
throw new RuntimeException("参数不允许为空");
}
Connection connection=null;
ResultSet resultSet=null;
Car car=new Car();
String sql="select * from tb_car where CarId=?";
try {
connection=ConnectionManagers.getConnection();
resultSet=ConnectionManagers.executeQuerry(connection,sql,CarId);
while (resultSet.next()){
car.setCarId(resultSet.getLong("CarId"));
car.setCarBrand(resultSet.getString("CarBrand"));
car.setCarCard(resultSet.getString("CarCard"));
car.setCarColor(resultSet.getString("CarColor"));
}
}finally {
ConnectionManagers.close(resultSet,null,connection);
}
return car;
}
@Override
public boolean updateById(Car example, Long oldCarId) throws Exception {
if (Objects.isNull(example)||Objects.isNull(oldCarId))
throw new RuntimeException("参数不能为空");
StringBuilder sb=new StringBuilder("update tb_car set CarId=?");
List<Object>params=new ArrayList<>();
params.add(example.getCarId());//啥意思
if (StringUtils.nonBlack(example.getCarBrand())){
sb.append(" ,CarBrand=? ");
params.add(example.getCarBrand());
}
if (example.getCarCard()!=null){
sb.append(" ,CarCard=? ");
params.add(example.getCarCard());
}
if (example.getCarColor()!=null){
sb.append(" ,CarColor=? ");
params.add(example.getCarColor());
}
sb.append(" where CarId=?");
params.add(oldCarId);
int res=0;
Connection connection=null;
try {
connection=ConnectionManagers.getConnection();
res=ConnectionManagers.executeUpdate(connection,sb.toString(),params.toArray());
}finally {
ConnectionManagers.close(null,null,connection);
}
return res>0;
}
@Override
public boolean delete(Long CarId) throws Exception {
int res=0;
String sql="delete from tb_car where CarId=?";
Connection connection=null;
try {
connection=ConnectionManagers.getConnection();
res=ConnectionManagers.executeUpdate(connection,sql,CarId);
}finally {
ConnectionManagers.close(null,null,connection);
}
return res>0;
}
@Override
public boolean add(Car car) throws Exception {
int res=0;
Connection connection=null;
String ss="insert into tb_car values (?,?,?,?)";
try {
connection=ConnectionManagers.getConnection();
res=ConnectionManagers.executeUpdate(connection,ss,car.getCarId(),car.getCarBrand(),car.getCarCard(),car.getCarColor());
}finally {
ConnectionManagers.close(null,null,connection);
}
return res>0;
}
}
ICarDao接口
package com.car.dao;
import com.car.domain.PageBean;
import com.car.entity.Car;
import java.util.List;
public interface ICarDao {
List<Car> selectByExample(Car example, PageBean pages) throws Exception;//查询
Car loadById(Long CarId)throws Exception;
boolean updateById(Car example, Long oldCarId) throws Exception;//修改
boolean delete(Long CarId)throws Exception;//删除
boolean add(Car car)throws Exception;//增加
}
doMain包
Constants
package com.car.domain;
public class Constants {
public static final boolean debug=true;
}
PageBean
做查询必做分页
package com.car.domain;
import lombok.Data;
import java.io.Serializable;
@Data
public class PageBean implements Serializable {
private int pageNum;//当前页码值
private int rowsNum;//总行数
private int rowsPerPage=15;//每页行数
private int maxPage;//最大页码值
}
entity
Car类
package com.car.entity;
import lombok.Data;
import java.io.Serializable;
@Data
public class Car implements Serializable {
private Long CarId;
private String CarBrand;
private String CarCard;
private String CarColor;
}
工具类
ckage com.car.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.car.domain.Constants;
import lombok.SneakyThrows;
import javax.sql.DataSource;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
public class ConnectionManagers {
private static DataSource dataSource;
static {
try {
Properties ps=new Properties();
InputStream is=Thread.currentThread().getContextClassLoader().getResourceAsStream("jdbc.properties");
ps.load(is);
dataSource= DruidDataSourceFactory.createDataSource(ps);
}catch (Exception e){
if (Constants.debug){
e.printStackTrace();
}
throw new RuntimeException(e);
}
}
@SneakyThrows
public static Connection getConnection(){
return dataSource.getConnection();
}
@SneakyThrows
public static PreparedStatement createPreparedStatement(Connection connection, String sql, Object...params){
PreparedStatement preparedStatement=connection.prepareStatement(sql);
if (params!=null && params.length>0){
for (int i=0;i<params.length;i++){
preparedStatement.setObject(i+1,params[i]);
}
}
return preparedStatement;
}
@SneakyThrows
public static int executeUpdate(Connection connection,String sql,Object...params){
PreparedStatement preparedStatement=createPreparedStatement(connection,sql,params);
return preparedStatement.executeUpdate();
}
@SneakyThrows
public static ResultSet executeQuerry(Connection connection, String sql, Object...params){
PreparedStatement preparedStatement=createPreparedStatement(connection,sql,params);
return preparedStatement.executeQuery();
}
@SneakyThrows
public static void close(ResultSet resultSet, PreparedStatement preparedStatement,Connection connection){
try {
if (resultSet!=null)
resultSet.close();
}finally {
try {
if (preparedStatement!=null)
preparedStatement.close();
}finally {
if (connection!=null)
connection.close();
}
}
}
}
package com.car.utils;
import com.car.dao.CarDaoImpl;
import com.car.dao.ICarDao;
public class DaoFactory {
public static ICarDao getCarDao(){
return new CarDaoImpl();
}
}
package com.car.utils;
public class StringUtils {
public static boolean isBlank(String value){return value==null||value.trim().length()<0;}//判定存在字符串
public static boolean nonBlack(String value){return !isBlank(value);}//判定不存在字符串
}
配置文件
druid.driverClassName=com.mysql.cj.jdbc.Driver
url=jdbc:mysql:///test?serverTimezone=Asia/Shanghai
username=root
password=123456
webapp
web.xml配置文件
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>show</servlet-name>
<servlet-class>com.car.action.ShowServlet</servlet-class>
<init-param>
<param-name>rows</param-name>
<param-value>2</param-value>
</init-param>
</servlet>
<servlet>
<servlet-name>remove</servlet-name>
<servlet-class>com.car.action.RemoveServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>add</servlet-name>
<servlet-class>com.car.action.AddServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>modify</servlet-name>
<servlet-class>com.car.action.ModifyServlet</servlet-class>
</servlet>
<!--===========================================-->
<servlet-mapping>
<servlet-name>show</servlet-name>
<url-pattern>/show.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>remove</servlet-name>
<url-pattern>/remove.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>add</servlet-name>
<url-pattern>/add.do</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>modify</servlet-name>
<url-pattern>/modify.do</url-pattern>
</servlet-mapping>
</web-app>
add.jsp
<%--
Created by IntelliJ IDEA.
User: 11868
Date: 2022/11/12
Time: 18:15
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="add.do" name="form1" method="post" onSubmit="return isSubmit();">
<table width="400" align="center">
<caption>车辆添加页面</caption>
<tr>
<td>车辆编号</td>
<td><input type="text" name="CarId" /></td>
</tr>
<tr>
<td>汽车品牌</td>
<td><input type="text" name="CarBrand"/></td>
</tr>
<tr>
<td>汽车牌照</td>
<td><input type="text" name="CarCard"/></td>
</tr>
<tr>
<td>汽车颜色</td>
<td><input type="text" name="CarColor"/></td>
</tr>
<tr>
<td>
<input type="submit" value="确定" />
<input type="reset" value="重置" />
</td>
</tr>
</table>
</form>
</body>
</html>
edit.jsp
<%@ page import="java.util.Objects" %>
<%@ page import="com.car.entity.Car" %><%--
Created by IntelliJ IDEA.
User: 11868
Date: 2022/11/12
Time: 19:19
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="modify.do"method="post">
<%
Object obj=request.getAttribute("car");
if (Objects.nonNull(obj)&&obj instanceof Car){
Car car=(Car)obj;
%>
<table width="400" align="center">
<caption>车辆信息编辑页面</caption>
<input type="hidden" name="oldId" value="<%=request.getAttribute("oldCarId")!=null?request.getAttribute("oldCarId"):car.getCarId()%>">
<tr>
<td>车辆编号</td>
<td><input type="text" name="CarId" value="<%=car.getCarId()%>"/></td>
<td></td>
</tr>
<tr>
<td>汽车品牌</td>
<td><input type="text" name="CarBrand" value="<%=car.getCarBrand()%>"/></td>
<td></td>
</tr>
<tr>
<td>汽车牌照</td>
<td><input type="text" name="CarCard" value="<%=car.getCarCard()%>"/></td>
<td></td>
</tr>
<tr>
<td>汽车颜色</td>
<td><input type="text" name="CarColor" value="<%=car.getCarColor()%>"/></td>
<td></td>
</tr>
<tr>
<td>
<input type="submit" value="确定" />
<input type="reset" value="重置" />
</td>
</tr>
</table>
<%}else{%>
<h3>数据加载出错</h3>
点击<a href="show.do">这里</a>返回显示信息页面
<%}%>
</form>
</body>
</html>
show.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="com.car.entity.Car" %>
<%@ page import="com.car.domain.PageBean" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
%>
<!DOCTYPE html>
<html lang="zh_CN">
<head>
<base href="<%=basePath%>">
<title>My JSP 'show.jsp' starting page</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
</head>
<body>
<table>
<caption>车辆管理系统</caption>
<thead>
<tr>
<td colspan="2">车辆编号</td>
<td colspan="2">车辆品牌</td>
<td colspan="2">车辆牌照</td>
<td colspan="2">车辆颜色</td>
</tr>
</thead>
<tbody>
<%
Object obj=request.getAttribute("carList");
if (obj!=null && obj instanceof List){
List<Car> carList=(List<Car>) obj;
for (Car tmp:carList){
%>
<tr>
<td colspan="2"><%=tmp.getCarId()%></td>
<td colspan="2"><%=tmp.getCarBrand()%></td>
<td colspan="2"><%=tmp.getCarCard()%></td>
<td colspan="2"><%=tmp.getCarColor()%></td>
<th colspan="2">
<input type="button" value="删除" onClick="location.href='remove.do?id=<%=tmp.getCarId()%>'"/>
<input type="button" value="编辑" onClick="location.href='modify.do?id=<%=tmp.getCarId()%>'" /><!--页面跳转-->
</th>
</tr>
<%}}%>
<th colspan="2"><input type="button" value="添加车辆" onClick="location.href='add.do'" /></th>
</tbody>
<tfoot>
<%
Object obj1=request.getAttribute("pages");
if (obj1!=null&& obj1 instanceof PageBean){
PageBean pb=(PageBean) obj1;
%>
<tr>
<td colspan="6">
当前页<%=pb.getPageNum()%>共<%=pb.getMaxPage()%>页;有<%=pb.getRowsNum()%>车
</td>
<td colspan="4">
<%for (int i=1;i<=pb.getMaxPage();i++){%>
[<a href="show.do?page=<%=i%>"><%=i%></a>]
<%}%>
</td>
</tr>
<%}%>
</tfoot>
</table>
</body>
</html>
按照javabean创建数据库,并填入相应数据,便可以使用网页对数据库进行增删改查的操作