一個簡單的java web 項目

本文實現一個簡單的 Java Web 項目,包括如下5個功能:javascript

1. 登陸css

    用戶默認主頁index.jsp , 可選擇登陸功能,輸入用戶名和密碼,若登陸成功,則進入產品管理總頁面main.jsp。若不成功仍退回index.jsphtml

   

2. 註冊java

    用戶默認主頁index.jsp ,  可選擇註冊功能 ,若註冊,則進入 register.jspmysql

3. 管理產品(增長,刪除,查看)web

    登陸成功後,進入產品管理總頁面main.jsp。第一次進入main.jsp,默認顯示全部產品列表。在此頁面上更實現 查詢某個產品記錄,添加產品,批量刪除,選中一項產品查看詳情,實現分頁功能。sql

    3.1 添加產品數據庫

  

    3.2 查詢"聖女果"apache

    3.3 選擇「香蕉」 ,點擊 「查看」api

 

4. 退出

    用戶點擊「退出」時,清除session,退回主頁面index.jsp

5. 過濾器

    若用戶沒有登陸成功,而直接訪問 main.jsp 或 addProduct.jsp ,則被過濾器過濾到 index.jsp . 由於有成功登陸,驗證其身份後,纔有權利訪問產品和管理產品。不然將被過濾到默認主頁index.jsp.

    例如:在地址欄直接輸入:http://192.168.0.103:8080/xianfengProject/main.jsp,則被過濾到index.jsp

-------------------------------------------------------------------------------

項目環境:

操做系統:win7

實現技術:jsp+servlet

數據庫: mysql5.5.20 , Navicat_for_MySQL_11.0.10

服務器:apache-tomcat-7.0.40

開發平臺: MyEclipse10

--------------------------------------------------------------------------------

說明:

1. 數據庫

     數據庫名:mydb , 共兩張表.

     表一:userinfo (id , username , pswd)

     表二:product (proid , proname, proprice , proaddress , proimage)

 

product (proid , proname, proprice , proaddress , proimage)表結構:

 

userinfo (id , username , pswd)表結構以下:

 

2. MyEclipse 工程目錄

 

----------------------------------------------------------------------------------------------------------------------

1. index.jsp

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   
  10.   <head>  
  11.     <base href="<%=basePath%>">  
  12.       
  13.       
  14.     <title>先鋒管理系統歡迎您</title>  
  15.     <meta http-equiv="pragma" content="no-cache">  
  16.     <meta http-equiv="cache-control" content="no-cache">  
  17.     <meta http-equiv="expires" content="0">      
  18.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  19.     <meta http-equiv="description" content="This is my page">  
  20.     <!--  
  21.     <link rel="stylesheet" type="text/css" href="styles.css">  
  22.     -->  
  23.           
  24. <script type="text/javascript">  
  25. function login(){  
  26.     var th = document.form1;  
  27.     if(th.username.value==""){  
  28.         alert("用戶名不能爲空!");  
  29.         th.username.focus();  
  30.         return;  
  31.     }  
  32.     if(th.pswd.value==""){  
  33.         alert("密碼不能爲空!");  
  34.         th.pswd.focus();  
  35.         return;  
  36.     }  
  37.       
  38.     th.action = "<%=path%>/servlet/LoginAction";  
  39.     th.submit();  
  40.   
  41.   
  42. }  
  43.   
  44. </script>  
  45.       
  46.   </head>  
  47.     
  48.   <body>  
  49.     
  50.    <div style="text-align:center">     
  51.    <form name="form1" action="" method="post">  
  52.    <table  style="margin:auto">     
  53.    <tr>             
  54.         <td colspan="2">  
  55.         先鋒管理系統歡迎你!  
  56.         </td>           
  57.     </tr>  
  58.     <tr>  
  59.         <td>用戶名:</td>  
  60.         <td><input type="text" name="username"></input></td>          
  61.     </tr>  
  62.     <tr>  
  63.         <td>密    碼:</td>  
  64.         <td><input type="password" name="pswd"></input></td>          
  65.     </tr>  
  66.         <tr>  
  67.           
  68.         <td colspan="2" align="center">  
  69.         <button type="button" name="" value="" onclick="login()">登陸</button>  
  70.         <button type="button" name="" value="" onclick="javascript:location.href='register.jsp'">註冊</button>  
  71.         </td>           
  72.     </tr>     
  73.      
  74.    </table>  
  75.    </form>  
  76.   </div>  
  77.    
  78.      
  79.   </body>  
  80. </html>  

 

2. register.jsp

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>註冊新用戶</title>  
  13.       
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <!--  
  20.     <link rel="stylesheet" type="text/css" href="styles.css">  
  21.     -->  
  22. <script type="text/javascript">  
  23. function dosubmit(){  
  24.       
  25.     var th = document.form1;  
  26.     if(th.username.value==""){  
  27.         alert("用戶名不能爲空!");  
  28.         th.username.focus();  
  29.         return;  
  30.     }  
  31.     if(th.pswd.value==""){  
  32.         alert("密碼不能爲空!");  
  33.         th.pswd.focus();  
  34.         return;  
  35.     }  
  36.     th.action="<%=path%>/servlet/RegisterAction";  
  37.     th.submit();  
  38.   
  39. }  
  40. function back(){  
  41.     alert("退回主頁!");  
  42.     th = document.form1;  
  43.     th.acton="<%=path%>/index.jsp";  
  44.     th.submit;  
  45. }  
  46.   
  47. </script>  
  48.   
  49.   </head>  
  50.     
  51.   <body>  
  52.     <div style="text-align:center">     
  53.    <form action="" name="form1" method="post">  
  54.    <table  style="margin:auto">     
  55.    <tr>             
  56.         <td colspan="3">  
  57.         用戶註冊  
  58.         </td>           
  59.     </tr>  
  60.     <tr>  
  61.         <td>用戶名:</td>  
  62.         <td><input type="text" name="username"></input></td>    
  63.         <td>必須填寫!</td>        
  64.     </tr>  
  65.     <tr>  
  66.         <td>密    碼:</td>  
  67.         <td><input type="password" name="pswd"></input></td>    
  68.         <td>必須填寫!</td>            
  69.           
  70.     </tr>  
  71.     <tr>  
  72.           
  73.         <td colspan="3" align="center">  
  74.         <button type="button" name="" onclick="dosubmit()" >肯定</button>  
  75.         <button type="button" name="" value="" onclick="javascript:location.href='index.jsp'" >返回</button>  
  76.         </td>           
  77.     </tr>     
  78.      
  79.    </table>  
  80.    </form>  
  81.     
  82.   </div>  
  83.    
  84.   </body>  
  85. </html>  

 

