成品展示:
image.png
用到的技术:
Java+JSP+Mysql+Servlet+JDBC+JSTL+EL表达式+jQuery+Json
层次结构:
image.pngdao层:数据访问层
entity层:实体类层
service层:业务逻辑层
servlet层:MVC结构中的控制层
每层结构:
image.pngdao层:
BaseDao类:BaseDAO一般是提供从数据库 增加、删除、修改记录、查询所有记录、查询符合某个条件记录、取得某条记录等方法的底层数据操作自定义类。
petDao接口:制定增删改查的标准。
petDaoimpl类:petDao接口的实现类,实现增删改查的方法。
entity层:
Pet类:pet实体类。
service层:
petservice接口:制定增删改查的业务逻辑标准。
petserviceimpl类:petservice接口的实现类,实现增删改查的业务逻辑。
servlet层:
petServlet类:当客户机发送请求至服务器时,服务器将请求信息转发给Servlet,Servlet处理请求并生成响应内容并传给Web服务器,然后再由Web服务器将响应返回给客户端。
Web:
js文件夹:存放JavaScript文件。
WEB-INF文件夹:WEB-INF是用来存储服务端配置文件信息和在服务端运行的类文件的,它下面的东西不允许客户端直接访问的。
.jsp文件:用java实现的动态网页。
image.png
代码:
BaseDao类:
package dao;
import java.sql.*;
public class BaseDao {
private String driver="com.mysql.cj.jdbc.Driver";
private String url="jdbc:mysql://localhost:3306/lcz?useUnicode=true&characterEncoding=utf-8";
private String user="root";
private String pwd="root";
protected Connection conn=null;
protected PreparedStatement ps = null;
protected ResultSet rs = null;
public Connection getConnection() {
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,user,pwd);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public void close(Connection conn,PreparedStatement ps,ResultSet rs){
try {
if(rs != null){
rs.close();
}
if (ps != null) {
ps.close();
}
if(conn != null){
conn.close();
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected int executeUpdate(String sql, Object... params){
int result = 0;
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
if(params!=null){
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
}
result = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//�ر�
close(conn, ps, rs);
}
return result;
}
protected ResultSet executeQuery(String sql, Object... params){
try {
conn = getConnection();
ps = conn.prepareStatement(sql);
if(params!=null){
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
}
rs = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
}
petDao接口:
package dao;
import entity.Pet;
import java.util.List;
public interface petDao {
/**
* @return
* 显示全部宠物信息
*/
List<Pet>allPet();
List<Pet>byType(int type);
/**
*添加宠物信息
* @return
*/
boolean addPet(Pet pet);
/**
* @param name
* @return
* 根据姓名判断宠物是否重复
*/
boolean isFlag(String name);
/**
* 根据ID获取宠物信息
* @param id
* @return
*/
Pet getById(int id);
/**
* 修改宠物信息
* @param pet
* @return
*/
boolean update(Pet pet);
/**
* 删除宠物
* @param id
* @return
*/
boolean delete(int id);
}
petDaoimpl类:
package dao.impl;
import dao.BaseDao;
import dao.petDao;
import entity.Pet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class petDaoImpl extends BaseDao implements petDao {
@Override
public List<Pet> allPet() {
List<Pet> list = new ArrayList<Pet>();
String sql = "SELECT * FROM pet";
rs = executeQuery(sql);
try {
while (rs.next()) {
Pet p = new Pet();
p.setId(rs.getInt(1));
p.setName(rs.getString(2));
p.setPetBreed(rs.getInt(3));
p.setSex(rs.getInt(4));
p.setBirthday(rs.getString(5));
list.add(p);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(conn, ps, rs);
}
return list;
}
@Override
public boolean addPet(Pet pet) {
String sql = "INSERT INTO pet VALUES(NULL,?,?,?,?,?)";
int n = super.executeUpdate(sql, pet.getName(), pet.getPetBreed(), pet.getSex(), pet.getBirthday(),
pet.getDescription());
return n > 0 ? true : false;
}
@Override
public boolean isFlag(String name) {
String sql = "SELECT * FROM pet WHERE petname=?";
rs = executeQuery(sql, name);
boolean flag = false;
try {
if (rs.next()) {
flag = true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(conn, ps, rs);
}
return flag;
}
@Override
public List<Pet> byType(int type) {
// TODO Auto-generated method stub
List<Pet> list = new ArrayList<Pet>();
String sql = "SELECT * FROM pet WHERE petBreed=?";
rs = executeQuery(sql, type);
try {
while (rs.next()) {
Pet p = new Pet();
p.setId(rs.getInt(1));
p.setName(rs.getString(2));
p.setPetBreed(rs.getInt(3));
p.setSex(rs.getInt(4));
p.setBirthday(rs.getString(5));
list.add(p);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(conn, ps, rs);
}
return list;
}
@Override
public Pet getById(int id) {
String sql = "SELECT * FROM pet WHERE petId=?";
rs = executeQuery(sql, id);
try {
if (rs.next()) {
Pet p = new Pet();
p.setId(rs.getInt(1));
p.setName(rs.getString(2));
p.setPetBreed(rs.getInt(3));
p.setSex(rs.getInt(4));
p.setBirthday(rs.getString(5));
p.setDescription(rs.getString(6));
return p;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
close(conn, ps, rs);
}
// TODO Auto-generated method stub
return null;
}
@Override
public boolean update(Pet pet) {
// TODO Auto-generated method stub
String sql = "update pet set petName=?,petBreed=?,petSex=?,birthday=?,description=? where petId=?";
int n = super.executeUpdate(sql, pet.getName(), pet.getPetBreed(), pet.getSex(), pet.getBirthday(),
pet.getDescription(), pet.getId());
return n > 0 ? true : false;
}
@Override
public boolean delete(int id) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
String sql = "delete from pet where petId=?";
int n = super.executeUpdate(sql, id);
return n > 0 ? true : false;
}
}
Pet类:
package entity;
public class Pet {
private int id;
private String name;
private int sex;
private int petBreed;
private String birthday;
private String description;
public int getPetBreed() {
return petBreed;
}
public void setPetBreed(int petBreed) {
this.petBreed = petBreed;
}
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 int getSex() {
return sex;
}
public void setSex(int sex) {
this.sex = sex;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Pet(String name, int sex, int petBreed, String birthday, String description) {
super();
this.name = name;
this.sex = sex;
this.petBreed = petBreed;
this.birthday = birthday;
this.description = description;
}
public Pet() {
super();
}
public Pet(int id, String name, int sex, int petBreed, String birthday, String description) {
super();
this.id = id;
this.name = name;
this.sex = sex;
this.petBreed = petBreed;
this.birthday = birthday;
this.description = description;
}
}
petservice接口:
package service;
import entity.Pet;
import java.util.List;
public interface petService {
List<Pet>allPet();
List<Pet>byType(int type);
boolean addPet(Pet pet);
boolean isFlag(String name);
Pet getById(int id);
boolean update(Pet pet);
boolean delete(int id);
}
petserviceimpl类:
package service.impl;
import dao.impl.petDaoImpl;
import dao.petDao;
import entity.Pet;
import service.petService;
import java.util.List;
public class petServiceImpl implements petService {
petDao dao=new petDaoImpl();
@Override
public List<Pet> allPet() {
return dao.allPet();
}
@Override
public boolean addPet(Pet pet) {
return dao.addPet(pet);
}
@Override
public boolean isFlag(String name) {
return dao.isFlag(name);
}
@Override
public List<Pet> byType(int type) {
return dao.byType(type);
}
@Override
public Pet getById(int id) {
return dao.getById(id);
}
@Override
public boolean update(Pet pet) {
return dao.update(pet);
}
@Override
public boolean delete(int id) {
return dao.delete(id);
}
}
petServlet类:
package servlet;
import entity.Pet;
import service.impl.petServiceImpl;
import service.petService;
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.io.PrintWriter;
import java.util.List;
/**
* Servlet implementation class petServlet
*/
@WebServlet("/petServlet")
public class petServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
// 获取temp值
String temp = request.getParameter("temp");
petService service = new petServiceImpl();
PrintWriter out = response.getWriter();
if (temp.equals("getAll")) {
// 查询全部信息
String petBreed = request.getParameter("petBreed");
List<Pet> list = service.allPet();
request.setAttribute("list", list);
request.getRequestDispatcher("main.jsp").forward(request, response);
} else if (temp.equals("bytype")) {
String type = request.getParameter("type");
List<Pet> list = null;
if (type == "") {
list = service.allPet();
} else {
list = service.byType(Integer.parseInt(type));
}
request.setAttribute("list", list);
request.getRequestDispatcher("main.jsp").forward(request, response);
} else if (temp.equals("getname")) {
// 获取昵称
String name = request.getParameter("name");
if (service.isFlag(name)) {
out.print(true);
} else {
out.print(false);
}
} else if (temp.equals("add")) {
// 添加信息
String name = request.getParameter("name");
String type = request.getParameter("type");
String sex = request.getParameter("sex");
String date = request.getParameter("date");
String description = request.getParameter("description");
Pet pet = new Pet(name, Integer.parseInt(sex),Integer.parseInt(type), date, description);
if (service.addPet(pet)) {
out.print("<script>alert('添加成功! ');location.href='petServlet?temp=getAll';</script>");
} else {
out.print("<script>alert('添加失败! ');location.href='add.jsp';</script>");
}
} else if(temp.equals("toUpdate")){
int id = Integer.parseInt(request.getParameter("id"));
Pet pet = service.getById(id);
request.setAttribute("pet", pet);
request.getRequestDispatcher("/update.jsp").forward(request, response);
} else if(temp.equals("update")){
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
int type = Integer.parseInt(request.getParameter("type"));
int sex = Integer.parseInt(request.getParameter("sex"));
String date = request.getParameter("date");
String description = request.getParameter("description");
Pet pet = new Pet(id,name,sex,type,date,description);
if (service.update(pet)) {
out.print("<script>alert('修改成功! ');location.href='petServlet?temp=getAll';</script>");
} else {
out.print("<script>alert('修改失败! ');location.href='petServlet?temp=toUpdate&id="+id+";</script>");
}
}else if(temp.equals("delete")){
int id = Integer.parseInt(request.getParameter("id"));
if (service.delete(id)) {
out.print("<script>alert('删除成功! ');location.href='petServlet?temp=getAll';</script>");
} else {
out.print("<script>alert('删除失败! ');location.href='petServlet?temp=getAll';</script>");
}
}
out.flush();
out.close();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
add页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//获取项目路径
String path = request.getContextPath();
//协议名+主机名+服务器端口号+项目名
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
</style>
</head>
<body>
<h2>宠物新增</h2>
<form action="petServlet?temp=add" method="post">
<p>昵称:<input type="text" name="name" id="name"/> <span id="pname"></span></p>
<p>品种:<select name="type" id="type">
<option value="">请选择</option>
<option value="1">狗</option>
<option value="2">猫</option>
<option value="3">鸟</option>
<option value="4">兔</option>
</select></p>
<p>性别:
<input type="radio" name="sex" value="2">雌
<input type="radio" name="sex" value="1">雄
</p>
<p>出生日期:<input type="text" name="date" id="date"/> yyyy-MM-dd格式</p>
<p>宠物描述:<textarea name="description" id="description" cols="40" rows="4" style="OVERFLOW: hidden"></textarea></p>
<input type="submit" id="btn" value="保存"/>
<input type="button" value="重置" />
</form>
<script src="js/jquery-1.12.4.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function(){
$("#name").blur(function(){
var name = $(this).val();
//发送ajax请求
$.ajax({
url:"petServlet",
data:{"temp":"getname","name":name},
type:"get",
dataType:"json",
success:function(result){
if(result){
alert("昵称已存在");
//禁用提交按钮
$("#btn").attr("disabled",true);
}else{
alert("昵称可用");
//解除提交按钮的禁用
$("#btn").attr("disabled",false);
}
}
});
})
//表单验证
$("form").submit(function(){
if (checkname() && checktype() && checkdate()) {
return true;
}else{
return false;
}
})
function checkname(){
var name=$("#name").val();
if (name=="") {
alert("宠物昵称不能为空")
return false;
}
return true;
}
function checktype(){
var type=$("#type").val();
if (type=="") {
alert("请选择宠物类型")
return false;
}
return true;
}
function checkdate(){
var date=$("#date").val();
if (date=="") {
alert("宠物出生日期不能为空")
return false;
}
var reg = /^(19\d{2}|20[01]\d|2020)-(0?[1-9]|1[0-2])-(0?[1-9]|[1-2]\d|3[0-1])$/;
if(!reg.test(saleStarting)){
alert("宠物出生日期格式不正确");
return false;
}
return true;
}
})
</script>
</body>
</html>
index页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
//获取项目路径
String path = request.getContextPath();
//协议名+主机名+服务器端口号+项目名
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<script src="js/jquery-1.12.4.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function(){
window.location.href="petServlet?temp=getAll";
})
</script>
</body>
</html>
main页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%
//获取项目路径
String path = request.getContextPath();
//协议名+主机名+服务器端口号+项目名
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style>
* {
margin: 0px auto;
text-align: center;
}
p {
text-align:center;
}
</style>
</head>
<body>
<form action="petServlet?temp=bytype" method="post">
<p> 品种
<select name="type">
<option value="">请选择</option>
<option value="1">狗</option>
<option value="2">猫</option>
<option value="3">鸟</option>
<option value="4">兔</option>
</select> <input type="submit" value="查询" />
<a href="add.jsp">新增宠物</a>
</p>
</form>
<table border="1" width="700px" style="text-align: center;">
<tr>
<th>宠物昵称</th>
<th>种类</th>
<th>出生日期</th>
<th>性别</th>
<th>操作</th>
</tr>
<c:forEach items="${list }" var="p">
<tr>
<td>${p.name}</td>
<td>
<c:choose>
<c:when test="${p.petBreed==1 }">狗</c:when>
<c:when test="${p.petBreed==2 }">猫</c:when>
<c:when test="${p.petBreed==3 }">鸟</c:when>
<c:otherwise>
兔
</c:otherwise>
</c:choose>
</td>
<td> ${fn:substring(p.birthday, 0, 10)}</td>
<td>
<c:if test="${p.sex eq 1}">雄</c:if>
<c:if test="${p.sex eq 2}">雌</c:if>
</td>
<td>
<a href="petServlet?temp=toUpdate&id=${p.id }">编辑</a>
<a href="petServlet?temp=delete&id=${p.id }" style="color:red">删除</a>
</td>
</tr>
</c:forEach>
</table>
<script src="js/jquery-1.12.4.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function() {
$("table tr:even").css("background", "#9ECEF8");
$("table tr:first").css("background", "darkgrey");
})
</script>
</body>
</body>
</html>
update页面:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%
//获取项目路径
String path = request.getContextPath();
//协议名+主机名+服务器端口号+项目名
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
<style type="text/css">
</style>
</head>
<body>
<h2>宠物编辑</h2>
<form action="petServlet?temp=update" method="post">
<input type="hidden" id="id" name="id" value="${pet.id }"}/>
<p>昵称:<input type="text" name="name" id="name" value="${pet.name}" /> <span id="pname"></span></p>
<p>品种:<select name="type" id="type">
<option value="">请选择</option>
<option value="1" <c:if test='${pet.petBreed == 1}'>selected</c:if>>狗</option>
<option value="2" <c:if test='${pet.petBreed == 2}'>selected</c:if>>猫</option>
<option value="3" <c:if test='${pet.petBreed == 3}'>selected</c:if>>鸟</option>
<option value="4" <c:if test='${pet.petBreed == 4}'>selected</c:if>>兔</option>
</select></p>
<p>性别:
<input type="radio" name="sex" value="2" <c:if test='${pet.sex == 2}'>checked</c:if>>雌
<input type="radio" name="sex" value="1" <c:if test='${pet.sex == 1}'>checked</c:if>>雄
</p>
<p>出生日期:<input type="text" name="date" id="date" value="${pet.birthday}" /> yyyy-MM-dd格式</p>
<p>宠物描述:<textarea name="description" id="description" cols="40" rows="4" style="OVERFLOW: hidden">${pet.description }</textarea></p>
<input type="submit" id="btn" value="保存"/>
<input type="button" value="重置" />
</form>
<script src="js/jquery-1.12.4.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(function(){
//表单验证
$("form").submit(function(){
if (checkname() && checktype() && checkdate()) {
return true;
}else{
return false;
}
})
function checkname(){
var name=$("#name").val();
if (name=="") {
alert("宠物昵称不能为空")
return false;
}
return true;
}
function checktype(){
var type=$("#type").val();
if (type=="") {
alert("请选择宠物类型")
return false;
}
return true;
}
function checkdate(){
var date=$("#date").val();
if (date=="") {
alert("宠物出生日期不能为空")
return false;
}
var reg = /^(19\d{2}|20[01]\d|2020)-(0?[1-9]|1[0-2])-(0?[1-9]|[1-2]\d|3[0-1])$/;
if(!reg.test(saleStarting)){
alert("宠物出生日期格式不正确");
return false;
}
return true;
}
})
</script>
</body>
</html>
数据库:
image.png
SET NAMES utf8mb4;
SET FOREIGN_KEY_CHECKS = 0;
-- ----------------------------
-- Table structure for pet
-- ----------------------------
DROP TABLE IF EXISTS `pet`;
CREATE TABLE `pet` (
`petId` int(20) NOT NULL AUTO_INCREMENT COMMENT '宠物ID',
`petName` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL COMMENT '宠物名称',
`petBreed` int(11) NOT NULL COMMENT '宠物种类:1狗,2猫,3鸟,4兔',
`petSex` int(11) NOT NULL COMMENT '宠物性别',
`birthday` date NOT NULL COMMENT '生日',
`description` varchar(200) CHARACTER SET utf8 COLLATE utf8_general_ci NULL DEFAULT NULL COMMENT '描述',
PRIMARY KEY (`petId`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 8 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
-- ----------------------------
-- Records of pet
-- ----------------------------
INSERT INTO `pet` VALUES (1, '小白', 1, 2, '2020-11-02', '');
INSERT INTO `pet` VALUES (2, '小毛', 2, 2, '2020-11-01', '');
INSERT INTO `pet` VALUES (3, '鹦鹉', 3, 1, '2020-11-01', '');
INSERT INTO `pet` VALUES (4, '小黄', 1, 2, '2020-11-01', '');
INSERT INTO `pet` VALUES (5, '小黑', 1, 1, '2020-11-01', '');
INSERT INTO `pet` VALUES (6, '啧啧', 4, 1, '2020-11-01', '');
INSERT INTO `pet` VALUES (8, '毛毛', 4, 1, '2020-01-01', '');
SET FOREIGN_KEY_CHECKS = 1;
网友评论