JSP学习笔记(四) JSP实现文件上传 JSP数据验证 JSP分页实现

1 实现文件上传

<form action="" method="POST" enctype="multipart/form-data">
file:<input type="file" name="file"/>
<br/>
<input type="submit"/>
</form>
观测HTTP Monitor
POST /fileUpload/upload.jsp HTTP/1.1
Accept: image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*
Referer: http://127.0.0.1:8082/fileUpload/
Accept-Language: zh-cn
Content-Type: multipart/form-data; boundary=---------------------------7d73e2c110626
Accept-Encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1)
Host: 127.0.0.1
Content-Length: 234
Connection: Keep-Alive
Cache-Control: no-cache

-----------------------------7d73e2c110626
Content-Disposition: form-data; name="file"; filename="C:\Documents and Settings\Administrator\桌面\test.txt"
Content-Type: text/plain

abc
-----------------------------7d73e2c110626--


1)获得文件边界标记
   if (contentType.indexOf("multipart/form-data") >= 0) {
      boundary = contentType.substring(contentType.indexOf("boundary=") + 9);
    }

2)获得content的长度
int contentLength = request.getContentLength();

3)  //以流的形式接收http数据
    InputStream is = request.getInputStream();
    byte dataBuffer[] = new byte[contentLength];
    int dataRead = 0;
    int totalDataRead = 0;
    while ( (dataRead = is.read(dataBuffer, totalDataRead, contentLength)) !=
           -1) {
      totalDataRead += dataRead;
    }
4)    //取得文件名
    String file = new String(dataBuffer);
    String saveFile = file.substring(file.indexOf("filename=\"") + 10);
    saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
    saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,
                                  saveFile.indexOf("\""));
5)    //寻找文件起始位置
    int pos = file.indexOf("filename=");
    pos = file.indexOf("\n", pos) + 1;//换行
    pos = file.indexOf("\n", pos) + 1;//换行
    pos = file.indexOf("\n", pos) + 1;//换行
   
6)   //文件的结束位置(boundary多两个--加上一个换行符合)
int boundaryEnd = file.indexOf(boundary, pos) - 4;

7)  可以处理文本文件和二进制文件(以byte为单位)
    //起始点
    int start = (file.substring(0, pos)).getBytes().length;
    //结束点
    int end = (file.substring(0, boundaryEnd)).getBytes().length;
   
8)保存文件
    FileOutputStream fos = new FileOutputStream("d:\\temp\\" + saveFile);
    fos.write(dataBuffer, start, (end - start));
    fos.close();
   
2 数据验证

如何完成Web App中的数据验证工作

1)输入格式验证: 输入域不能为空,只能是数字,数据长度大于5等等
JavaScript客户端完成(验证框架,负责客户端方面的验证)

2)业务逻辑验证: 后台数据库要求提交数据唯一性
Java服务器端完成(没有现成的框架,因为不同的项目有不同的业务规则)


3 分页实现
查询数据库时,如果满足条件的记录很多,该如何返回给页面?
查询分页
1)一次性从数据库中查出所有信息,在内存中作分页(缓存)
特点:速度非常快,消耗资源大(内存?)
2)分多次查询数据库,一次查询的数据量就是一个页面可以显示的数据量
特点:销毁资源少,相对来说速度慢
3)折衷的方案(一次只取n页,1<n<总页数)(部分缓存)
特点:中庸之道

rows:数据库表中记录总行数
totalPage:总页数           导出属性(可以由其他属性计算而得)
size:每页显示的记录数目
curPageNo:当前页
startRowNo:当前页在数据库中的起始行号  导出属性

你可能感兴趣的:(JavaScript,jsp,框架,Excel,Flash)