3.main.jsp

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%@ page import="com.util.*" %>  
  3. <%@ page import="com.product.*" %>  
  4. <%  
  5. String path = request.getContextPath();  
  6. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  7. //獲取 session 中的 username;  
  8. String username = (String)session.getAttribute("username");  
  9. //獲取從 servlet ProductActiion 中 傳遞的參數(數據庫查詢的結果)  
  10. List<Map<String,Object>> list =(List<Map<String,Object>>) request.getAttribute("listProduct");  
  11. // 獲取 分頁對象  
  12. DividePage dividePage = (DividePage) request.getAttribute("dividePage");  
  13. // 獲取查詢的關鍵詞  
  14. String productName = (String) request.getAttribute("productName");  
  15. if(list==null){  
  16.     //第一次進 main.jsp頁面,默認加載全部的產品  
  17.     ProductService service = new ProductDao();  
  18.     int totalRecord = service.getItemCount("");  
  19.     dividePage = new DividePage(5,totalRecord,1);  
  20.     int start = dividePage.fromIndex();  
  21.     int end = dividePage.toIndex();  
  22.     list = service.listProduct("", start, end);  
  23. }  
  24.       
  25. %>  
  26.   
  27. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  28. <html>  
  29.   <head>  
  30.     <base href="<%=basePath%>">  
  31.       
  32.     <title>產品管理</title>  
  33.       
  34.     <meta http-equiv="pragma" content="no-cache">  
  35.     <meta http-equiv="cache-control" content="no-cache">  
  36.     <meta http-equiv="expires" content="0">      
  37.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  38.     <meta http-equiv="description" content="This is my page">  
  39.     <!--  
  40.     <link rel="stylesheet" type="text/css" href="styles.css">  
  41.     -->  
  42.     <script type="text/javascript">  
  43.     function searchProduct(){  
  44.         var th = document.form2;  
  45.         th.action="<%=path%>/servlet/ProductAction?action_flag=search";  
  46.         th.submit();  
  47.     }  
  48.       
  49.     function first(){  
  50.           
  51.         window.location.href = "<%=path%>/servlet/ProductAction?action_flag=search&pageNum=1";  
  52.           
  53.     }  
  54.     function next(){  
  55.           
  56.         window.location.href = "<%=path%>/servlet/ProductAction?action_flag=search&pageNum=<%=dividePage.getCurrentPage()+1%>";       
  57.       
  58.     }  
  59.     function forward(){  
  60.           
  61.         window.location.href = "<%=path%>/servlet/ProductAction?action_flag=search&pageNum=<%=dividePage.getCurrentPage()-1%>";  
  62.           
  63.     }  
  64.     function end(){  
  65.           
  66.         window.location.href = "<%=path%>/servlet/ProductAction?action_flag=search&pageNum=<%=dividePage.getPageCount() %>";  
  67.               
  68.     }  
  69.       
  70.     function changePage(currentPage){  
  71.       
  72.         window.location.href = "<%=path%>/servlet/ProductAction?action_flag=search&pageNum="+currentPage;  
  73.       
  74.     }  
  75.        
  76.     function selectAll(flag){  
  77.           
  78.         var ids = document.getElementsByName("ids");  
  79.         for(var i = 0 ; i < ids.length ; i++){  
  80.             ids[i].checked = flag;  
  81.         }  
  82.       
  83.     }  
  84.       
  85.     function getSelectedCount(){  
  86.       
  87.         var ids = document.getElementsByName("ids");  
  88.         var count = 0;  
  89.         for(var i = 0 ; i < ids.length ; i++)  
  90.         {  
  91.                           
  92.             ids[i].checked==true?count++:0;                   
  93.         }  
  94.         return count;  
  95.       
  96.     }  
  97.       
  98.     function del(){  
  99.       
  100.         if(getSelectedCount()==0){  
  101.               
  102.             alert("至少選擇一個刪除項!");  
  103.             return;  
  104.           
  105.         }  
  106.           
  107.         var th = document.form1;  
  108.         th.action="<%=path%>/servlet/ProductAction?action_flag=del";  
  109.         th.submit();          
  110.       
  111.     }  
  112.       
  113.     function getSelectedValue(){  
  114.         var ids = document.getElementsByName("ids");  
  115.           
  116.         for(var i = 0 ; i < ids.length ; i++)  
  117.         {  
  118.                           
  119.             if(ids[i].checked){  
  120.                 return ids[i].value;  
  121.             }                 
  122.         }  
  123.           
  124.     }  
  125.       
  126.     function view(){  
  127.       
  128.         if(getSelectedCount()<1){  
  129.               
  130.             alert("至少選擇一個查看項!");  
  131.             return;  
  132.           
  133.         }else if(getSelectedCount()>1){  
  134.             alert("只能選擇一個查看項!");  
  135.             return;  
  136.         }  
  137.           
  138.         var th = document.form1;  
  139.         th.action="<%=path%>/servlet/ProductAction?action_flag=view&proid="+getSelectedValue();  
  140.         th.submit();          
  141.       
  142.     }  
  143.       
  144.     function logout(){  
  145.       
  146.     window.location.href="<%=path %>/servlet/LogoutAction?action_flag=logout";  
  147.           
  148.     }  
  149.       
  150.       
  151.     </script>  
  152.   
  153.   </head>  
  154.     
  155.   <body>  
  156.    <div>  
  157.    <table width=60% align="center">  
  158.    <tr>  
  159.         <td align="left"><font size=2>歡迎您的光臨,<%=username%><br><a href="javascript:logout();">退出</a></font></td>  
  160.    </tr>  
  161.     <tr>  
  162.         <td align="center">  
  163.         <form name = "form2" action="" method="post">  
  164.         <table>  
  165.             <tr>  
  166.                 <td colspan="2">產品信息查詢</td>  
  167.                   
  168.             </tr>  
  169.             <tr>  
  170.                 <td >產品名稱</td>  
  171.                 <td ><input type="text" name="proname" value="<%= productName!=null?productName:"" %>"/></td>  
  172.                   
  173.             </tr>  
  174.               
  175.             <tr>  
  176.                 <td colspan="2" align="center">  
  177.                     <button type="button" onclick="searchProduct()" >查詢</button>  
  178.                     <button type="button" onclick="javascript:location.href='<%=path %>/addProduct.jsp'">添加</button>                        
  179.                       
  180.                 </td>                   
  181.             </tr>           
  182.         </table>        
  183.         </form>     
  184.               
  185.         </td>  
  186.     </tr>  
  187.       
  188.     <tr>  
  189.         <td height=50> </td>  
  190.     </tr>  
  191.     <tr>  
  192.         <td> 查詢結果</td>  
  193.     </tr>  
  194.       
  195.     <tr>  
  196.         <td >  
  197.         <form name="form1" action="" method="post">  
  198.         <table border=1 width=100%>  
  199.             <tr align="center">  
  200.                 <td width=10%><input type="checkbox" name="checkall" onclick="javascript:selectAll(this.checked);" /></td>  
  201.                 <td width=30%>產品名稱</td>  
  202.                 <td width=30%>產品產地</td>  
  203.                 <td>產品價格</td>  
  204.               
  205.             </tr>  
  206.             <%  
  207.             if(list!=null && !list.isEmpty()){  
  208.               
  209.                 for(Map<String,Object> map :list){%>  
  210.               
  211.                 <tr align="center">  
  212.                 <td width=10%><input type="checkbox" name="ids" value="<%=map.get("proid") %>"/></td>  
  213.                 <td width=30%><%=map.get("proname") %></td>  
  214.                 <td width=30%><%=map.get("proaddress") %></td>  
  215.                 <td><%=map.get("proprice") %></td>  
  216.                   
  217.                 <%}  
  218.               
  219.               
  220.             }else{%>  
  221.               
  222.             <tr align="center">  
  223.                 <td width=10%><input type="checkbox" name="" /></td>  
  224.                 <td width=30%></td>  
  225.                 <td width=30%></td>  
  226.                 <td></td>  
  227.               
  228.             </tr><%  
  229.               
  230.             }                 
  231.              %>  
  232.               
  233.       
  234.               
  235.           
  236.         </table>            
  237.         </form>  
  238.         </td>  
  239.       
  240.     </tr>  
  241.       
  242.     <tr>  
  243.         <td>  
  244.             <button type="button" onclick="javascript:del();">刪除</button>  
  245.             <button type="button" onclick="javascript:view();" >查看</button>  
  246.           
  247.         </td>  
  248.     </tr>  
  249.       
  250.     <tr>  
  251.         <td colspan="4" align="center">  
  252.             共<%=dividePage.getPageCount()  %>頁      
  253.             <a href="javascript:first();">首頁</a>     
  254.             <a href="javascript:forward();">上一頁</a>   
  255.             <a href="javascript:next();">下一頁</a>   
  256.             <a href="javascript:end();">尾頁</a>   
  257.             跳轉到<select name="select" onchange="changePage(this.value)">  
  258.               
  259.             <%  
  260.             int pageCount = dividePage.getPageCount();  
  261.             if(pageCount>0){  
  262.             for(int i = 1 ; i<=pageCount;i++){%>  
  263.               
  264.             <option value="<%=i %>" <%= (i==dividePage.getCurrentPage()?"selected":"")%>>  <%=i %>  
  265.             </option>  
  266.               
  267.             <%             
  268.             }  
  269.               
  270.             }else{// 無記錄  
  271.                 %>  
  272.                 <option value="1">1</option>     
  273.              <%}           
  274.               
  275.             %>  
  276.                       
  277.             </select>  
  278.           
  279.         </td>  
  280.     </tr>  
  281.               
  282.      
  283.      
  284.      
  285.      
  286.    </table>  
  287.      
  288.      
  289.      
  290.    </div>  
  291.      
  292.      
  293.   </body>  
  294. </html>  

 

