jsp实现MVC架构
从以下列举的四个数据库中,任选其一,或者自行定义其他数据库,每个数据库中包含一张表,数据库名、表名、列名、列数据类型自行定义(提示:主键可以设为自增列):
1) 学生数据库:存储的信息包括学生学号、姓名、性别、生日等。
2) 商品数据库:存储的信息包括商品ID、商品名称、商品数量、生产厂家等。
3) 客户数据库:存储的信息包括客户ID、客户姓名、客户地址、手机号码等。
4) 车辆数据库:存储的信息包括汽车ID、品牌、颜色、车主姓名等。
开发一个数据库管理系统需要完成对以上数据库表中的记录的基本的查看、增加、修改和删除功能。以数据库表Book为例,参考系统架构如图1所示:
各个文件功能如下:
1) Dao类:作为数据访问层(持久层)直接访问数据库,包括构造方法(连接数据库),executeQuery方法(执行查询操作,返回ResultSet对象),executeUpdate方法(执行更新操作,返回int数据),close方法(关闭语句对象和连接)。
2) Model类:针对数据库表建立一个对应的模型,包括对应该表各个列的多个属性,这些属性的getter和setter访问器,以及getAll类方法(调用Dao类的方法获取该表所有记录,返回ArrayList对象),getById类方法(调用Dao类的方法获取指定Id的某一条记录,返回Model对象),update类方法(调用Dao类的方法更新一条记录,返回int数据),delete类方法(调用Dao类的方法删除一条记录,返回int数据),add类方法(调用Dao类的方法增加一条数据,返回int数据)。
3) Controller控制器:拦截后缀为.do的请求,对请求进行处理,并转入相应的视图层的文件。包含以下转向功能:
a) index.do:调用Model类提供的getAll方法,得到ArrayList对象,将该对象作为request属性传递给index.jsp进行显示;
b) addview.do:转到add.html显示新增图书页面;
c) add.do:接收add.html发送过来的新增图书的信息,构建一个Model对象,并调用Model提供的add方法插入数据库,根据返回值转到success.html或failure.html显示结果;
d) edit.do:接收index.jsp发送过来的编辑某一Model的请求,调用Model提供的getById方法构建一个Model对象,并转到edit.jsp进行显示;
e) update.do:接收edit.jsp发送过来的保存某一Model的请求,调用Model提供的update方法保存到数据库中,根据返回值转到success.html或failure.html显示结果;
f) delete.do:接收edit.jsp发送过来的删除某一Model的请求,调用Model提供的delete方法保存到数据库中,根据返回值转到success.html或failure.html显示结果;
4) index.jsp:视图层文件,接收Controller发送过来的ArrayList<Model>对象,并进行显示,提供新建超链接到addview.do,修改超链接到edit.do,删除超链接到delete.do。
5) edit.jsp:视图层文件,接收Controller发送过来的Model对象,创建表单,提供用户修改页面,并进行显示原有数据。用户修改后提交到update.do。
6) add.html:视图层文件,创建表单,提供新增图书页面,用户录入数据后提交到add.do。
7) success.html:显示用户操作成功页面,提供超链接到index.do。
8) failure.html:显示用户操作失败页面,提供超链接到index.do。
完成基本功能后,可以从以下方面对系统进行改进:
1) 对于客户端增加和修改信息页面,使用JavaScript、Jquery、Vue等技术进行必要的数据的非空验证;
2) 自行添加一些CSS,使得页面和字体更加美观;
3) 使用AJAX技术,减少页面之间的跳转,提高界面友好性。
实验步骤
1) 打开MySQL,新建一个数据库。
Create database car_db
2) 新建一个数据库表。
create table cars
(
id int auto_increment
primary key,
model varchar(50) null,
brand varchar(50) null,
price double null
);
3) 在表中增加若干记录,作为初始数据。
4) 打开Eclipse软件,新建一个名为Lab04的Web项目,并设置其部署程序为Tomcat。
5)
在Lab04中添加文件,编写代码。
1) CarController文件代码
package com.example.web04.controller;
import com.example.web04.model.Car;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.ArrayList;
public class CarController extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
response.setCharacterEncoding("UTF-8");
String action = request.getServletPath();
switch (action) {
case "/index.do":
index(request, response);
break;
case "/addview.do":
addView(request, response);
break;
case "/add.do":
add(request, response);
break;
case "/edit.do":
edit(request, response);
break;
case "/update.do":
update(request, response);
break;
case "/delete.do":
delete(request, response);
break;
}
}
private void index(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ArrayList<Car> list = Car.getAll();
request.setAttribute("carList", list);
request.getRequestDispatcher("index.jsp").forward(request, response);
}
private void addView(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("add.html").forward(request, response);
}
private void add(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Car car = new Car();
car.setModel(request.getParameter("model"));
car.setBrand(request.getParameter("brand"));
car.setPrice(Double.parseDouble(request.getParameter("price")));
int result = car.add();
if (result > 0) {
response.sendRedirect("success.html");
} else {
response.sendRedirect("failure.html");
}
}
private void edit(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
Car car = Car.getById(id);
request.setAttribute("car", car);
request.getRequestDispatcher("edit.jsp").forward(request, response);
}
private void update(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Car car = new Car();
car.setId(Integer.parseInt(request.getParameter("id")));
car.setModel(request.getParameter("model"));
car.setBrand(request.getParameter("brand"));
car.setPrice(Double.parseDouble(request.getParameter("price")));
int result = car.update();
if (result > 0) {
response.sendRedirect("success.html");
} else {
response.sendRedirect("failure.html");
}
}
private void delete(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
Car car = new Car();
car.setId(id);
int result = car.delete();
if (result > 0) {
response.sendRedirect("success.html");
} else {
response.sendRedirect("failure.html");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
2) Car.Dao文件代码
package com.example.web04.dao;
import java.sql.*;
public class CarDao {
private Connection conn;
private PreparedStatement stmt;
private ResultSet rs;
public CarDao() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/car_db", "root", "1234");
} catch (Exception e) {
e.printStackTrace();
}
}
public ResultSet executeQuery(String sql, Object[] params) {
try {
stmt = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
stmt.setObject(i + 1, params[i]);
}
rs = stmt.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
public int executeUpdate(String sql, Object[] params) {
int result = 0;
try {
stmt = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
stmt.setObject(i + 1, params[i]);
}
result = stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return result;
}
public void close() {
try {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
3) Car.java文件代码
package com.example.web04.model;
import com.example.web04.dao.CarDao;
import java.sql.ResultSet;
import java.util.ArrayList;
public class Car {
private int id;
private String model;
private String brand;
private double price;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public String getBrand() {
return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
// Getter and Setter methods
// ...
public static ArrayList<Car> getAll() {
ArrayList<Car> list = new ArrayList<>();
CarDao dao = new CarDao();
ResultSet rs = dao.executeQuery("SELECT * FROM cars", new Object[]{});
try {
while (rs.next()) {
Car car = new Car();
car.setId(rs.getInt("id"));
car.setModel(rs.getString("model"));
car.setBrand(rs.getString("brand"));
car.setPrice(rs.getDouble("price"));
list.add(car);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
dao.close();
}
return list;
}
public static Car getById(int id) {
Car car = null;
CarDao dao = new CarDao();
ResultSet rs = dao.executeQuery("SELECT * FROM cars WHERE id = ?", new Object[]{id});
try {
if (rs.next()) {
car = new Car();
car.setId(rs.getInt("id"));
car.setModel(rs.getString("model"));
car.setBrand(rs.getString("brand"));
car.setPrice(rs.getDouble("price"));
}
} catch (Exception e) {
e.printStackTrace();
} finally {
dao.close();
}
return car;
}
public int add() {
CarDao dao = new CarDao();
int result = dao.executeUpdate("INSERT INTO cars (model, brand, price) VALUES (?, ?, ?)",
new Object[]{this.model, this.brand, this.price});
dao.close();
return result;
}
public int update() {
CarDao dao = new CarDao();
int result = dao.executeUpdate("UPDATE cars SET model = ?, brand = ?, price = ? WHERE id = ?",
new Object[]{this.model, this.brand, this.price, this.id});
dao.close();
return result;
}
public int delete() {
CarDao dao = new CarDao();
int result = dao.executeUpdate("DELETE FROM cars WHERE id = ?", new Object[]{this.id});
dao.close();
return result;
}
}
4) Index.jsp文件代码
<%@ page import="com.example.web04.model.Car" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>车辆管理系统</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<header>
<h1>车辆管理系统</h1>
</header>
<div class="container">
<h2>车辆列表</h2>
<a href="addview.do">新增车辆</a>
<table>
<tr>
<th>ID</th>
<th>型号</th>
<th>品牌</th>
<th>价格</th>
<th>操作</th>
</tr>
<%
ArrayList<Car> carList = (ArrayList<Car>) request.getAttribute("carList");
for (Car car : carList) {
%>
<tr>
<td><%= car.getId() %></td>
<td><%= car.getModel() %></td>
<td><%= car.getBrand() %></td>
<td><%= car.getPrice() %></td>
<td>
<a href="edit.do?id=<%= car.getId() %>">编辑</a> |
<a href="delete.do?id=<%= car.getId() %>">删除</a>
</td>
</tr>
<%
}
%>
</table>
</div>
</body>
</html>
5) Add.html文件代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>新增车辆</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<header>
<h1>新增车辆</h1>
</header>
<div class="container">
<form action="add.do" method="post">
<div>
<label for="model">型号:</label>
<input type="text" id="model" name="model">
</div>
<div>
<label for="brand">品牌:</label>
<input type="text" id="brand" name="brand">
</div>
<div>
<label for="price">价格:</label>
<input type="text" id="price" name="price">
</div>
<input type="submit" value="提交">
</form>
</div>
</body>
</html>
6) Edit.jsp文件代码
<%@ page import="com.example.web04.model.Car" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page pageEncoding="UTF-8" %>
<html>
<head>
<meta charset="UTF-8">
<title>编辑车辆信息</title>
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<header>
<h1>编辑车辆信息</h1>
</header>
<div class="container">
<%
Car car = (Car) request.getAttribute("car");
%>
<form action="update.do" method="post">
<input type="hidden" name="id" value="<%= car.getId() %>">
<div>
<label for="model">型号:</label>
<input type="text" id="model" name="model" value="<%= car.getModel() %>">
</div>
<div>
<label for="brand">品牌:</label>
<input type="text" id="brand" name="brand" value="<%= car.getBrand() %>">
</div>
<div>
<label for="price">价格:</label>
<input type="text" id="price" name="price" value="<%= car.getPrice() %>">
</div>
<input type="submit" value="保存">
</form>
</div>
</body>
</html>
7) Success.html文件代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>操作成功</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<header>
<h1>操作成功</h1>
</header>
<div class="container">
<p>您的操作已成功完成。</p>
<a href="index.do">返回车辆列表</a>
</div>
</body>
</html>
8) Failure.html文件代码
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<title>操作失败</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body>
<header>
<h1>操作失败</h1>
</header>
<div class="container">
<p>抱歉,操作失败,请重试。</p>
<a href="index.do">返回车辆列表</a>
</div>
</body>
</html>
9) Style.css文件代码
body {
font-family: Arial, sans-serif;
background-color: #f4f4f4;
margin: 0;
padding: 0;
}
header {
background-color: #333;
color: white;
padding: 10px 0;
text-align: center;
}
h1 {
margin: 0;
padding: 10px;
}
.container {
width: 80%;
margin: 20px auto;
background: white;
padding: 20px;
box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
}
table {
width: 100%;
border-collapse: collapse;
margin-bottom: 20px;
}
table, th, td {
border: 1px solid #ddd;
}
th, td {
padding: 8px;
text-align: left;
}
th {
background-color: #f2f2f2;
}
a {
color: #333;
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
button, input[type="submit"] {
background-color: #4CAF50;
color: white;
border: none;
padding: 10px 20px;
cursor: pointer;
text-align: center;
}
button:hover, input[type="submit"]:hover {
background-color: #45a049;
}
form {
margin: 0;
}