宠物管理系统项目(纯代码)

这篇博客主要分享了如何使用Java开发一个宠物管理系统,作者强调需要自行导入相关依赖,并鼓励读者点赞、转发和收藏。
摘要由CSDN通过智能技术生成

宠物管理的主页
宠物管理的添加页面

你可能还想了解的:

序号内容地址
1图书管理器项目https://blog.csdn.net/qq_44739706/article/details/109468694
2人事管理系统项目https://blog.csdn.net/qq_44739706/article/details/109459668
3俱乐部会员信息管理系统https://blog.csdn.net/qq_44739706/article/details/109442031
4考勤登记管理系统https://blog.csdn.net/qq_44739706/article/details/109450805
5花卉管理系统https://blog.csdn.net/qq_44739706/article/details/109416241
6理财产品信息管理系统https://blog.csdn.net/qq_44739706/article/details/109408326
7会议室管理系统https://blog.csdn.net/qq_44739706/article/details/109437351
8宠物管理系统项目https://blog.csdn.net/qq_44739706/article/details/104905632
9北京市雨量检测信息管理系统https://blog.csdn.net/qq_44739706/article/details/104619449
10阳光旅行网app中用户下单功能https://blog.csdn.net/qq_44739706/article/details/102592773
create DATABASE petdb;
use petdb;
create table tb_pet(
		petId bigint primary key auto_increment,
		petName varchar(50) not null,	
		petBreed int not null,
		petSex int not null,	
		birthday date not null,
		description varchar(200)
)default charset=utf8;
insert into tb_pet (petName,petBreed,petSex,birthday,description)
value
('豆豆','1','1','2010-02-24','可爱'),
('憨憨','2','2','2011-01-02','调皮'),
('冰冰','3','1','2011-09-09','漂亮'),
('猪猪','4','1','2011-09-08','白色'),
('跳跳','1','1','2011-03-02','柴犬');
select*from tb_pet where petBreed=1;
package org.news.entity;

import java.util.Date;

/**
 * @author k
 * 实体类
 */
public class TbPet {

  private long petId;
    /**
     * 昵称
     */
  private String petName;
    /**
     * 品种
     */
  private long petBreed;
    /**
     * 性别
     */
  private long petSex;
    /**
     * 出生日期
     */
  private Date birthday;
    /**
     * 描述
     */
  private String description;


  public long getPetId() {
    return petId;
  }

  public void setPetId(long petId) {
    this.petId = petId;
  }


  public String getPetName() {
    return petName;
  }

  public void setPetName(String petName) {
    this.petName = petName;
  }


  public long getPetBreed() {
    return petBreed;
  }

  public void setPetBreed(long petBreed) {
    this.petBreed = petBreed;
  }


  public long getPetSex() {
    return petSex;
  }

  public void setPetSex(long petSex) {
    this.petSex = petSex;
  }


  public Date getBirthday() {
    return birthday;
  }

  public void setBirthday(Date birthday) {
    this.birthday = birthday;
  }


  public String getDescription() {
    return description;
  }

  public void setDescription(String description) {
    this.description = description;
  }

}

package org.news.dao;

import org.news.entity.TbPet;

import java.sql.SQLException;
import java.util.List;

/**
 * @author k
 */
public interface PetDao {
    /**
     * 获取所有的宠物信息
     * @param petBreed
     * @return
     * @throws SQLException
     */
    List<TbPet> getAll(long petBreed) throws SQLException;

    /**
     * 宠物添加
     * @param tbPet
     * @return
     */
    int insertPet(TbPet tbPet);

    /**
     * 查询名字
     * @param petName
     * @return
     * @throws SQLException
     */
    TbPet selectByName(String petName) throws SQLException;
}

package org.news.dao;

import java.sql.*;

/**
 * @author k
 */
public class BaseDao {

    protected Connection connection = null;
    protected PreparedStatement preparedStatement = null;
    protected ResultSet resultSet = null;