4.addProduct.jsp

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. %>  
  6.   
  7. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  8. <html>  
  9.   <head>  
  10.     <base href="<%=basePath%>">  
  11.       
  12.     <title>新增產品</title>  
  13.       
  14.     <meta http-equiv="pragma" content="no-cache">  
  15.     <meta http-equiv="cache-control" content="no-cache">  
  16.     <meta http-equiv="expires" content="0">      
  17.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  18.     <meta http-equiv="description" content="This is my page">  
  19.     <!--  
  20.     <link rel="stylesheet" type="text/css" href="styles.css">  
  21.     -->  
  22. <script type="text/javascript">  
  23. function dosubmit(){  
  24.     var th = document.form1;  
  25.     th.action="<%= path%>/servlet/ProductAction?action_flag=add";  
  26.     th.submit();  
  27.   
  28. }  
  29.   
  30. </script>  
  31.   </head>  
  32.     
  33.   <body>  
  34.     <div align="center">  
  35.       
  36.         <table width=70% style="margin:auto;">  
  37.             <tr><td align="center" height=150 valign="bottom">產品信息添加</td></tr>  
  38.             <tr>  
  39.                 <td>  
  40.                     <form id="form1" name="form1" action="" method="post" enctype="multipart/form-data">  
  41.                     <table border=1 style="margin:auto">  
  42.                         <tr >  
  43.                             <td>產品名稱</td>  
  44.                             <td><input type="text" name="proname" id="proname"/></td>  
  45.                             <td>產品價格</td>  
  46.                             <td><input type="text" name="proprice" id="proprice"/></td>  
  47.                         </tr>  
  48.                         <tr>  
  49.                             <td>產品產地</td>  
  50.                             <td colspan="3"><input type="text" name="proaddress" id="proaddress"/></td>  
  51.                         </tr>  
  52.                         <tr>  
  53.                             <td>產品圖片</td>  
  54.                             <td colspan="3"><input type="file" name="proimage" id="proimage"  size=35/></td>  
  55.                         </tr>  
  56.                       
  57.                     </table>   
  58.                     </form>                     
  59.                   
  60.                 </td>  
  61.             </tr>  
  62.             <tr>  
  63.                 <td colspan="4" align="center">  
  64.                     <button type="button" onclick="javascript:dosubmit();">肯定</button>  
  65.                     <button type="button" onclick="javascript:location.href='main.jsp'">返回</button>  
  66.                   
  67.                 </td>  
  68.             </tr>  
  69.               
  70.           
  71.         </table>  
  72.           
  73.     </div>  
  74.   </body>  
  75. </html>  

 

5. viewProduct.jsp

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. <%@ page language="java" import="java.util.*" pageEncoding="utf-8" %>  
  2. <%  
  3. String path = request.getContextPath();  
  4. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";  
  5. Map<String,Object> map = (Map<String,Object>)request.getAttribute("productMap");  
  6.   
  7. %>  
  8.   
  9. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">  
  10. <html>  
  11.   <head>  
  12.     <base href="<%=basePath%>">  
  13.       
  14.     <title>查看產品</title>  
  15.       
  16.     <meta http-equiv="pragma" content="no-cache">  
  17.     <meta http-equiv="cache-control" content="no-cache">  
  18.     <meta http-equiv="expires" content="0">      
  19.     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">  
  20.     <meta http-equiv="description" content="This is my page">  
  21.     <!--  
  22.     <link rel="stylesheet" type="text/css" href="styles.css">  
  23.     -->  
  24.   
  25.   </head>  
  26.     
  27.   <body>  
  28.   <div align="center">  
  29.           
  30.         <table width=60% style="margin:auto">  
  31.               
  32.             <tr>  
  33.                 <td height=100>  
  34.                       
  35.                 </td>  
  36.             </tr>  
  37.             <tr>  
  38.                 <td >  
  39.                     產品信息  
  40.                 </td>  
  41.             </tr>  
  42.             <tr>  
  43.                 <td>  
  44.                     <table width = 99% border =1 >  
  45.                         <tr align="center">  
  46.                             <td width = 20%>產品名稱</td>  
  47.                             <td width = 30%><%=map.get("proname") %></td>  
  48.                             <td width = 20%>產品價格</td>  
  49.                             <td><%=map.get("proprice") %></td>  
  50.                               
  51.                           
  52.                         </tr>  
  53.                         <tr align="center">  
  54.                             <td >產品產地</td>  
  55.                             <td colspan=3><%=map.get("proaddress") %></td>                      
  56.                               
  57.                           
  58.                         </tr>  
  59.                         <tr align="center">  
  60.                             <td>產品圖片</td>  
  61.                             <td colspan=3><img src="<%=path%>/upload/<%=map.get("proimage") %>"></td>                           
  62.                           
  63.                         </tr>  
  64.                       
  65.                       
  66.                     </table>  
  67.                 </td>  
  68.             </tr>  
  69.             <tr>  
  70.                 <td align="center">  
  71.                     <button type="button" onclick="javascript:location.href='<%=path %>/main.jsp'">肯定</button>  
  72.                     <button type="button" onclick="javascript:history.go(-1)">返回</button>  
  73.                 </td>  
  74.             </tr>  
  75.           
  76.         </table>  
  77.           
  78.       
  79.   </div>  
  80.   </body>  
  81. </html>  

 

6.LoginAction.Java

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. package com.login;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12.   
  13. public class LoginAction extends HttpServlet {  
  14.   
  15.     private LoginService service;  
  16.     /** 
  17.      * Constructor of the object. 
  18.      */  
  19.     public LoginAction() {  
  20.         super();  
  21.     }  
  22.   
  23.     /** 
  24.      * Destruction of the servlet. <br> 
  25.      */  
  26.     public void destroy() {  
  27.         super.destroy(); // Just puts "destroy" string in log  
  28.         // Put your code here  
  29.     }  
  30.   
  31.     /** 
  32.      * The doGet method of the servlet. <br> 
  33.      * 
  34.      * This method is called when a form has its tag value method equals to get. 
  35.      *  
  36.      * @param request the request send by the client to the server 
  37.      * @param response the response send by the server to the client 
  38.      * @throws ServletException if an error occurred 
  39.      * @throws IOException if an error occurred 
  40.      */  
  41.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  42.             throws ServletException, IOException {  
  43.         this.doPost(request, response);  
  44.           
  45.     }  
  46.   
  47.     /** 
  48.      * The doPost method of the servlet. <br> 
  49.      * 
  50.      * This method is called when a form has its tag value method equals to post. 
  51.      *  
  52.      * @param request the request send by the client to the server 
  53.      * @param response the response send by the server to the client 
  54.      * @throws ServletException if an error occurred 
  55.      * @throws IOException if an error occurred 
  56.      */  
  57.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  58.             throws ServletException, IOException {  
  59.   
  60.         response.setContentType("text/html;charset=utf-8");  
  61.         PrintWriter out = response.getWriter();  
  62.           
  63.         String path = request.getContextPath();  
  64.         String username = request.getParameter("username");  
  65.         String pswd = request.getParameter("pswd");  
  66.           
  67.         List<Object> params = new ArrayList<Object>();  
  68.         params.add(username);  
  69.         params.add(pswd);  
  70.         boolean flag = service.login(params);  
  71.           
  72.         if (flag) {  
  73.               
  74.             request.getSession().setAttribute("username", username);  
  75.             response.sendRedirect(path+"/main.jsp");  
  76.         }else{  
  77.                           
  78.             response.sendRedirect(path+"/index.jsp");  
  79.         }  
  80.           
  81.           
  82.           
  83.           
  84.         out.flush();  
  85.         out.close();  
  86.     }  
  87.   
  88.     /** 
  89.      * Initialization of the servlet. <br> 
  90.      * 
  91.      * @throws ServletException if an error occurs 
  92.      */  
  93.     public void init() throws ServletException {  
  94.         // Put your code here  
  95.         service = new LoginDao();  
  96.     }  
  97.   
  98. }  

 

7.LoginDao.java

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. package com.login;  
  2.   
  3. import java.sql.SQLException;  
  4. import java.util.List;  
  5. import java.util.Map;  
  6.   
  7. import javax.mail.Flags.Flag;  
  8.   
  9. import com.jdbc.JdbcUtils;  
  10.   
  11. public class LoginDao implements LoginService {  
  12.   
  13.     private JdbcUtils jdbcUtils;  
  14.     public LoginDao() {  
  15.         // TODO Auto-generated constructor stub  
  16.         jdbcUtils = new JdbcUtils();  
  17.     }  
  18.   
  19.     @Override  
  20.     public boolean login(List<Object> params) {  
  21.         // TODO Auto-generated method stub  
  22.         boolean flag = false;  
  23.           
  24.         try {  
  25.             jdbcUtils.getConnection();  
  26.             String sql = "select * from userinfo where username = ? and pswd = ?";  
  27.             Map<String, Object> map = jdbcUtils.findSimpleResult(sql, params);  
  28.             flag = !map.isEmpty()?true:false;             
  29.               
  30.         } catch (Exception e) {  
  31.             // TODO: handle exception  
  32.             e.printStackTrace();  
  33.         }finally{  
  34.               
  35.         //關閉數據庫  
  36.         jdbcUtils.releaseConn();  
  37.               
  38.         }  
  39.           
  40.         return flag;  
  41.     }     
  42.   
  43. }  

 

8.LoginService.java

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. package com.login;  
  2.   
  3. import java.util.List;  
  4.   
  5. public interface LoginService {  
  6.   
  7.     public boolean login(List<Object> params);  
  8. }  

 

