Web功能实现:
案例需求:
1.展示全部
2.根据品种查询,(下拉列表框选)
3.Ajax验证是否可以录入
4.添加功能
数据库脚本
CREATE DATABASE /*!32312 IF NOT EXISTS*/`test` /*!40100 DEFAULT CHARACTER SET latin1 */;
USE `test`;
/*Table structure for table `pet` */
DROP TABLE IF EXISTS `pet`;
CREATE TABLE `pet` (
`petId` int(11) NOT NULL AUTO_INCREMENT,
`petName` varchar(20) NOT NULL,
`petBreed` varchar(20) NOT NULL,
`petSex` varchar(20) NOT NULL,
`birthday` datetime NOT NULL,
`desc` varchar(20) DEFAULT NULL,
PRIMARY KEY (`petId`)
) ENGINE=InnoDB AUTO_INCREMENT=172 DEFAULT CHARSET=utf8;
insert into `pet`(`petId`,`petName`,`petBreed`,`petSex`,`birthday`,`desc`) values (152,'飞飞','鸟','雄','2017-08-15 00:00:00','这是一只喜鹊');
Pojo层更具数据库的数据写private..+get/set方法:
接下来写接口写实现,
01:Dao层:
001:PetDao
public interface PetDao {
List<Pet> getAll();
int addPet(Pet pet);
int selectPetByName(String name);
List<Pet> selectPetByBreed(String breed);
}
002:PetDaoImpl
public class PetDaoImpl extends BaseDao implements PetDao {
@Override
public List<Pet> getAll() {
String sql = "select * from pet";
ResultSet resultSet = executeQuery(sql,null);
List<Pet> petList = new ArrayList<>();
try {
while (resultSet.next()){
Pet pet = new Pet();
pet.setPetId(resultSet.getInt("petId"));
pet.setPetName(resultSet.getString("petName"));
pet.setPetBreed(resultSet.getString("petBreed"));
pet.setPetSex(resultSet.getString("petSex"));
pet.setBirthday(resultSet.getDate("birthday"));
pet.setDesc(resultSet.getString("desc"));
petList.add(pet);
}
}catch (Exception e){
e.printStackTrace();
}
return petList;
}
@Override
public int addPet(Pet pet) {
String sql = "insert into `pet`(`petName`,`petBreed`,`petSex`,`birthday`,`desc`) values (?,?,?,?,?)";
Object[] objects = {pet.getPetName(),pet.getPetBreed(),pet.getPetSex(),pet.getBirthday(),pet.getDesc()};
return executeUpdate(sql,objects);
}
@Override
public int selectPetByName(String name) {
String sql = "select count(1) as c from pet where petName=?";
Object[] objects = {name};
ResultSet resultSet = executeQuery(sql,objects);
try {
if (resultSet.next()){
return resultSet.getInt("c");
}
}catch (Exception e){
e.printStackTrace();
}
return 0;
}
@Override
public List<Pet> selectPetByBreed(String breed) {
String sql = "select * from pet where petBreed = ?";
Object[] objects = {breed};
ResultSet resultSet = executeQuery(sql,objects);
List<Pet> petList = new ArrayList<>();
try {
while (resultSet.next()){
Pet pet = new Pet();
pet.setPetId(resultSet.getInt("petId"));
pet.setPetName(resultSet.getString("petName"));
pet.setPetBreed(resultSet.getString("petBreed"));
pet.setPetSex(resultSet.getString("petSex"));
pet.setBirthday(resultSet.getDate("birthday"));
pet.setDesc(resultSet.getString("desc"));
petList.add(pet);
}
}catch (Exception e){
e.printStackTrace();
}
return petList;
}
}
Service层:
001:PetService
public interface PetService {
List<Pet> getAll();
boolean addPet(Pet pet);
boolean selectPetByName(String name);
List<Pet> selectPetByBreed(String breed);
}
002:PetServiceImpl
public class PetServiceImpl implements PetService {
PetDao petDao = new PetDaoImpl();
@Override
public List<Pet> getAll() {
return petDao.getAll();
}
@Override
public boolean addPet(Pet pet) {
return petDao.addPet(pet) > 0;
}
@Override
public boolean selectPetByName(String name) {
return petDao.selectPetByName(name) > 0;
}
@Override
public List<Pet> selectPetByBreed(String breed) {
return petDao.selectPetByBreed(breed);
}
}
Servlet层:
@WebServlet("/PetServlet")
public class PetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
String path = req.getParameter("path");
HttpSession session = req.getSession();
PetService petService = new PetServiceImpl();
if (path == null){
List<Pet> petList = petService.getAll();
session.setAttribute("petList",petList);
resp.sendRedirect("show.jsp");
}else if (path.equals("breed")){
List<Pet> petList = new ArrayList<>();
String breed = req.getParameter("breed");
if (breed.equals("0")){
petList = petService.getAll();
}else {
petList = petService.selectPetByBreed(breed);
}
session.setAttribute("petList",petList);
resp.sendRedirect("show.jsp");
}else if (path.equals("check")){
String name = req.getParameter("name");
System.out.println(name);
boolean value = petService.selectPetByName(name);
System.out.println(value);
PrintWriter printWriter = resp.getWriter();
printWriter.print(value);
printWriter.flush();
printWriter.close();
}else if(path.equals("add")){
String petName = req.getParameter("petName");
String petBreed = req.getParameter("petBreed");
String petSex = req.getParameter("petSex");
String birthday = req.getParameter("birthday");
String petDesc = req.getParameter("desc");
System.out.println(petName+" "+petBreed+" "+petSex+" "+birthday+" "+petDesc);
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date birthdayDate = null;
try {
birthdayDate = simpleDateFormat.parse(birthday);
} catch (ParseException e) {
e.printStackTrace();
}
Pet pet = new Pet();
pet.setPetName(petName);
pet.setPetBreed(petBreed);
pet.setPetSex(petSex);
pet.setDesc(petDesc);
pet.setBirthday(birthdayDate);
boolean flag = petService.addPet(pet);
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
if (flag){
resp.getWriter().print("<script type='text/javascript'>alert('添加成功!'); window.location='PetServlet'</script>");
}else {
resp.getWriter().print("<script type='text/javascript'>alert('添加失败!'); window.location='PetServlet'</script>");
}
}
}
}
页面show.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery-3.6.0.min.js"></script>
</head>
<body>
<form action="PetServlet?path=breed" method="post">
<select name="breed">
<option value="0">请选择</option>
<option value="猫">猫</option>
<option value="狗">狗</option>
<option value="鸟">鸟</option>
<option value="老鼠">老鼠</option>
<option value="龙">龙</option>
</select>
<input type="submit" value="搜索">
</form>
<a href="add.jsp">新增宠物</a>
<table border="1">
<tr>
<th colspan="6">宠物信息</th>
</tr>
<tr>
<td>编号</td>
<td>昵称</td>
<td>品种</td>
<td>性别</td>
<td>出生日期</td>
<td>备注</td>
</tr>
<c:forEach var="pet" items="${petList}">
<tr>
<td>${pet.petId}</td>
<td>${pet.petName}</td>
<td>${pet.petBreed}</td>
<td>${pet.petSex}</td>
<td>${pet.birthday}</td>
<td>${pet.desc}</td>
</tr>
</c:forEach>
</table>
<script>
$("#tr:odd").css("background","red");
$("#tr:even").css("background","green");
</script>
</body>
</html>
页面add.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery-3.6.0.min.js"></script>
</head>
<body>
<form action="PetServlet?path=add" method="post">
<table border="1">
<tr>
<th colspan="2">添加宠物信息</th>
</tr>
<tr>
<td>昵称</td>
<td><input id="name" type="text" name="petName" onblur="check()"><span id="msg"></span></td>
</tr>
<tr>
<td>品种</td>
<td>
<select name="petBreed">
<option value="0">请选择</option>
<option value="猫">猫</option>
<option value="狗">狗</option>
<option value="鸟">鸟</option>
<option value="老鼠">老鼠</option>
<option value="龙">龙</option>
</select>
</td>
</tr>
<tr>
<td>性别</td>
<td>
<input type="radio" value="雄" name="petSex">雄
<input type="radio" value="雌" name="petSex">雌
</td>
</tr>
<tr>
<td>生日</td>
<td><input type="text" name = "birthday"></td>
</tr>
<tr>
<td>备注</td>
<td><textarea name="desc"></textarea></td>
</tr>
<tr>
<td><input type="submit" value="添加"></td>
</tr>
</table>
</form>
<script>
function check() {
var name = $("#name").val();
alert(name);
$.post("PetServlet","path=check&name="+name,function (data) {
if (data == "true"){
$("#msg").css("color","red");
$("#msg").html("昵称已存在");
}else {
$("#msg").css("color","green");
$("#msg").html("昵称可以使用");
}
},"text");
}
</script>
</body>
</html>