使用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>