9. MyFilter.java

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. package com.filter;  
  2.   
  3. import java.io.IOException;  
  4.   
  5. import javax.servlet.Filter;  
  6. import javax.servlet.FilterChain;  
  7. import javax.servlet.FilterConfig;  
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.ServletRequest;  
  10. import javax.servlet.ServletResponse;  
  11. import javax.servlet.http.HttpServletRequest;  
  12. import javax.servlet.http.HttpServletResponse;  
  13.   
  14. public class MyFilter implements Filter {  
  15.   
  16.     public MyFilter() {  
  17.         // TODO Auto-generated constructor stub  
  18.     }  
  19.   
  20.     @Override  
  21.     public void destroy() {  
  22.         // TODO Auto-generated method stub  
  23.   
  24.     }  
  25.   
  26.     @Override  
  27.     public void doFilter(ServletRequest request, ServletResponse response,  
  28.             FilterChain filterChain) throws IOException, ServletException {  
  29.         // 過濾用戶請求,判斷是否登陸  
  30.         HttpServletRequest httpServletRequest = (HttpServletRequest)request;  
  31.         HttpServletResponse httpServletResponse = (HttpServletResponse)response;  
  32.           
  33.         httpServletRequest.setCharacterEncoding("utf-8");  
  34.         httpServletResponse.setCharacterEncoding("utf-8");  
  35.           
  36.         String username = (String)httpServletRequest.getSession().getAttribute("username");  
  37.           
  38.         if (username == null) {  
  39.             String path = httpServletRequest.getContextPath();  
  40.             httpServletResponse.sendRedirect(path+"/index.jsp");  
  41.         }         
  42.         filterChain.doFilter(httpServletRequest, httpServletResponse);  
  43.     }  
  44.   
  45.     @Override  
  46.     public void init(FilterConfig arg0) throws ServletException {  
  47.         // TODO Auto-generated method stub  
  48.   
  49.     }  
  50.   
  51. }  

 

10.RegisterAction.java

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. package com.register;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5. import java.util.ArrayList;  
  6. import java.util.List;  
  7.   
  8. import javax.servlet.ServletException;  
  9. import javax.servlet.http.HttpServlet;  
  10. import javax.servlet.http.HttpServletRequest;  
  11. import javax.servlet.http.HttpServletResponse;  
  12.   
  13.   
  14.   
  15. public class RegisterAction extends HttpServlet {     
  16.       
  17.     private RegisterService service;  
  18.     /** 
  19.      * Constructor of the object. 
  20.      */  
  21.     public RegisterAction() {  
  22.         super();  
  23.     }  
  24.   
  25.     /** 
  26.      * Destruction of the servlet. <br> 
  27.      */  
  28.     public void destroy() {  
  29.         super.destroy(); // Just puts "destroy" string in log  
  30.         // Put your code here  
  31.     }  
  32.   
  33.     /** 
  34.      * The doGet method of the servlet. <br> 
  35.      * 
  36.      * This method is called when a form has its tag value method equals to get. 
  37.      *  
  38.      * @param request the request send by the client to the server 
  39.      * @param response the response send by the server to the client 
  40.      * @throws ServletException if an error occurred 
  41.      * @throws IOException if an error occurred 
  42.      */  
  43.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  44.             throws ServletException, IOException {  
  45.   
  46.         this.doPost(request, response);  
  47.           
  48.     }  
  49.   
  50.     /** 
  51.      * The doPost method of the servlet. <br> 
  52.      * 
  53.      * This method is called when a form has its tag value method equals to post. 
  54.      *  
  55.      * @param request the request send by the client to the server 
  56.      * @param response the response send by the server to the client 
  57.      * @throws ServletException if an error occurred 
  58.      * @throws IOException if an error occurred 
  59.      */  
  60.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  61.             throws ServletException, IOException {  
  62.   
  63.         response.setContentType("text/html;charset=utf-8");  
  64.         PrintWriter out = response.getWriter();  
  65.         String path = request.getContextPath();  
  66.           
  67.         String username = request.getParameter("username");  
  68.         String pswd = request.getParameter("pswd");  
  69.           
  70.         List<Object> params = new ArrayList<Object>();  
  71.         params.add(username);  
  72.         params.add(pswd);     
  73.         boolean flag = service.registerUser(params);  
  74.         if (flag) {  
  75.             response.sendRedirect(path+"/index.jsp");  
  76.         }  
  77.           
  78.           
  79.           
  80.         out.flush();  
  81.         out.close();  
  82.     }  
  83.   
  84.     /** 
  85.      * Initialization of the servlet. <br> 
  86.      * 
  87.      * @throws ServletException if an error occurs 
  88.      */  
  89.     public void init() throws ServletException {  
  90.         // Put your code here  
  91.         service = new RegisterDao();  
  92.     }  
  93.   
  94. }  

 

11. RegisterDao.java

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. package com.register;  
  2.   
  3. import java.sql.SQLException;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6.   
  7. import com.jdbc.JdbcUtils;  
  8.   
  9. public class RegisterDao implements RegisterService {  
  10.   
  11.     private JdbcUtils jdbcUtils;  
  12.     public RegisterDao() {  
  13.         // TODO Auto-generated constructor stub  
  14.         jdbcUtils = new JdbcUtils();  
  15.     }  
  16.   
  17.     /* 完成對用戶註冊的dao的編寫 
  18.      * @see com.register.service.RegisterService#registerUser(java.util.List) 
  19.      */  
  20.     @Override  
  21.     public boolean registerUser(List<Object> params) {  
  22.         // TODO Auto-generated method stub  
  23.         boolean flag = false;  
  24.         try {  
  25.             jdbcUtils.getConnection();  
  26.             String sql = "insert into userinfo(username,pswd) values(?,?)";           
  27.             flag = jdbcUtils.updateByPreparedStatement(sql, params);  
  28.               
  29.               
  30.         } catch (Exception e) {  
  31.             // TODO: handle exception  
  32.             e.printStackTrace();  
  33.         }finally{  
  34.             //關閉數據庫鏈接             
  35.             jdbcUtils.releaseConn();  
  36.               
  37.         }  
  38.           
  39.           
  40.         return flag;  
  41.     }  
  42.   
  43. }  

 

12. RegisterService.java

 

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. package com.register;  
  2.   
  3. import java.util.List;  
  4.   
  5. public interface RegisterService {  
  6.       
  7.     //完成用戶註冊功能  
  8.     public boolean registerUser(List<Object> params);  
  9. }  

 

 

 

 

 

