使用JSP+servLet实现宠物管理系统,oraC1e11g作为后台数据厍,实现查看宠物和增加宠物
的功能由你实现,如图:
其中宠物包栝:狗、猫、鸟、鼠
具体要求及推荐实现步骤
第一步:创建数据库代码:
create table pet ( petId number(10) not null primary key, --id petName varchar2(50) not null, --昵称 petBread varchar(50) not null, --品种 petSex varchar(10) not null, --性别 birthday date not null, --出生日期 description varchar(400) --描述 ) --序列自增 create sequence pet_squ start with 1 increment by 1 nomaxvalue cache 10; drop table pet --删除宠物表 drop sequence pet_squ --删除序列 --插入数据 insert into pet values (‘1‘,‘aa‘,‘狗‘,‘雄‘,to_date(‘2015-05-26‘,‘yyyy-mm-dd‘),‘聪明的拉布拉多犬‘); insert into pet values (pet_squ.nextval,‘bb‘,‘猫‘,‘雄‘,to_date(‘2015-05-26‘,‘yyyy-mm-dd‘),‘可爱的加菲猫‘); insert into pet values (pet_squ.nextval,‘cc‘,‘鸟‘,‘雄‘,to_date(‘2015-05-26‘,‘yyyy-mm-dd‘),‘活泼的鸟‘); insert into pet values (pet_squ.nextval,‘dd‘,‘鼠‘,‘雄‘,to_date(‘2015-05-26‘,‘yyyy-mm-dd‘),‘可爱的小白鼠‘); insert into pet values (pet_squ.nextval,‘ee‘,‘猫‘,‘雄‘,to_date(‘2015-05-26‘,‘YYYY-MM-dd‘),‘可爱的加菲猫‘); select * from pet --查询所有宠物
第二步:建立宠物实体类entity(pet)
package entity; /** * 宠物实体类 * @author Administrator * */ public class pet { private int petId; //--id private String petName ; //--昵称 private String petBread ;//--品种 private String petSex; //--性别 private String birthday ;//--出生日期 private String description;//--描述 public int getPetId() { return petId; } public void setPetId(int petId) { this.petId = petId; } public String getPetName() { return petName; } public void setPetName(String petName) { this.petName = petName; } public String getPetBread() { return petBread; } public void setPetBread(String petBread) { this.petBread = petBread; } public String getPetSex() { return petSex; } public void setPetSex(String petSex) { this.petSex = petSex; } 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; } }
第三步:建立数据库 帮助类DB(记得导入架包)
package DB; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class JNDI { //数据库名和登入密码 String driver="oracle.jdbc.driver.OracleDriver"; String url="jdbc:oracle:thin:@localhost:1521:ORCL"; String user = "epet"; String pwd = "123456"; //建立数据库连接方法 public Connection getConnection(){ //加载驱动 try { //第一步:加载驱动 Class.forName(driver); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Connection con =null; //获取连接对象 try { con =DriverManager.getConnection(url,user,pwd); //连接数据库 } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return con; } //======释放资源方法======= public void ShiFang(ResultSet rs, Statement st,Connection con){ //如果结果集不为空,则释放成功 ,否则失败 try { if(rs!=null){ rs.close(); }if(st!=null){ st.close(); }if(con!=null){ con.close(); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
第四步:三层架构(数据查询层+业务逻辑层+表示层JSP)
1、创建Biz(业务逻辑层)
package Biz; import java.util.List; import entity.pet; /** * 业务逻辑层 * @author Administrator * */ public interface petBiz { //查询宠物信息 public List<pet> returnList(); //添加宠物信息 public int insertPet(pet pet); //根据宠物类型查询宠物信息 public List<pet> selectPet(String petType); }
package Biz.Impl; import java.util.List; import entity.pet; import Biz.petBiz; import Dao.petDao; import Dao.Impl.petDaoImpl; public class petBizImpl implements petBiz { //实例化数据连接层 petDao pe=new petDaoImpl(); public List<pet> returnList() { return pe.returnList(); } public int insertPet(pet pet) { // TODO Auto-generated method stub return pe.insertPet(pet); } public List<pet> selectPet(String petType) { // TODO Auto-generated method stub return pe.selectPet(petType); } }
2、创建DAO(数据查询层)
package Dao; import java.util.List; import entity.pet; /** * 数据查询层 * @author Administrator * */ public interface petDao { //查询宠物信息 public List<pet> returnList(); //添加宠物信息 public int insertPet(pet pet); //根据宠物类型查询宠物信息 public List<pet> selectPet(String petType); }
package Dao.Impl; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import entity.pet; import DB.JNDI; import Dao.petDao; public class petDaoImpl extends JNDI implements petDao { private Connection cn; private PreparedStatement ps; private ResultSet rs; public List<pet> returnList() { List<pet> li=new ArrayList<pet>(); cn=super.getConnection(); String sql="select * from pet order by petId"; try { ps=cn.prepareStatement(sql); rs=ps.executeQuery(); while(rs.next()){ pet pe=new pet(); pe.setPetId(rs.getInt("petId")); pe.setPetName(rs.getString("petName")); pe.setPetBread(rs.getString("petBread")); pe.setPetSex(rs.getString("petSex")); pe.setBirthday(rs.getString("birthday")); pe.setDescription(rs.getString("description")); li.add(pe); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return li; } public int insertPet(pet pet) { int i=0; cn=super.getConnection(); String sql="insert into pet values (pet_squ.nextval,?,?,?,to_date(?,‘YYYY-MM-dd‘),?)"; try { ps=cn.prepareStatement(sql); ps.setString(1,pet.getPetName() ); ps.setString(2, pet.getPetBread()); ps.setString(3,pet.getPetSex() ); ps.setString(4,pet.getBirthday() ); ps.setString(5,pet.getDescription() ); i=ps.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return i; } public List<pet> selectPet(String petType) { List<pet> li=new ArrayList<pet>(); if(petType.equals("请选择")){ cn=super.getConnection(); String sql="select * from pet order by petId"; try { ps=cn.prepareStatement(sql); rs=ps.executeQuery(); while(rs.next()){ pet pe=new pet(); pe.setPetId(rs.getInt("petId")); pe.setPetName(rs.getString("petName")); pe.setPetBread(rs.getString("petBread")); pe.setPetSex(rs.getString("petSex")); pe.setBirthday(rs.getString("birthday")); pe.setDescription(rs.getString("description")); li.add(pe); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else{ cn=super.getConnection(); String sql="select * from pet where petBread=? order by petId"; try { ps=cn.prepareStatement(sql); ps.setString(1,petType); rs=ps.executeQuery(); while(rs.next()){ pet pe=new pet(); pe.setPetId(rs.getInt("petId")); pe.setPetName(rs.getString("petName")); pe.setPetBread(rs.getString("petBread")); pe.setPetSex(rs.getString("petSex")); pe.setBirthday(rs.getString("birthday")); pe.setDescription(rs.getString("description")); li.add(pe); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return li; } }
第五步:创建实现Servlet的配置(web项目xml配置)和部署
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <!-- 注册 --> <servlet> <servlet-name>selectPet</servlet-name> <servlet-class>servlet.selectPet</servlet-class> </servlet> <!-- 映射 --> <servlet-mapping> <servlet-name>selectPet</servlet-name> <url-pattern>/selectPet</url-pattern> </servlet-mapping> <!-- 注册 --> <servlet> <servlet-name>servletInsert</servlet-name> <servlet-class>servlet.servletInsert</servlet-class> </servlet> <!-- 映射 --> <servlet-mapping> <servlet-name>servletInsert</servlet-name> <url-pattern>/servletInsert</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app>
部署servlet:
package servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import entity.pet; import Biz.petBiz; import Biz.Impl.petBizImpl; public class selectPet extends HttpServlet { /** * Initialization of the servlet. <br> * * @throws ServletException if an error occurs */ public void init() throws ServletException { System.out.println("初始化servlet"); } /** * The doGet method of the servlet. <br> * * This method is called when a form has its tag value method equals to get. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { System.out.println("test_get"); petBiz pet=new petBizImpl(); List<pet> li=pet.returnList(); request.getSession().setAttribute("list", li); response.sendRedirect("index.jsp"); System.out.println("test"); } /** * The doPost method of the servlet. <br> * * This method is called when a form has its tag value method equals to post. * * @param request the request send by the client to the server * @param response the response send by the server to the client * @throws ServletException if an error occurred * @throws IOException if an error occurred */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); String petType=request.getParameter("petType"); String pett=""; if(("").equals(petType)||petType==null){ pett="请选择"; }else{ petType=new String(petType.getBytes("ISO8859-1"),"UTF-8"); pett=petType; } petBiz pet=new petBizImpl(); List<pet> li=pet.selectPet(pett); response.setCharacterEncoding("utf-8"); response.setContentType("text/html;charset=UTF-8"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); request.getSession().setAttribute("list", li); response.sendRedirect("index.jsp"); } /** * Destruction of the servlet. <br> */ public void destroy() { System.out.println("销毁servlet"); } }
配置添加宠物servlect
package servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import Biz.petBiz; import Biz.Impl.petBizImpl; import entity.pet; public class servletInsert extends HttpServlet{ @Override public void init() throws ServletException { // TODO Auto-generated method stub System.out.println("servlet初始化成功"); } @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // TODO Auto-generated method stub System.out.println("Test_Get"); PrintWriter out =response.getWriter(); out.print("tets"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("utf-8"); pet pet=new pet(); pet.setPetName(request.getParameter("petname")); pet.setPetBread(request.getParameter("select")); pet.setPetSex(request.getParameter("radio")); pet.setBirthday(request.getParameter("bornDate")); pet.setDescription(request.getParameter("textarea")); petBiz pb=new petBizImpl(); int i=pb.insertPet(pet); request.setCharacterEncoding("UTF-8"); response.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out =response.getWriter(); if(i>0){ response.sendRedirect("index.jsp"); }else{ response.sendRedirect("insert.jsp"); } } @Override public void destroy() { // TODO Auto-generated method stub System.out.println("销毁servlet"); } }
3、三层架构之表示层(jsp)
<%@page import="entity.pet"%> <%@page import="Biz.Impl.petBizImpl"%> <%@page import="Biz.petBiz"%> <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; List<pet> list=(List)request.getSession().getAttribute("list"); request.setAttribute("pet", list); String []petArray={"请选择","猫","狗","鸟","鼠"}; request.setAttribute("petArray", petArray); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>显示页</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <style type="text/css"> table tr th{width:100px;background:grey} table tr td{width:100px;} </style> <script type="text/javascript"> function petChange(){ var select =document.getElementById("select").value; document.getElementById("form").action="selectPet?petType="+select; document.getElementById("form").method="post" document.getElementById("form").submit(); } </script> </head> <body> <div> <p> <form id="form"> 品种 <select name="select" id="select" > <c:forEach var="petArray" items="${requestScope.petArray }"> <option <c:if test="${petArray}">selected=selected</c:if> value="${petArray }">${petArray }</option> </c:forEach> </select> <input type="submit" value="提交" onclick="petChange()"/> <a href="insert.jsp">添加宠物</a> </form> </p> <table> <tr> <th>宠物昵称</th> <th>出生日期</th> <th>性别</th> </tr> <c:forEach var="pet" items="${requestScope.pet }" varStatus="stauts"> <tr <c:if test="${stauts.index%2==1}">style="background-color:rgb(219,241,212)"</c:if>> <td>${pet.petName } </td> <td>${pet.birthday }</td> <td>${pet.petSex }</td> </tr> </c:forEach> </table> </div> </body> </html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP ‘insert.jsp‘ starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="servletInsert" method="post" onsubmit="return check()"> <table> <tr> <th colspan="2">宠物基本信息</th> </tr> <tr> <td>昵称:</td> <td><input type="text" name="petname" id="petname" /></td> </tr> <tr> <td>品种</td> <td> <select name="select" id="select""> <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="radio" checked="checked"/>雄 <input type="radio" value="雌" name="radio"/>雌 </td> </tr> <tr> <td>出生日期</td> <td><input type="text" name="bornDate" id="bornDate"/> <span id="span"></span></td> </tr> <tr> <td>宠物描述</td> <td> <textarea name="textarea" id="textarea" cols="60" rows="10"> </textarea> </td> </tr> <tr> <td colspan="2" style="text-align:center"> <input type="submit" value="提交"/> <input type="reset" value="重置"/> </td> </tr> </table> </form> <script language="javascript"> function check(){ var petname =document.getElementById("petname").value; var select =document.getElementById("select").value; var bornDate =document.getElementById("bornDate").value; var textarea =document.getElementById("textarea").value; var span =document.getElementById("span"); var reg=/^(18|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])/; if(petname==""){ alert("宠物名称不能为空"); return false; } if(select=="请选择"){ alert("请选择宠物类型"); return false; } if(bornDate==""){ alert("请输入宠物出生日期"); return false; } if(reg.test(bornDate)==false){ span.innerHTML="YYYY-MM-DD"; alert("日期格式错误"); return false; } if(textarea==" "){ alert("请输入宠物描述"); return false; } } </script> </body> </html>
时间: 2024-10-14 20:22:40