    protected Connection getConnection() {

        try {

            try {
                Class.forName("com.mysql.jdbc.Driver");
                connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/petdb?useUnicode=true&amp;characterEncoding=utf-8", "root","123456");
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {

            e.printStackTrace();
        }
        return connection;
    }
    // 2、关闭所有资源

    protected void closeAll(Connection connection, PreparedStatement preparedStatement, ResultSet result) {
        if (result != null) {
            try {
                result.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 3、增、删、改通用方法
     * @param sql  SQL语句
     * @param param 数组
     */
    protected int executeUpdate(String sql, Object...param) {

        // 影响行数
        int num = 0;
        connection = this.getConnection();
        try {
            preparedStatement = connection.prepareStatement(sql);
            // 为参数进行赋值
            if (param != null) {
                for (int i = 0; i < param.length; i++) {
                    preparedStatement.setObject(i + 1, param[i]);
                }
            }
            // 执行SQL语句
            num = preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            this.closeAll(connection, preparedStatement, null);
        }
        return num;
    }

    /**
     * 执行查询操作 备注:此方法适用于纯查询使用,若是输入加查询需要另外设计
     *
     * @param sql 语句
     * @return resultSet 返回集合
     */
    public ResultSet executeQuery(String sql,Object...param) {

        connection = this.getConnection();
        try {
            // 发送SQL语句
            preparedStatement = connection.prepareStatement(sql);
            //参数进行赋值
            if (param != null) {
                for (int i = 0; i < param.length; i++) {
                    preparedStatement.setObject(i + 1, param[i]);
                }
            }
            // 返回结果集
            resultSet = preparedStatement.executeQuery();

        } catch (Exception e) {
            // 关闭所有连接
            closeAll(connection, preparedStatement, resultSet);

            System.out.println("发生异常:\n" + e.getMessage());

        }
        return resultSet;
    }
}

package org.news.dao.impl;

import org.news.dao.BaseDao;
import org.news.dao.PetDao;
import org.news.entity.TbPet;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author k
 */
public class PetDaoImpl extends BaseDao implements PetDao {
    /**
     * 查询宠物的方法和根据品种查询的方法合并在一起
     * @param petBreed
     * @return
     * @throws SQLException
     */
    @Override
    public List<TbPet> getAll(long petBreed) throws SQLException {
        connection=super.getConnection();
        String sql="select * from tb_pet";
        StringBuffer sb=new StringBuffer(sql);
        List<TbPet> list=new ArrayList<TbPet>();
        if (petBreed!=0){
            //按照品种查询
            sb.append(" where petBreed=? ");
            preparedStatement=connection.prepareStatement(sb.toString());
            preparedStatement.setLong(1,petBreed);
            resultSet=preparedStatement.executeQuery();
            selectGetAll(list);
        }else{
            //不是按照品种查询
            preparedStatement=connection.prepareStatement(sql);
            resultSet=preparedStatement.executeQuery();
            selectGetAll(list);
        }
        //关闭文档流
        super.closeAll(connection, preparedStatement, resultSet);
        return list;
    }

    private void selectGetAll(List<TbPet> list) throws SQLException {
        TbPet tbPet;
        while (resultSet.next()) {
            tbPet=new TbPet();
            tbPet.setPetId(resultSet.getLong("petId"));
            tbPet.setPetName(resultSet.getString("petName"));
            tbPet.setPetBreed(resultSet.getLong("petBreed"));
            tbPet.setPetSex(resultSet.getLong("petSex"));
            tbPet.setBirthday(resultSet.getDate("birthday"));
            tbPet.setDescription(resultSet.getString("description"));
            list.add(tbPet);
        }
    }

    @Override
    public int insertPet(TbPet tbPet) {
        String sql="insert into tb_pet (petName,petBreed,petSex,birthday,description)value(?,?,?,?,?)";
        int result=this.executeUpdate(sql,tbPet.getPetName()
        ,tbPet.getPetBreed(),tbPet.getPetSex(),tbPet.getBirthday(),tbPet.getDescription());
        return result;
    }

    @Override
    public TbPet selectByName(String petName) throws SQLException {
        connection=super.getConnection();
        String sql="select * from tb_pet where petName=?";
        preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setString(1,petName);
        resultSet=preparedStatement.executeQuery();
        TbPet tbPet=null;
        while(resultSet.next()){
            tbPet=new TbPet();
            tbPet.setPetId(resultSet.getLong("petId"));
        }
        return tbPet;
    }
}

package org.news.service;

import org.news.entity.TbPet;

import java.sql.SQLException;
import java.util.List;

/**
 * @author k
 */
public interface PetService {
    /**
     * 获取所有的宠物信息
     * @param petBreed
     * @return
     * @throws SQLException
     */
    List<TbPet> getAll(long petBreed) throws SQLException;

    /**
     * 宠物添加
     * @param tbPet
     * @return
     */
    int insertPet(TbPet tbPet);

    /**
     * 查询名字
     * @param petName
     * @return
     * @throws SQLException
     */
    TbPet selectByName(String petName) throws SQLException;
}

package org.news.service.impl;

import org.news.dao.PetDao;
import org.news.dao.impl.PetDaoImpl;
import org.news.entity.TbPet;
import org.news.service.PetService;

import java.sql.SQLException;
import java.util.List;

/**
 * @author k
 */
public class PetServiceImpl implements PetService {

    private  static PetDao petDao=new PetDaoImpl();
    @Override
    public List<TbPet> getAll(long petBreed) throws SQLException {
        return petDao.getAll(petBreed);
    }

    @Override
    public int insertPet(TbPet tbPet) {
        return petDao.insertPet(tbPet);
    }

    @Override
    public TbPet selectByName(String petName) throws SQLException {
        return petDao.selectByName(petName);
    }
}

package org.news.servlet;

import com.sun.net.httpserver.HttpContext;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.InetSocketAddress;
import java.util.concurrent.Executor;

/**
 * @author k
 */
public class BaseServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    /**
     * Constructor of the object.
     */
    public BaseServlet() {
        super();
    }


    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) {
        //创建java反射实现调用方法
        //不需要依赖实例化的对象就可以拿到所有类的资源
        try {
            request.setCharacterEncoding("utf-8");
            Class clazz = this.getClass();
            String opr = request.getParameter("opr");
            //this是拿到所有子类对象

            //一开始加载主页的时候没有参数,默认是加载全部显示数据
            if (opr == null) {
                opr = "list";
            }
            //要找的方法的条件
            Method me = clazz.getMethod(opr,
                    HttpServletRequest.class,
                    HttpServletResponse.class);
            //调用method的方法
            me.invoke(this, request, response);

        } catch (IllegalArgumentException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SecurityException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
}
package org.news.servlet;

import org.news.entity.TbPet;
import org.news.service.PetService;
import org.news.service.impl.PetServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author k
 */
@WebServlet("/ListServlet")
public class ListServlet extends BaseServlet{
    private static final long serialVersionUID = 1L;
    private static PetService petService=new PetServiceImpl();

    public void list(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
        List<TbPet> list=null;

        String petBreedString=request.getParameter("petBreed");

        if (petBreedString!=null){
            int petBreed=Integer.parseInt(petBreedString);
            list=petService.getAll(petBreed);
        }else{

            list=petService.getAll(0);
        }
        request.setAttribute("list",list);
        request.getRequestDispatcher("index.jsp").forward(request,response);
    }

    public void selectByName(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException {
        response.setCharacterEncoding("utf-8");
        String petName=request.getParameter("petName");
        TbPet tbPet=petService.selectByName(petName);
        if (tbPet!=null){
            response.getWriter().print(1);
            System.out.println("名字已经存在");
        }else{
            response.getWriter().print(0);
        }

    }

    public void insert(HttpServletRequest request, HttpServletResponse response) throws SQLException, ServletException, IOException, ParseException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out ;
        String contextPath = request.getContextPath();
        String petName=request.getParameter("petName");
        int petBreed=Integer.parseInt(request.getParameter("petBreed"));
        int petSex=Integer.parseInt(request.getParameter("petSex"));
        Date date=new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("birthday"));
        String description=request.getParameter("description");

        TbPet tbPet=new TbPet();
        tbPet.setPetName(petName);
        tbPet.setPetBreed(petBreed);
        tbPet.setPetSex(petSex);
        tbPet.setBirthday(date);
        tbPet.setDescription(description);

        int result=petService.insertPet(tbPet);
        out = response.getWriter();
        if (result == -1) {
            out.print("<script type=\"text/javascript\">");
            out.print("alert(\"没有添加成功!\");");
            out.print("location.href=\"" + contextPath
                    + "/insert.jsp\";");
            out.print("</script>");
        } else if (result == 0) {
            out.print("<script type=\"text/javascript\">");
            out.print("alert(\"没有添加成功!\");");
            out.print("location.href=\"" + contextPath
                    + "/insert.jsp\";");
            out.print("</script>");
        } else {
            out.print("<script type=\"text/javascript\">");
            out.print("alert(\"已经添加成功信息,点击确认返回首页\");");
            out.print("location.href=\"" + contextPath
                    + "/ListServlet?opr=list\";");
            out.print("</script>");
        }
    }




}

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib  uri="http://java.sun.com/jsp/jstl/core"  prefix="c" %>
<html>
  <head>
    <title>宠物信息</title>
      <script type="text/javascript" src="js/jquery-1.12.4.js"></script>
      <style>
          *{
              margin: 0;
              padding: 0;
          }
            div{
                margin: auto;
                text-align: center;
            }
            table{
                margin: auto;
                text-align: center;
            }
          tr:nth-child(2n-1){
              background-color: deepskyblue;
          }
          tr:first-child{
              background-color: gray;
          }
      </style>
  </head>
  <body>
  <script>
      $(function () {
          $('#sel').click(function () {
              var select=document.getElementsByName("petBreed")[0];
              var index=select.selectedIndex;
              window.location.href="ListServlet?opr=list&petBreed="+index;
          })
      })
  </script>
  <div>
  <h4>品种<select name="petBreed">
        <option>--请选择--</option>
        <option></option>
        <option></option>
        <option></option>
        <option></option>
  </select>
    <input type="button" value="查询" id="sel">
      <a href="insert.jsp">新增宠物</a>
  </h4>
  <table border="1">
      <tr>
          <td>宠物昵称</td>
          <td>出生日期</td>
          <td>性别</td>
      </tr>
    <c:forEach var="i" items="${requestScope.list}">
      <tr>
          <td>${i.petName}</td>
          <td>${i.birthday}</td>
          <c:choose>
              <c:when test="${i.petSex==1}">
                  <td></td></c:when>
              <c:when test="${i.petSex==2}">
                  <td></td></c:when>
          </c:choose>
      </tr>
    </c:forEach>
  </table>
  </div>
  </body>
</html>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>新增宠物</title>
    <script type="text/javascript" src="js/jquery-1.12.4.js"></script>
    <style>
        *{
            margin: 0;
            padding:0;
        }
        form{
            margin: auto;
            text-align: left;
        }
    </style>
</head>
<body>
<script>
    $(function () {
        //重置
        $('#reset').click(function () {
            $('[type=text]').val("");
            $('[type=radio]').val("");
            $('#petBreed').val("--请选择--");
        })
        //验证名字是否重复
        $('#petName').blur(function () {
            var petName=$('#petName').val();
            $.ajax({
                url:"ListServlet?opr=selectByName",
                type:"POST",
                data:"petName="+petName,
                dataType:"text",
                success:function (plam) {
                    if (plam==1) {
                        alert("昵称已存在!")
                        $('#petName').val("");
                    }
                },
                error:function () {
                    alert("222,出错了,请联系管理人员!")
                }
            });
        });

        //提交的时候需要非空验证
        $('#sub').click(function () {
            var petName=$('#petName').val();
            var select=document.getElementsByName("petBreed")[0];
            var index=select.selectedIndex;
            var birthday=$('#birthday').val();
            var r=new RegExp(/^(\d{4})-(0\d{1}|1[0-2])-(0\d{1}|[12]\d{1}|3[01])$/);

            if(petName==""||index==0){
                alert("昵称不为空,请选择品种!")
            }else if (!r.test(birthday)) {
                alert("日期格式不正确!")
            }else{
                window.location.href="javascript:document.form.submit()";
            }
        });
    });
</script>
    <form action="ListServlet?opr=insert" name="form" method="post">
        <h3>宠物的基本信息</h3>
        昵称:<input type="text" name="petName" id="petName"><br>
        品种:<select name="petBreed" id="petBreed">
            <option value="0">--请选择--</option>
        <option value="1"></option>
        <option value="2"></option>
        <option value="3"></option>
        <option value="4"></option>
    </select><br>
        性别:<input type="radio" name="petSex" value="1" checked><input type="radio" name="petSex" value="2" ><br>
        出生日期:<input type="text" name="birthday" id="birthday"><span>yyyy-MM-dd</span><br>
        宠物描述:<input type="text" name="description" id="description"><br>
        <input type="button" value="提交" id="sub">
        <input type="button" value="重置" id="reset">
    </form>
</body>
</html>

需要自己导包

<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>

作者留言

原创不易,得到帮助的小伙伴记得点赞,转发,收藏!!!

  • 10
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

天元白手

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值