13. ProductAction.java

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. package com.product;  
  2.   
  3. import java.io.File;  
  4. import java.io.IOException;  
  5. import java.io.PrintWriter;  
  6. import java.util.ArrayList;  
  7. import java.util.List;  
  8. import java.util.Map;  
  9. import java.util.UUID;  
  10.   
  11. import javax.servlet.ServletException;  
  12. import javax.servlet.http.HttpServlet;  
  13. import javax.servlet.http.HttpServletRequest;  
  14. import javax.servlet.http.HttpServletResponse;  
  15.   
  16. import org.apache.commons.fileupload.FileItem;  
  17. import org.apache.commons.fileupload.disk.DiskFileItemFactory;  
  18. import org.apache.commons.fileupload.servlet.ServletFileUpload;  
  19.   
  20.   
  21. import com.util.DividePage;  
  22. import com.util.UUIDTools;  
  23.   
  24. public class ProductAction extends HttpServlet {  
  25.   
  26.     private ProductService service;  
  27.     /** 
  28.      * Constructor of the object. 
  29.      */  
  30.     public ProductAction() {  
  31.         super();  
  32.     }  
  33.   
  34.     /** 
  35.      * Destruction of the servlet. <br> 
  36.      */  
  37.     public void destroy() {  
  38.         super.destroy(); // Just puts "destroy" string in log  
  39.         // Put your code here  
  40.     }  
  41.   
  42.     /** 
  43.      * The doGet method of the servlet. <br> 
  44.      * 
  45.      * This method is called when a form has its tag value method equals to get. 
  46.      *  
  47.      * @param request the request send by the client to the server 
  48.      * @param response the response send by the server to the client 
  49.      * @throws ServletException if an error occurred 
  50.      * @throws IOException if an error occurred 
  51.      */  
  52.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  53.             throws ServletException, IOException {  
  54.   
  55.         this.doPost(request, response);  
  56.     }  
  57.   
  58.     /** 
  59.      * The doPost method of the servlet. <br> 
  60.      * 
  61.      * This method is called when a form has its tag value method equals to post. 
  62.      *  
  63.      * @param request the request send by the client to the server 
  64.      * @param response the response send by the server to the client 
  65.      * @throws ServletException if an error occurred 
  66.      * @throws IOException if an error occurred 
  67.      */  
  68.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  69.             throws ServletException, IOException {  
  70.   
  71.         response.setContentType("text/html;charset=utf-8");  
  72.         request.setCharacterEncoding("utf-8");  
  73.         response.setCharacterEncoding("utf-8");  
  74.         PrintWriter out = response.getWriter();  
  75.           
  76.         String action_flag = request.getParameter("action_flag");  
  77.         if (action_flag.equals("add")) {  
  78.             addProduct(request,response);  
  79.         }else if (action_flag.equals("search")) {  
  80.             listProduct(request,response);  
  81.         }else if (action_flag.equals("del")) {  
  82.             delProduct(request,response);  
  83.         }else if (action_flag.equals("view")) {  
  84.             viewProduct(request,response);  
  85.         }  
  86.           
  87.           
  88.         out.flush();  
  89.         out.close();  
  90.     }  
  91.   
  92.     private void viewProduct(HttpServletRequest request,  
  93.             HttpServletResponse response) {  
  94.         // TODO Auto-generated method stub  
  95.         String proid = request.getParameter("proid");  
  96.         Map<String, Object> map = service.viewProduct(proid);  
  97.         request.setAttribute("productMap", map);  
  98.         try {  
  99.             request.getRequestDispatcher("/viewProduct.jsp").forward(request, response);  
  100.         } catch (Exception e) {  
  101.             // TODO Auto-generated catch block  
  102.             e.printStackTrace();  
  103.         }   
  104.           
  105.     }  
  106.   
  107.     /**批量刪除產品 
  108.      * @param request 
  109.      * @param response 
  110.      */  
  111.     private void delProduct(HttpServletRequest request,  
  112.             HttpServletResponse response) {  
  113.         // TODO Auto-generated method stub  
  114.           
  115.         System.out.println("進入del");  
  116.         //得到複選框的值  
  117.         String[] ids = request.getParameterValues("ids");  
  118.         for (int i = 0; i < ids.length; i++) {  
  119.             System.out.println("ids["+i+"]="+ids[i]);  
  120.         }  
  121.         boolean flag = service.delProduct(ids);  
  122.         System.out.println("刪除flag:"+flag);  
  123.         if (flag) {  
  124.             try {  
  125.                 request.getRequestDispatcher("/main.jsp").forward(request, response);  
  126.             } catch (Exception e) {  
  127.                 // TODO Auto-generated catch block  
  128.                 e.printStackTrace();  
  129.             }  
  130.         }         
  131.     }  
  132.   
  133.     private void listProduct(HttpServletRequest request,  
  134.             HttpServletResponse response) {  
  135.         // TODO Auto-generated method stub  
  136.           
  137.         String productName = request.getParameter("proname");     
  138.         String pageNum = request.getParameter("pageNum");  
  139.         System.out.println("參數 pageNum :"+pageNum);  
  140.         if (productName == null) {  
  141.             productName = "";  
  142.         }  
  143.           
  144.           
  145.           
  146.         int totalRecord = service.getItemCount(productName); //獲取總的記錄數  
  147.         int currentPage = 1;  
  148.         DividePage dividePage = new DividePage(5, totalRecord);//默認第一頁開始  
  149.         if (pageNum != null) {  
  150.               
  151.               
  152.             currentPage = Integer.parseInt(pageNum);  
  153.               
  154.             dividePage.setCurrentPage(currentPage);  
  155.         }  
  156.           
  157.         //記錄從第幾行開始  
  158.         int start = dividePage.fromIndex();  
  159.         //顯示幾條記錄  
  160.         int end = dividePage.toIndex();       
  161.           
  162.         System.out.println("currentPageNum :"+ dividePage.getCurrentPage() +", start = "+start +", end = "+end);  
  163.           
  164.         List<Map<String, Object>> list = null;  
  165.         try {  
  166.             list = service.listProduct(productName , start , end);  
  167.             request.setAttribute("listProduct", list);  
  168.             request.setAttribute("dividePage", dividePage);  
  169.             request.setAttribute("productName",productName );  
  170.             request.getRequestDispatcher("/main.jsp").forward(request, response);  
  171.         } catch (Exception e) {  
  172.             // TODO: handle exception  
  173.             e.printStackTrace();  
  174.         }         
  175.           
  176.     }  
  177.   
  178.     private void addProduct(HttpServletRequest request, HttpServletResponse response)   
  179.             throws ServletException, IOException{  
  180.         //表單含有文件要提交  
  181.         String  path = request.getContextPath();          
  182.         DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();  
  183.         ServletFileUpload servletFileUpload = new ServletFileUpload(diskFileItemFactory);  
  184.         servletFileUpload.setFileSizeMax(3*1024*1024);//單個文件大小限制3M  
  185.         servletFileUpload.setSizeMax(6*1024*1024);//上傳文件總大小  
  186.         List<FileItem> list = null;         
  187.         List<Object> params = new ArrayList<Object>();  
  188.         params.add(UUIDTools.getUUID()); // 參數傳 product表的主鍵  
  189.         try {  
  190.             //解析request的請求  
  191.             list = servletFileUpload.parseRequest(request);               
  192.             //取出全部表單的值,判斷非文本字段和文本字段  
  193.             for(FileItem fileItem : list){  
  194.                 if (fileItem.isFormField()) {//是文本字段  
  195.                     String fileItemName = fileItem.getFieldName(); //獲取 <input>控件的 名稱  
  196.                     String fileItemValue = fileItem.getString("utf-8");//獲取<input>控件的值  
  197.                     if (fileItemName.equals("proname")) {  
  198.                         params.add(fileItemValue); //參數傳入 proname  
  199.                     }else if (fileItemName.equals("proprice")) {  
  200.                         params.add(fileItemValue);//參數傳入 proprice  
  201.                     }else if (fileItemName.equals("proaddress")) {  
  202.                         params.add(fileItemValue);////參數傳入 proaddress  
  203.                     }                     
  204.                 }else{ //非文本字段                    
  205.                       
  206.                     String imageName = fileItem.getName(); //獲取文件名稱  
  207.                     params.add(imageName);//參數傳入  proimage            
  208.                     //String path = request.getRealPath("/upload");  
  209.                     String upload_dir = request.getServletContext().getRealPath("/upload");//獲取服務器端 /upload 路徑  
  210.                     File uploadFile = new File(upload_dir+"/"+imageName);  
  211.                     System.out.println("---upload_dir--->>"+uploadFile);  
  212.                     fileItem.write(uploadFile);                       
  213.                 }                 
  214.             }  
  215.               
  216.             // 把產品加入數據庫  
  217.             boolean flag = service.addProduct(params);  
  218.             if (flag) {  
  219.                   
  220.                 response.sendRedirect(path+"/main.jsp");  
  221.             }  
  222.                   
  223.               
  224.         } catch (Exception e) {  
  225.             // TODO: handle exception  
  226.             e.printStackTrace();  
  227.         }  
  228.           
  229.           
  230.           
  231.     }  
  232.   
  233.     /** 
  234.      * Initialization of the servlet. <br> 
  235.      * 
  236.      * @throws ServletException if an error occurs 
  237.      */  
  238.     public void init() throws ServletException {  
  239.         // Put your code here  
  240.         service = new ProductDao();  
  241.     }  
  242.   
  243. }  


