hooyantsing's Blog

第67次课程_jndi_验证码_分页与文件上传等组件技术

字数统计: 3.8k阅读时长: 21 min
2019/10/20

源辰76班

第67次课程

2019.10.20

内容

jndi_验证码_分页与文件上传等组件技术[廖彦]

1.连接池的创建与使用

**3de9d0a8c0e9a77f064932d4b758d5bd.png

**

context.xml

META-INF服务器配置目录

配置连接池参数

1
<?xml version="1.0" encoding="UTF-8"?><Context><!--    *连接池    auth:容器 固定值    driverClassName:驱动地址    maxIdle:空闲连接    maxTotal:最多创建连接    maxWaitMillis:如果连接都被占用,等待时间。 "-1":一直等待 单位毫秒    name:本服务名  后续需要此服务时 引用此名称A    username:数据库用户名    password:数据库用户密码    url:数据库连接地址 -->    <Resource       auth="Container"       driverClassName="com.mysql.jdbc.Driver"       maxIdle="30"       maxTotal="50"       maxWaitMillis="-1"       name="mysql/damai"       username="root"       password="a"       type="javax.sql.DataSource"       url="jdbc:mysql://localhost:3306/demo-damai"    /></Context>

web.xml

WEB-INF页面配置目录

页面配置文件

1
<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">  <display-name>191016_demo-damai</display-name>  <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list>   <!-- 引用JNDI服务 -->  <resource-ref>    <!-- 描述 -->    <description>大麦数据库连接</description>    <!-- 引用的服务名 -->    <res-ref-name>mysql/damai</res-ref-name>    <res-type>javax.sql.DataSource</res-type>    <res-auth>Container</res-auth>  </resource-ref></web-app>

DBHelper.java

工具类

