使用jsp+servLet實(shí)現(xiàn)寵物管理系統(tǒng),oraC1e11g作為后臺(tái)數(shù)據(jù)厙,實(shí)現(xiàn)查看寵物和增加寵物的功能由你實(shí)現(xiàn),如圖:

其中寵物包栝:狗、貓、鳥、鼠
具體要求及推薦實(shí)現(xiàn)步驟

第一步:創(chuàng)建數(shù)據(jù)庫(kù)代碼:
create table pet(petId number(10) not null PRimary key, --idpetName varchar2(50) not null, --昵稱petBread varchar(50) not null, --品種petSex varchar(10) not null, --性別birthday date not null, --出生日期description varchar(400) --描述)--序列自增create sequence pet_squstart with 1increment by 1nomaxvaluecache 10;drop table pet --刪除寵物表drop sequence pet_squ --刪除序列--插入數(shù)據(jù)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 --查詢所有寵物
第二步:建立寵物實(shí)體類entity(pet)
package entity;/** * 寵物實(shí)體類 * @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; }}第三步:建立數(shù)據(jù)庫(kù) 幫助類DB(記得導(dǎo)入架包)
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 { //數(shù)據(jù)庫(kù)名和登入密碼 String driver="Oracle.jdbc.driver.OracleDriver"; String url="jdbc:oracle:thin:@localhost:1521:ORCL"; String user = "epet"; String pwd = "123456"; //建立數(shù)據(jù)庫(kù)連接方法 public Connection getConnection(){ //加載驅(qū)動(dòng) try { //第一步:加載驅(qū)動(dòng) Class.forName(driver); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } Connection con =null; //獲取連接對(duì)象 try { con =DriverManager.getConnection(url,user,pwd); //連接數(shù)據(jù)庫(kù) } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } return con; } //======釋放資源方法======= public void ShiFang(ResultSet rs, Statement st,Connection con){ //如果結(jié)果集不為空,則釋放成功 ,否則失敗 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(); } } }第四步:三層架構(gòu)(數(shù)據(jù)查詢層+業(yè)務(wù)邏輯層+表示層JSP)
1、創(chuàng)建Biz(業(yè)務(wù)邏輯層)
package Biz;import java.util.List;import entity.pet;/** * 業(yè)務(wù)邏輯層 * @author Administrator * */public interface petBiz { //查詢寵物信息 public List<pet> returnList(); //添加寵物信息 public int insertPet(pet pet); //根據(jù)寵物類型查詢寵物信息 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 { //實(shí)例化數(shù)據(jù)連接層 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、創(chuàng)建DAO(數(shù)據(jù)查詢層)
package Dao;import java.util.List;import entity.pet;/** * 數(shù)據(jù)查詢層 * @author Administrator * */public interface petDao { //查詢寵物信息 public List<pet> returnList(); //添加寵物信息 public int insertPet(pet pet); //根據(jù)寵物類型查詢寵物信息 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("請(qǐng)選擇")){ 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; }}第五步:創(chuàng)建實(shí)現(xiàn)Servlet的配置(web項(xiàng)目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"> <!-- 注冊(cè) --> <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> <!-- 注冊(cè) --> <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="請(qǐng)選擇"; }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、三層架構(gòu)之表示層(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={"請(qǐng)選擇","貓","狗","鳥","鼠"}; request.setAttribute("petArray", petArray);%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <base href="<%=basePath%>"> <title>顯示頁(yè)</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="請(qǐng)選擇">--請(qǐng)選擇--</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=="請(qǐng)選擇"){ alert("請(qǐng)選擇寵物類型"); return false; } if(bornDate==""){ alert("請(qǐng)輸入寵物出生日期"); return false; } if(reg.test(bornDate)==false){ span.innerHTML="YYYY-MM-DD"; alert("日期格式錯(cuò)誤"); return false; } if(textarea==" "){ alert("請(qǐng)輸入寵物描述"); return false; } } </script> </body></html>新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注