14.ProductDao.java

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. package com.product;  
  2.   
  3. import java.sql.SQLException;  
  4. import java.util.ArrayList;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. import com.jdbc.JdbcUtils;  
  9.   
  10. public class ProductDao implements ProductService {  
  11.   
  12.     private JdbcUtils jdbcUtils;  
  13.     public ProductDao() {  
  14.         // TODO Auto-generated constructor stub  
  15.         jdbcUtils = new JdbcUtils();  
  16.     }  
  17.   
  18.     @Override  
  19.     public boolean addProduct(List<Object> params) {  
  20.           
  21.         boolean flag = false;  
  22.         try {  
  23.             jdbcUtils.getConnection();  
  24.             String sql = "insert into product(proid,proname,proprice,proaddress,proimage) values(?,?,?,?,?)";  
  25.             flag = jdbcUtils.updateByPreparedStatement(sql, params);  
  26.         } catch (Exception e) {  
  27.             // TODO: handle exception  
  28.             e.printStackTrace();  
  29.         }finally{  
  30.               
  31.             // 關閉數據庫鏈接  
  32.             jdbcUtils.releaseConn();  
  33.               
  34.         }  
  35.           
  36.           
  37.         return flag;  
  38.     }  
  39.   
  40.     @Override  
  41.     public List<Map<String, Object>> listProduct(String proname ,int start ,int end) {  
  42.         // TODO Auto-generated method stub  
  43.         List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();  
  44.         List<Object> params  = new ArrayList<Object>();       
  45.         try {  
  46.             jdbcUtils.getConnection();            
  47.             String sql = "select * from product where 1=1 and proname like ? limit ? ,?";     
  48.             if(proname.equals("")){  
  49.                 sql = "select * from product limit ? ,?";  
  50.                 params.add(start);  
  51.                 params.add(end);  
  52.                   
  53.             }else{                
  54.                 params.add("%"+proname+"%");  
  55.                 params.add(start);  
  56.                 params.add(end);  
  57.             }         
  58.                       
  59.             list = jdbcUtils.findMoreResult(sql, params);             
  60.               
  61.         } catch (Exception e) {  
  62.             // TODO: handle exception  
  63.             e.printStackTrace();  
  64.         } finally{  
  65.               
  66.               
  67.             jdbcUtils.releaseConn();  
  68.               
  69.         }  
  70.           
  71.           
  72.         return list;  
  73.     }  
  74.   
  75.     //查詢總記錄數  
  76.     @Override  
  77.     public int getItemCount(String proname) {  
  78.         // TODO Auto-generated method stub  
  79.         int count = 0;  
  80.         Map<String, Object> map = null;  
  81.         List<Object> params = null;         
  82.         try {  
  83.             jdbcUtils.getConnection();            
  84.             String sql = "select count(*) totalCount from product where 1=1 and proname like ?";      
  85.             if(proname.equals("")){  
  86.                 sql = "select count(*) totalCount from product";  
  87.                   
  88.             }else{  
  89.                 params = new ArrayList<Object>();  
  90.                 params.add("%"+proname+"%");  
  91.             }  
  92.         map = jdbcUtils.findSimpleResult(sql, params);  
  93.         count = Integer.parseInt(map.get("totalCount").toString());  
  94.               
  95.         } catch (Exception e) {  
  96.             // TODO: handle exception  
  97.             e.printStackTrace();  
  98.         } finally{  
  99.             // 關閉數據庫鏈接  
  100.             jdbcUtils.releaseConn();  
  101.         }  
  102.           
  103.           
  104.         return count;  
  105.     }  
  106.   
  107.     @Override  
  108.     public boolean delProduct(String[] ids) {  
  109.         boolean flag = false;  
  110.         try {  
  111.             jdbcUtils.getConnection();  
  112.             if (ids!=null) {  
  113.                 String[] sql = new String[ids.length];  
  114.                 for(int i = 0 ; i< ids.length; i++){  
  115.                     sql[i] = "delete from product where proid = '"+ids[i]+"'";  
  116.                     System.out.println(sql[i]);  
  117.                 }  
  118.                 flag = jdbcUtils.deleteByBatch(sql);      
  119.             }  
  120.                       
  121.               
  122.         } catch (Exception e) {  
  123.             // TODO: handle exception  
  124.             e.printStackTrace();  
  125.         } finally{  
  126.             // 關閉數據庫鏈接  
  127.             jdbcUtils.releaseConn();  
  128.         }     
  129.           
  130.         return flag;  
  131.     }  
  132.   
  133.     @Override  
  134.     public Map<String, Object> viewProduct(String proid) {  
  135.         // TODO Auto-generated method stub  
  136.         Map<String, Object> map = null;  
  137.         try {  
  138.             jdbcUtils.getConnection();  
  139.             List<Object> params = new ArrayList<Object>();  
  140.             params.add(proid);  
  141.             String sql = "select * from product where proid = ?";  
  142.             map = jdbcUtils.findSimpleResult(sql, params);  
  143.               
  144.         } catch (Exception e) {  
  145.             // TODO: handle exception  
  146.             e.printStackTrace();  
  147.         } finally{  
  148.             // 關閉數據庫鏈接  
  149.             jdbcUtils.releaseConn();  
  150.         }  
  151.           
  152.           
  153.         return map;  
  154.     }  
  155.   
  156.       
  157.   
  158. }  

 

15. ProductService.java

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. package com.product;  
  2.   
  3. import java.util.List;  
  4. import java.util.Map;  
  5.   
  6. public interface ProductService {  
  7.     public boolean addProduct(List<Object> params);  
  8.       
  9.     //列出產品,爲了分頁,加上參數 start,end  
  10.     public List<Map<String, Object>> listProduct(String proname , int start , int end);  
  11.     //獲取總的記錄數  
  12.     public int getItemCount(String proname);  
  13.     //批處理刪除產品  
  14.     public boolean delProduct(String[] ids);  
  15.     //查詢單個產品  
  16.     public Map<String, Object> viewProduct(String proid);  
  17. }  

 