根据连接池的特点已重构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package com.yc.damai.util;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class DBhelper {
    
    public static Connection getConnection() throws SQLException {
        try {
            //创建上下文对象
            Context ctx = new InitialContext();
            //引入服务规则:java:comp/env/ + 服务名称
            DataSource ds = (DataSource) ctx.lookup("java:comp/env/mysql/damai");
            //从连接池中取出一个连接返回
            return ds.getConnection();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    
    //增删改
    public static int update(String sql,Object...paramArray) {
        Connection conn = null;
        try {
            conn = getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            for(int i=0;i<paramArray.length;i++) {
                ps.setObject(i+1, paramArray[i]);
            }
            return ps.executeUpdate();
        } catch(Exception e){
            throw new RuntimeException(e);
        } finally {
            try {
                if(conn!=null) {
                    conn.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
    
    //查
    public static List<Map<String,Object>> selectList(String sql,Object...paramArray) {
        Connection conn = null;
        try {
            conn = getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            for(int i=0;i<paramArray.length;i++) {
                ps.setObject(i+1, paramArray[i]);
            }
            ResultSet rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            List<Map<String,Object>> ret = new ArrayList<>();
            while(rs.next()) {
                Map<String,Object> row = new LinkedHashMap<>();
                for(int i=1;i<rsmd.getColumnCount();i++) {
                    String columnName = rsmd.getColumnName(i);
                    Object columnValue = rs.getObject(i);
                    row.put(columnName, columnValue);
                }
                ret.add(row);
            }
            return ret;
        } catch(Exception e){
            throw new RuntimeException(e);
        } finally {
            try {
                if(conn!=null) {
                    conn.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
    
    //查询一条记录
    public static Map<String,Object> queryOne (String sql,Object...paramArray){
        Connection conn = null;
        try {
            conn = getConnection();
            PreparedStatement ps = conn.prepareStatement(sql);
            for(int i=0;i<paramArray.length;i++) {
                ps.setObject(i+1, paramArray[i]);
            }
            ResultSet rs = ps.executeQuery();
            ResultSetMetaData rsmd = rs.getMetaData();
            if(rs.next()) {
                Map<String,Object> row = new LinkedHashMap<>();
                for(int i=1;i<=rsmd.getColumnCount();i++) {
                    String columnName = rsmd.getColumnName(i);
                    Object columnValue = rs.getObject(i);
                    row.put(columnName, columnValue);
                }
                return row;
            }
            return null;
        } catch(Exception e){
            throw new RuntimeException(e);
        } finally {
            try {
                if(conn!=null) {
                    conn.close();
                }
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
    }
    
    //分页 MySQL中不适用
    public static List<Map<String,Object>> queryPage (
            String sql,int page,int rows,Object...paramArray){
        int startrow = (page - 1) * rows;
        int endrow = page * rows;
        sql = "select t.*\n" +
              " from ( select t.*,rownum rn from ( "+sql+") t where rownum <= ?) t\n" +
              " where t.rn > ?";    
        Object[] newParamArray = new Object[paramArray.length + 2];
        System.arraycopy(paramArray, 0, newParamArray, 0, paramArray.length);
        newParamArray[newParamArray.length - 2] = endrow;
        newParamArray[newParamArray.length - 1] = startrow;

        return selectList(sql,newParamArray);
    }
    
    //使用聚合函数查询
    public static Object selectValue(String sql,Object...paramArray) {
        Map<String,Object> row = queryOne(sql,paramArray);
        if(row==null) {
            return null;
        }else {
            for(Map.Entry<String, Object> e:row.entrySet()) {
                return e.getValue();
            }
        }
        return null;
    }
}

2.MySQL分页

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
<%@page import="java.util.*"%>
<%@page  import="com.yc.damai.util.DBhelper"%>
<%@page  import="com.sun.corba.se.spi.ior.iiop.RequestPartitioningComponent"%>
<%@ page language="java"  contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"  content="text/html; charset=UTF-8"/>
<title>大麦商城</title>
<link href="css/slider.css" rel="stylesheet"  type="text/css"/>
<link href="css/common.css" rel="stylesheet"  type="text/css"/>
<link href="css/index.css" rel="stylesheet"  type="text/css"/>
</head>
<body>
<div class="container header">
    
    
<div class="span5">
       <div class="logo">
           <a href="index.html">
               <img  src="image/r___________renleipic_01/logo.png" alt="依依不舍"/>
           </a>
       </div>
    </div>
    <div class="span9">
<div class="headerAd">
    <img src="image/header.jpg" width="320"  height="50" alt="正品保障" title="正品保障"/>
</div> </div>
<div class="span10 last">
       <div class="topNav clearfix">
           <ul>
               
                  <li id="headerLogin"  class="headerLogin" style="display:  list-item;">
                      Song|
                  </li>
                  <li id="headerLogin"  class="headerLogin" style="display:  list-item;">
                      <a  href="olist.html">我的订单</a>|
                  </li>
                  <li id="headerRegister"  class="headerRegister" style="display:  list-item;">
                  <a href="index.html">退出</a>|
               </li>
               
               
               
               
               <li id="headerUsername"  class="headerUsername"></li>
               <li id="headerLogout"  class="headerLogout">
                  <a>[退出]</a>|
               </li>
                      <li>
                          <a>会员中心</a>
                          |
                      </li>
                      <li>
                          <a>购物指南</a>
                          |
                      </li>
                      <li>
                          <a>关于我们</a>
                          
                      </li>
           </ul>
       </div>
       <div class="cart">
           <a  href="cart.html">购物车</a>
       </div>
           <div class="phone">
               客服热线:
               <strong>96008/53277764</strong>
           </div>
    </div>
    
<div class="span24">
       <ul class="mainNav">
                  <li>
                      <a  href="index.html">首页</a>
                      |
                  </li>
                  
                  <li>
<a href="clist.html?1&pageIndex=1">
                  女装男装
</a>
                  |</li>
                  
                  <li>
<a href="clist.html?2&pageIndex=1">
                  鞋靴箱包
</a>
                  |</li>
                  
                  <li>
<a href="clist.html?3&pageIndex=1">
                  运动户外
</a>
                  |</li>
                  
                  <li>
<a href="clist.html?4&pageIndex=1">
                  珠宝配饰
</a>
                  |</li>
                  
                  <li>
<a href="clist.html?5&pageIndex=1">
                  手机数码
</a>
                  |</li>
                  
                  <li>
<a href="clist.html?6&pageIndex=1">
                  家电办公
</a>
                  |</li>
                  
                  <li>
<a href="clist.html?7&pageIndex=1">
                  护肤彩妆
</a>
                  |</li>
                          
       </ul>
    </div>
</div>
<div class="container index">
       
       <div class="span24">
           <div id="hotProduct"  class="hotProduct clearfix">
                  <div class="title">
                      <strong>热门商品</strong>
                      <!-- <a   target="_blank"></a> -->
                  </div>
                  <ul class="tab">
                          <li  class="current">
                              <a href="./蔬菜分类.htm?tagIds=1" target="_blank"></a>
                          </li>
                          <li>
                              <a   target="_blank"></a>
                          </li>
                          <li>
                              <a  target="_blank"></a>
                          </li>
                  </ul>
                      <ul class="tabContent"  style="display: block;">
                          <%
                              String  paramNumber =  request.getParameter("pageNumber");
                              String  paramRows =  request.getParameter("pageRows");
                              //第几页
                              int pageNumber  = paramNumber == null ? 1 :  Integer.parseInt(paramNumber);
                              //每页行数
                              int pageRows =  paramRows == null ? 10 :  Integer.parseInt(paramRows);
                              //第几页开始查询
                              int beginRow =  (pageNumber - 1) * 10;
                              
                              String sql =  "select count(*) from product where is_hot =  1";
                              //
                              Object value =  DBhelper.selectValue(sql);
                              int totalRows  = Integer.parseInt(""+value);
                              int totalPage  = totalRows / pageRows;
                              totalPage +=  totalRows % pageRows == 0 ? 0 : 1;
                              
                              
                              sql = "select  * from product where is_hot=1 limit ?,?";
                              List<Map<String,Object>> list =
                                     DBhelper.selectList(sql, beginRow,pageRows);
                              for(Map<String,Object> m : list){
                          %>
                              <li>
                                     <a  target="_blank" href="detail.html?1"><img  src="<%=m.get("image") %>" style="display:  block;"></a>
                              </li>
                          <%} %>
                          
                      </ul>
                      <a  href="index.jsp?pageNumber=1">首页</a>
                      <a  href="index.jsp?pageNumber=<%=pageNumber<=1  ? 1 : pageNumber-1 %>">上一页</a>
                      <a  href="index.jsp?pageNumber=<%=pageNumber>=totalPage ? totalPage : pageNumber+1 %>">下一页</a>
                      <a  href="index.jsp?pageNumber=<%=totalPage%>">尾页</a>
           </div>
       </div>
       <div class="span24">
           <div id="newProduct"  class="newProduct clearfix">
                  <div class="title">
                      <strong>最新商品</strong>
                      <a   target="_blank"></a>
                  </div>
                  <ul class="tab">
                          <li  class="current">
                              <a href="./蔬菜分类.htm?tagIds=2" target="_blank"></a>
                          </li>
                          <li>
                              <a   target="_blank"></a>
                          </li>
                          <li>
                              <a  target="_blank"></a>
                          </li>
                  </ul>             
                       <ul  class="tabContent" style="display: block;">
                       
                                 <li>
                                     <a  href="detail.html?72" target="_blank"><img  src="products/1/cs10011.jpg" style="display:  block;"></a>
                                 </li>
                      
                                 <li>
                                     <a  href="detail.html?57" target="_blank"><img  src="products/1/cs60006.png" style="display:  block;"></a>
                                 </li>
                      
                                 <li>
                                     <a  href="detail.html?4" target="_blank"><img  src="products/1/cs10004.jpg" style="display:  block;"></a>
                                 </li>
                      
                                 <li>
                                     <a  href="detail.html?45" target="_blank"><img  src="products/1/cs50004.png" style="display:  block;"></a>
                                 </li>
                      
                                 <li>
                                     <a  href="detail.html?51" target="_blank"><img  src="products/1/cs50010.png" style="display:  block;"></a>
                                 </li>
                      
                                 <li>
                                     <a  href="detail.html?68" target="_blank"><img  src="products/1/cs70007.png" style="display:  block;"></a>
                                 </li>
                      
                                 <li>
                                     <a  href="detail.html?60" target="_blank"><img  src="products/1/cs60009.png" style="display:  block;"></a>
                                 </li>
                      
                                 <li>
                                     <a  href="detail.html?30" target="_blank"><img  src="products/1/cs30010.png" style="display:  block;"></a>
                                 </li>
                      
                                 <li>
                                     <a  href="detail.html?6" target="_blank"><img  src="products/1/cs10006.jpg" style="display:  block;"></a>
                                 </li>
                      
                                 <li>
                                     <a  href="detail.html?2" target="_blank"><img  src="products/1/cs10002.jpg" style="display:  block;"></a>
                                 </li>
                      
                      </ul>
           </div>
       </div>
       <div class="span24">
           <div class="friendLink">
               <dl>
                  <dd>新手指南</dd>
                          <dd>
                              <a   target="_blank">支付方式</a>
                              |
                          </dd>
                          <dd>
                              <a   target="_blank">配送方式</a>
                              |
                          </dd>
                          <dd>
                              <a   target="_blank">售后服务</a>
                              |
                          </dd>
                          <dd>
                              <a   target="_blank">购物帮助</a>
                              |
                          </dd>
                          <dd>
                              <a   target="_blank">蔬菜卡</a>
                              |
                          </dd>
                          <dd>
                              <a   target="_blank">礼品卡</a>
                              |
                          </dd>
                          <dd>
                              <a  target="_blank">银联卡</a>
                              |
                          </dd>
                          <dd>
                              <a   target="_blank">亿家卡</a>
                              |
                          </dd>
                          
                  <dd class="more">
                      <a >更多</a>
                  </dd>
               </dl>
           </div>
       </div>
    </div>
<div class="container footer">
    <div class="span24">
       <div class="footerAd">
                  <img  src="image/footer.jpg" width="950"  height="52" alt="我们的优势" title="我们的优势">
</div> </div>
    <div class="span24">
       <ul class="bottomNav">
                  <li>
                      <a>关于我们</a>
                      |
                  </li>
                  <li>
                      <a>联系我们</a>
                      |
                  </li>
                  <li>
                      <a>招贤纳士</a>
                      |
                  </li>
                  <li>
                      <a>法律声明</a>
                      |
                  </li>
                  <li>
                      <a>友情链接</a>
                      |
                  </li>
                  <li>
                      <a target="_blank">支付方式</a>
                      |
                  </li>
                  <li>
                      <a target="_blank">配送方式</a>
                      |
                  </li>
                  <li>
                      <a>服务声明</a>
                      |
                  </li>
                  <li>
                      <a>广告声明</a>
                      
                  </li>
       </ul>
    </div>
    <div class="span24">
       <div class="copyright">Copyright ©  2005-2013 大麦商城 版权所有</div>
    </div>
</div>
</body></html>

3.上传文件

提示:首先在”WebContent”目录下创建”upload”目录(文件夹)。

tmp_upload.jsp

上传文件页面

上传文件的表单(form),不是普通的文本表单

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%@ page language="java"  contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01  Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"  content="text/html; charset=utf-8">
<title>文件上传</title>
</head>
<body>
<!-- method提交方式  enctype编码格式  -->
<form action="tmp_doupload.jsp"  method="post" enctype="multipart/form-data">
    <input type="file" name="file"  multiple>    //multiple 可同时选中多个文件并上传

    <input type="submit" value="上传">

</form>
</body>
</html>

tmp_doupload.jsp

上传文件后台

需要导入jsmartcom_zh_CN jar包

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
<%@page import="java.util.ArrayList"%>
<%@page import="com.jspsmart.upload.Files"%>
<%@page  import="com.jspsmart.upload.SmartUpload"%>
<%@ page language="java"  contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01  Transitional//EN"  "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type"  content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<%
    //创建文件上传对象
    SmartUpload su = new SmartUpload();
    //初始化 传入页面上下文对象
    su.initialize(pageContext);
    //设置上传的配置信息
    //限定文件名后缀
    su.setAllowedFilesList("jpg,png,gif,bmp");
    //限定大小
    su.setMaxFileSize(1024 * 1024 * 10);
    //执行上传
    su.upload();
    
    Files files = su.getFiles();
    ArrayList<String> fileList = new  ArrayList<String>();
    
    for(int i=0;i<files.getCount();i++){
       String filename =  files.getFile(i).getFileName();
       System.out.println(filename);
       //使用application(应用上下文) web路径  转换成 磁盘路径
       //例:/upload ==>  d:/dev/tomcat/webapps/damai/upload
       String diskPath =  application.getRealPath("/upload");
       System.out.println(diskPath);
       files.getFile(i).saveAs(diskPath+"/"+filename);
       
       //将上传的文件的web路径添加到
       fileList.add("upload/" + filename);
    }
%>
文件上传成功
<%for(String filepath:fileList) {%>
    <img alt="" src="<%=filepath %>"  width="200px">
<%} %>
</body>
</html>

工具jar包:

%!(EXTRA markdown.ResourceType=, string=, string=)

CATALOG