16. JdbcUtils.java

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. package com.jdbc;  
  2.   
  3. import java.lang.reflect.Field;  
  4. import java.sql.Connection;  
  5. import java.sql.DriverManager;  
  6. import java.sql.PreparedStatement;  
  7. import java.sql.ResultSet;  
  8. import java.sql.ResultSetMetaData;  
  9. import java.sql.SQLException;  
  10. import java.sql.Statement;  
  11. import java.util.ArrayList;  
  12. import java.util.HashMap;   
  13. import java.util.List;  
  14. import java.util.Map;  
  15.   
  16. import com.mysql.jdbc.Driver;  
  17.   
  18. public class JdbcUtils {  
  19.   
  20.     // 定義數據庫的用戶名  
  21.     private final String USERNAME = "root";  
  22.     // 定義數據庫的密碼  
  23.     private final String PASSWORD = "123456";  
  24.     // 定義數據庫的驅動信息  
  25.     private final String DRIVER = "com.mysql.jdbc.Driver";  
  26.     // 定義訪問數據庫的地址  
  27.     private final String URL = "jdbc:mysql://localhost:3306/mydb";  
  28.   
  29.     // 定義訪問數據庫的鏈接  
  30.     private Connection connection;  
  31.     // 定義sql語句的執行對象  
  32.     private PreparedStatement pstmt;  
  33.     // 定義查詢返回的結果集合  
  34.     private ResultSet resultSet;  
  35.       
  36.     // 實現批處理的功能  
  37.     private Statement stmt;  
  38.   
  39.     public JdbcUtils() {  
  40.         // TODO Auto-generated constructor stub  
  41.         try {  
  42.             Class.forName(DRIVER);  
  43.             System.out.println("註冊驅動成功!!");  
  44.         } catch (ClassNotFoundException e) {  
  45.             // TODO Auto-generated catch block  
  46.             System.out.println("註冊驅動失敗!!");  
  47.         }  
  48.   
  49.     }  
  50.   
  51.     // 定義得到數據庫的鏈接  
  52.     public Connection getConnection() {  
  53.   
  54.         try {  
  55.             connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);  
  56.   
  57.         } catch (Exception e) {  
  58.             // TODO: handle exception  
  59.             System.out.println("Connection exception !");  
  60.         }  
  61.   
  62.         return connection;  
  63.   
  64.     }  
  65.       
  66.       
  67.       
  68.     /** 實現批處理刪除 
  69.      * @param sql 
  70.      * @return 
  71.      * @throws SQLException 
  72.      */  
  73.     public boolean deleteByBatch(String[] sql) throws SQLException{  
  74.         boolean flag = false;  
  75.         stmt = connection.createStatement();  
  76.         if (sql!=null) { //判斷數組是否爲空,不能用length來判斷,不然可能會報空指針異常。  
  77.               
  78.             for(int i = 0 ; i<sql.length ; i++){  
  79.                 stmt.addBatch(sql[i]);  
  80.             }  
  81.               
  82.             int[] count = stmt.executeBatch();  
  83.             if (count!=null) {  
  84.                 flag = true;  
  85.             }  
  86.               
  87.         }     
  88.         return flag;          
  89.     }  
  90.   
  91.     /** 
  92.      * 完成對數據庫標的增長刪除和修改的操做 
  93.      *  
  94.      * @param sql 
  95.      * @param params 
  96.      * @return 
  97.      * @throws SQLException 
  98.      */  
  99.     public boolean updateByPreparedStatement(String sql, List<Object> params)  
  100.             throws SQLException {  
  101.         boolean flag = false;  
  102.         int result = -1;// 表示當用戶執行增長刪除和修改的操做影響的行數  
  103.         int index = 1; // 表示 佔位符 ,從1開始  
  104.         pstmt = connection.prepareStatement(sql);  
  105.         if (params != null && !params.isEmpty()) {  
  106.             for (int i = 0; i < params.size(); i++) {  
  107.                 pstmt.setObject(index++, params.get(i)); // 填充佔位符  
  108.             }  
  109.         }  
  110.   
  111.         result = pstmt.executeUpdate();  
  112.         flag = result > 0 ? true : false;  
  113.         return flag;  
  114.   
  115.     }  
  116.   
  117.     /** 
  118.      * 查詢返回單條記錄 
  119.      *  
  120.      * @param sql 
  121.      * @param params 
  122.      * @return 
  123.      * @throws SQLException 
  124.      */  
  125.     public  Map<String, Object> findSimpleResult(String sql, List<Object> params)  
  126.             throws SQLException {  
  127.         Map<String, Object> map = new HashMap<String, Object>();  
  128.         pstmt = connection.prepareStatement(sql);  
  129.         int index = 1;  
  130.         if (params != null && !params.isEmpty()) {  
  131.             for (int i = 0; i < params.size(); i++) {  
  132.                 pstmt.setObject(index++, params.get(i));  
  133.             }  
  134.         }  
  135.         resultSet = pstmt.executeQuery(); // 返回查詢結果  
  136.   
  137.         ResultSetMetaData metaData = pstmt.getMetaData(); // 獲取 結果中,一行全部列的結果  
  138.         int cols_len = metaData.getColumnCount(); // 得到列的總數  
  139.   
  140.         while (resultSet.next()) {  
  141.             for (int i = 0; i < cols_len; i++) {  
  142.                 String col_name = metaData.getColumnName(i + 1); // 得到第i列的字段名稱  
  143.                 Object col_value = resultSet.getObject(col_name);// 返回 第i列的內容值  
  144.                 if (col_value == null) {  
  145.                     col_value = "";  
  146.                 }  
  147.                 map.put(col_name, col_value);  
  148.             }  
  149.   
  150.         }  
  151.   
  152.         return map;  
  153.     }  
  154.   
  155.     /** 
  156.      * 查詢返回多條記錄 
  157.      *  
  158.      * @param sql 
  159.      * @param params 
  160.      * @return 
  161.      * @throws SQLException 
  162.      */  
  163.     public List<Map<String, Object>> findMoreResult(String sql,  
  164.             List<Object> params) throws SQLException {  
  165.         List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
  166.         pstmt = connection.prepareStatement(sql);  
  167.         int index = 1; // 表示佔位符  
  168.         if (params != null && !params.isEmpty()) {  
  169.             for (int i = 0; i < params.size(); i++) {  
  170.                 pstmt.setObject(index++, params.get(i));  
  171.             }  
  172.         }  
  173.         resultSet = pstmt.executeQuery(); // 返回查詢結果集合  
  174.         ResultSetMetaData metaData = resultSet.getMetaData(); // 得到列的結果  
  175.   
  176.         while (resultSet.next()) {  
  177.             Map<String, Object> map = new HashMap<String, Object>();  
  178.             int cols_len = metaData.getColumnCount(); // 獲取總的列數  
  179.             for (int i = 0; i < cols_len; i++) {  
  180.                 String col_name = metaData.getColumnName(i + 1); // 獲取第 i列的字段名稱  
  181.                                                                     // ,列計算從1開始  
  182.                 Object col_value = resultSet.getObject(col_name); // 獲取第i列的內容值  
  183.                 if (col_value == null) {  
  184.                     col_value = "";  
  185.                 }  
  186.   
  187.                 map.put(col_name, col_value);  
  188.             }  
  189.             list.add(map);  
  190.         }  
  191.   
  192.         return list;  
  193.   
  194.     }  
  195.   
  196.     /** 
  197.      * 查詢返回單個JavaBean(使用java反射機制) 
  198.      *  
  199.      * @param sql 
  200.      * @param params 
  201.      * @param cls 
  202.      * @return 
  203.      * @throws Exception 
  204.      */  
  205.     public <T> T findSimpleRefResult(String sql, List<Object> params,  
  206.             Class<T> cls) throws Exception {  
  207.         T resultObject = null;  
  208.         int index = 1; // 佔位符  
  209.         pstmt = connection.prepareStatement(sql);  
  210.         if (params != null && !params.isEmpty()) {  
  211.             for (int i = 0; i < params.size(); i++) {  
  212.                 pstmt.setObject(index++, params.get(i)); // 填充佔位符  
  213.             }  
  214.         }  
  215.         resultSet = pstmt.executeQuery(); // 獲取查詢結果  
  216.   
  217.         ResultSetMetaData metaData = resultSet.getMetaData(); // 獲取列的信息  
  218.         int cols_len = metaData.getColumnCount(); // 獲取總的列數  
  219.         while (resultSet.next()) {  
  220.             // 經過反射機制建立實例  
  221.             resultObject = cls.newInstance(); // java反射機制  
  222.             for (int i = 0; i < cols_len; i++) {  
  223.                 String col_name = metaData.getColumnName(i + 1); // 獲取第i列的名稱  
  224.                 Object col_value = resultSet.getObject(col_name); // 獲取第i列的值  
  225.                 if (col_value == null) {  
  226.                     col_value = "";  
  227.                 }  
  228.                 Field field = cls.getDeclaredField(col_name);  
  229.                 field.setAccessible(true);// 打開 JavaBean的訪問 private權限  
  230.                 field.set(resultObject, col_value);  
  231.             }  
  232.   
  233.         }  
  234.   
  235.         return resultObject;  
  236.     }  
  237.   
  238.     /** 查詢返回多個JavaBean(經過java反射機制) 
  239.      * @param sql 
  240.      * @param params 
  241.      * @param cls 
  242.      * @return 
  243.      * @throws Exception 
  244.      */  
  245.     public <T> List<T> findMoreRefResult(String sql, List<Object> params,  
  246.             Class<T> cls) throws Exception {  
  247.         List<T> list = new ArrayList<T>();  
  248.         int index = 1; //佔位符  
  249.         pstmt = connection.prepareStatement(sql);  
  250.         if (params != null && !params.isEmpty()) {  
  251.             for (int i = 0; i < params.size(); i++) {  
  252.                 pstmt.setObject(index++, params.get(i));  
  253.             }  
  254.         }  
  255.         resultSet = pstmt.executeQuery(); // 返回查詢結果集合  
  256.   
  257.         ResultSetMetaData metaData = resultSet.getMetaData(); // 返回列的信息  
  258.         int cols_len = metaData.getColumnCount(); // 結果集中總的列數  
  259.         while (resultSet.next()) {  
  260.             // 經過反射機制建立一個java實例  
  261.             T resultObject = cls.newInstance();  
  262.             for (int i = 0; i < cols_len; i++) {  
  263.                 String col_name = metaData.getColumnName(i + 1); // 得到第i列的名稱  
  264.                 Object col_value = resultSet.getObject(col_name); // 得到第i列的內容  
  265.                 if (col_value == null) {  
  266.                     col_value = "";  
  267.                 }  
  268.                 Field field = cls.getDeclaredField(col_name);  
  269.                 field.setAccessible(true); // 打開JavaBean的訪問private權限  
  270.                 field.set(resultObject, col_value);  
  271.             }  
  272.             list.add(resultObject);  
  273.   
  274.         }  
  275.   
  276.         return list;  
  277.     }  
  278.       
  279.     /**關閉數據庫訪問 
  280.      * @throws SQLException 
  281.      */  
  282.     public void releaseConn(){  
  283.         if (resultSet!=null) {  
  284.             try {  
  285.                 resultSet.close();  
  286.             } catch (Exception e) {  
  287.                 // TODO: handle exception  
  288.                 e.printStackTrace();  
  289.             }  
  290.               
  291.         }  
  292.         if(stmt!=null){  
  293.               
  294.             try {  
  295.                 stmt.close();  
  296.             } catch (Exception e) {  
  297.                 // TODO: handle exception  
  298.                 e.printStackTrace();  
  299.             }  
  300.         }  
  301.         if (pstmt!=null) {  
  302.             try {  
  303.                 pstmt.close();  
  304.             } catch (Exception e) {  
  305.                 // TODO: handle exception  
  306.                 e.printStackTrace();  
  307.             }  
  308.         }  
  309.         if (connection!=null) {  
  310.             try {  
  311.                 connection.close();  
  312.             } catch (Exception e) {  
  313.                 // TODO: handle exception  
  314.                 e.printStackTrace();  
  315.             }  
  316.         }  
  317.     }  
  318.   
  319.       
  320. }  

 

17. DividePage.java

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. package com.util;  
  2.   
  3. public class DividePage {  
  4.   
  5.     private int pageSize ; //每一頁的記錄數  
  6.     private int totalRecord;//總記錄數  
  7.     private int currentPage;//當前第幾頁  
  8.     public DividePage(int pageSize, int totalRecord, int currentPage) {       
  9.         this.pageSize = pageSize;  
  10.         this.totalRecord = totalRecord;  
  11.         setCurrentPage(currentPage);          
  12.           
  13.     }  
  14.     public DividePage(int pageSize, int totalRecord) {        
  15.         this(pageSize,totalRecord,1);     
  16.           
  17.     }  
  18.       
  19.     //獲取總頁數  
  20.     public int getPageCount(){        
  21.         int pageCount = totalRecord/pageSize;  
  22.         int mod = totalRecord%pageSize;  
  23.         if (mod!=0) {  
  24.             pageCount++;  
  25.         }         
  26.         return pageCount;         
  27.     }  
  28.       
  29.     // mysql : select * from product limit 5,10  表示查詢記錄行 第6到15行。  
  30.       
  31.     //起始記錄從第幾行開始(mysql 記錄默認從第0行開始)  
  32.     public int fromIndex(){  
  33.           
  34.         return (currentPage-1)*pageSize;  
  35.     }  
  36.       
  37.     //要查詢的的尾記錄相對於起始記錄的偏移量,即一頁的記錄數  
  38.     public int toIndex(){  
  39.         return pageSize;  
  40.     }  
  41.       
  42.     public void setCurrentPage( int currentPage){         
  43.           
  44.         if (getPageCount()!=0) {//有記錄  
  45.               
  46.             int validPage = currentPage<1?1:currentPage;  
  47.             validPage = validPage>getPageCount()?getPageCount():validPage;         
  48.             this.currentPage = validPage;  
  49.         } else{ // 0條記錄  
  50.             this.currentPage = 1;  
  51.         }  
  52.           
  53.     }  
  54.     public int getPageSize() {  
  55.         return pageSize;  
  56.     }  
  57.     public void setPageSize(int pageSize) {  
  58.         this.pageSize = pageSize;  
  59.     }  
  60.     public int getTotalRecord() {  
  61.         return totalRecord;  
  62.     }  
  63.     public void setTotalRecord(int totalRecord) {  
  64.         this.totalRecord = totalRecord;  
  65.     }  
  66.     public int getCurrentPage() {  
  67.         return currentPage;  
  68.     }  
  69.       
  70.       
  71. }  

 

18. UUIDTools.java

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. package com.util;  
  2.   
  3. import java.util.UUID;  
  4.   
  5. public class UUIDTools {  
  6.   
  7.     public UUIDTools() {  
  8.         // TODO Auto-generated constructor stub  
  9.     }  
  10.       
  11.     /**返回一個 6位的字符串 
  12.      * @return 
  13.      */  
  14.     public static String getUUID(){  
  15.           
  16.         UUID uuid = UUID.randomUUID();  
  17.         return uuid.toString().replaceAll("-", "").substring(0, 6);   
  18.           
  19.     }  
  20.   
  21. }  

 

20. LogoutAction.java

[java] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. package com.logout;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.PrintWriter;  
  5.   
  6. import javax.servlet.ServletException;  
  7. import javax.servlet.http.HttpServlet;  
  8. import javax.servlet.http.HttpServletRequest;  
  9. import javax.servlet.http.HttpServletResponse;  
  10.   
  11. public class LogoutAction extends HttpServlet {  
  12.   
  13.     /** 
  14.      * Constructor of the object. 
  15.      */  
  16.     public LogoutAction() {  
  17.         super();  
  18.     }  
  19.   
  20.     /** 
  21.      * Destruction of the servlet. <br> 
  22.      */  
  23.     public void destroy() {  
  24.         super.destroy(); // Just puts "destroy" string in log  
  25.         // Put your code here  
  26.     }  
  27.   
  28.     /** 
  29.      * The doGet method of the servlet. <br> 
  30.      * 
  31.      * This method is called when a form has its tag value method equals to get. 
  32.      *  
  33.      * @param request the request send by the client to the server 
  34.      * @param response the response send by the server to the client 
  35.      * @throws ServletException if an error occurred 
  36.      * @throws IOException if an error occurred 
  37.      */  
  38.     public void doGet(HttpServletRequest request, HttpServletResponse response)  
  39.             throws ServletException, IOException {  
  40.         this.doPost(request, response);  
  41.     }  
  42.   
  43.     /** 
  44.      * The doPost method of the servlet. <br> 
  45.      * 
  46.      * This method is called when a form has its tag value method equals to post. 
  47.      *  
  48.      * @param request the request send by the client to the server 
  49.      * @param response the response send by the server to the client 
  50.      * @throws ServletException if an error occurred 
  51.      * @throws IOException if an error occurred 
  52.      */  
  53.     public void doPost(HttpServletRequest request, HttpServletResponse response)  
  54.             throws ServletException, IOException {  
  55.   
  56.         response.setContentType("text/html;charset=utf-8");  
  57.         request.setCharacterEncoding("utf-8");  
  58.         response.setCharacterEncoding("utf-8");  
  59.         String path = request.getContextPath();  
  60.         String action_flag = request.getParameter("action_flag");  
  61.         if (action_flag.equals("logout")) {  
  62.             request.getSession().removeAttribute("username");  
  63.             response.sendRedirect(path+"/index.jsp");  
  64.         }  
  65.     }  
  66.   
  67.     /** 
  68.      * Initialization of the servlet. <br> 
  69.      * 
  70.      * @throws ServletException if an error occurs 
  71.      */  
  72.     public void init() throws ServletException {  
  73.         // Put your code here  
  74.     }  
  75.   
  76. }  

 

21. web.xml

[html] view plain copy

在CODE上查看代碼片派生到個人代碼片

  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="3.0"   
  3.     xmlns="http://java.sun.com/xml/ns/javaee"   
  4.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
  5.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  6.     http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">  
  7.   <display-name></display-name>  
  8.   <servlet>  
  9.     <description>This is the description of my J2EE component</description>  
  10.     <display-name>This is the display name of my J2EE component</display-name>  
  11.     <servlet-name>RegisterAction</servlet-name>  
  12.     <servlet-class>com.register.RegisterAction</servlet-class>  
  13.   </servlet>  
  14.   <servlet>  
  15.     <description>This is the description of my J2EE component</description>  
  16.     <display-name>This is the display name of my J2EE component</display-name>  
  17.     <servlet-name>LoginAction</servlet-name>  
  18.     <servlet-class>com.login.LoginAction</servlet-class>  
  19.   </servlet>  
  20.   <servlet>  
  21.     <description>This is the description of my J2EE component</description>  
  22.     <display-name>This is the display name of my J2EE component</display-name>  
  23.     <servlet-name>ProductAction</servlet-name>  
  24.     <servlet-class>com.product.ProductAction</servlet-class>  
  25.   </servlet>  
  26.   <servlet>  
  27.     <description>This is the description of my J2EE component</description>  
  28.     <display-name>This is the display name of my J2EE component</display-name>  
  29.     <servlet-name>LogoutAction</servlet-name>  
  30.     <servlet-class>com.logout.LogoutAction</servlet-class>  
  31.   </servlet>  
  32.   
  33.   
  34.     
  35.   <servlet-mapping>  
  36.     <servlet-name>RegisterAction</servlet-name>  
  37.     <url-pattern>/servlet/RegisterAction</url-pattern>  
  38.   </servlet-mapping>  
  39.   <servlet-mapping>  
  40.     <servlet-name>LoginAction</servlet-name>  
  41.     <url-pattern>/servlet/LoginAction</url-pattern>  
  42.   </servlet-mapping>  
  43.   <servlet-mapping>  
  44.     <servlet-name>ProductAction</servlet-name>  
  45.     <url-pattern>/servlet/ProductAction</url-pattern>  
  46.   </servlet-mapping>  
  47.   <servlet-mapping>  
  48.     <servlet-name>LogoutAction</servlet-name>  
  49.     <url-pattern>/servlet/LogoutAction</url-pattern>  
  50.   </servlet-mapping>  
  51.    
  52.     
  53.   <!-- 配置 過濾器 -->  
  54.     
  55.   <filter>  
  56.     <filter-name>MyFilter</filter-name>  
  57.     <filter-class>com.filter.MyFilter</filter-class>  
  58.   </filter>  
  59.    
  60.   <filter-mapping>  
  61.     <filter-name>MyFilter</filter-name>  
  62.     <!-- /*表示過濾全部頁面 ,/main.jsp 表示只過濾main.jsp頁面-->  
  63.     <url-pattern> /main.jsp</url-pattern>     
  64.   </filter-mapping>  
  65.    <filter-mapping>  
  66.     <filter-name>MyFilter</filter-name>  
  67.     <!-- /*表示過濾全部頁面 /addProduct.jsp 表示只過濾addProduct.jsp頁面-->  
  68.     <url-pattern>/addProduct.jsp</url-pattern>     
  69.   </filter-mapping>  
  70.     
  71.   
  72.     
  73.   <welcome-file-list>  
  74.     <welcome-file>index.jsp</welcome-file>  
  75.   </welcome-file-list>  
  76. </web-app>  

注意:

1. 使用過濾器,要引入jar包:servlet-2_5-api.jar

2. 使用jdbc鏈接MySQL , 要引入jar包:mysql-connector-java-5.1.7-bin.jar

3. 文件上傳,要引入2個jar包:

commons-fileupload-1.3.1.jar 和

commons-io-2.4.jar

相關文章
相關標籤/搜索