一.用mysql建立数据库及其表
create database file set gbk;
create table user(id int not null primary key auto_increment,username varchar(20),password varchar(20));
create table file(fileid int not null primary key auto_increment,filesavename varchar(100),filename varchar(100),filetype varchar(100),filesize varchar(50),fileinfo text,fileuptime varchar(30),fileip varchar(30),filetimes varchar(30),filetag varchar(30));
二.源码实例
1.表现层页面
(1)login.jsp(登录页面)
<%@ page language="java" import="java.util.*" pageEncoding="gbk"%> <% String path = request.getContextPath(); %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>登陆首页</title> <mce:style type="text/css"><!-- .button1 { background: #ebebeb; border: 1px solid #888888; color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: 12px; height: 23px; cursor: pointer } --></mce:style><style type="text/css" mce_bogus="1">.button1 { background: #ebebeb; border: 1px solid #888888; color: #333333; font-family: Arial, Helvetica, sans-serif; font-size: 12px; height: 23px; cursor: pointer }</style> <mce:script type="text/javascript"><!-- history.go(1); // --></mce:script> <mce:script language="javascript" src="<%=path%><!-- /js/zxc.js"> // --></mce:script> </head> <body style="background:url(./images/yun.jpg)" mce_style="background:url(images/yun.jpg)"onload="alertWin('登陆','这里是内容,弹出层可以移动,弹出层可以关闭',450,160);"> <input type="hidden" id="path"value="<%=path%>"/> <div id="logincontent" style="display: none" mce_style="display: none"> <form id="loginForm" action='<%=path%>/login.do' method="post"> <table> <tr> <td> <label> 用户名: </label> </td> <td align='left'> <input type='text' name='username'/> </td> <td> <p id="errorname"></p> </td> </tr> <tr> <td> <label> 密 码: </label> </td> <td align='left'> <input type='password' name='password' /> </td> <td /> </tr> <tr> <td> <label> 验证码: </label> </td> <td align='left'> <input type='text' name='randcode' /> </td> <td> <img id="imgCode" style="border: 1px solid #C6D8E5;" mce_style="border: 1px solid #C6D8E5;" src="<%=path%>/servlet/textBufferedImage?timestampt=" +<%=new java.util.Date().getTime()%> /> </td> </tr> <tr> <td /> <td align='left'> <input class="button1" type='submit' value='登陆' /> <input class="button1" type='reset' value='重置' /> </td> <td /> </tr> </table> </form> </div> </body> </html>
(2)index.jsp(首页)
<%@ page language="java" pageEncoding="gbk" isELIgnored="false"%> <%@page import="bean.FileInfo"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%> <% String path = request.getContextPath(); %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base target="_self"/> <title>首页</title> <mce:style type="text/css"><!-- body { font-size: 10pt; text-align: center; } dl { margin: 0; } dt { background-color: #666; color: #fff; margin: 1px; padding: 0 3px; } dd { margin: 3px; } div { margin: auto; line-height: 150%; text-align: left; width: 600px; border: 1px solid #049ed0; } #postBox { margin-top: 10px; } dd.button { text-align: center; } dd.button input { margin: 0 20px; } .messageHistabs { width:60%; } .messageHistabs li { margin:0 2px 0 0; background:#dcecf8 url(../images/steps_right.gif) no-repeat right top; float:left; cursor:pointer; text-align:left; } ul, ol { list-style:none outside none; } th{ color:#049ed0; text-align:center; } td{ text-align:left; } a{ color:#049ed0; } --></mce:style><style type="text/css" mce_bogus="1">body { font-size: 10pt; text-align: center; } dl { margin: 0; } dt { background-color: #666; color: #fff; margin: 1px; padding: 0 3px; } dd { margin: 3px; } div { margin: auto; line-height: 150%; text-align: left; width: 600px; border: 1px solid #049ed0; } #postBox { margin-top: 10px; } dd.button { text-align: center; } dd.button input { margin: 0 20px; } .messageHistabs { width:60%; } .messageHistabs li { margin:0 2px 0 0; background:#dcecf8 url(../images/steps_right.gif) no-repeat right top; float:left; cursor:pointer; text-align:left; } ul, ol { list-style:none outside none; } th{ color:#049ed0; text-align:center; } td{ text-align:left; } a{ color:#049ed0; }</style> <mce:script language="javascript" src="<%=path%><!-- /js/zxc.js"> // --></mce:script> </head> <body bgcolor="#F4F4F4"> <mce:script type="text/javascript"><!-- history.go(1); // --></mce:script> <h1><font color="#049ed0" face="Arial">简易文件<a target="_self"style="color:#049ed0;"href="javascript:openUpwin()">上传</a>与下载系统</font></h1> <span style="color:#049ed0;float:right;text-decoration:underline;cursor:pointer;" mce_style="color:#049ed0;float:right;text-decoration:underline;cursor:pointer;"><a onclick="quit();"style="color:#049ed0;">退出系统</a></span> <input type="hidden" id="path"value="<%=path%>"/> <form name="FileListForm" id="FileListForm" action="<%=path%>/fileUpDownLoad.do?method=getFileList"method="post"> <font color="#141F78" size="5">文件列表</font> <table id="me" border="0" align="center" style="border-spacing:10" mce_style="border-spacing:10"> <thead> <tr> <th > <span>序号</span> </th> <th> <span>文件名称</span> </th> <th> <span>文件描述</span> </th> <th> <span>文件大小</span> </th> <th> <span>下载次数</span> </th> <th> <span>上传者IP</span> </th> <th> <span>上传时间</span> </th> <th> <span>操作</span> </th> </tr> </thead> <c:if test="${not empty pageList}"> <tbody> <c:forEach var="file" varStatus="fvs" items="${pageList.dataArray}"> <tr> <td class="indent"> ${fvs.index+1+(pageList.page-1)*pageList.pageSize} </td> <td class="indent"> ${file.fileName} </td> <td class="indent"> <c:choose> <c:when test="${fn:length(file.fileInfo)>10}"> <a href="javascript:showInfo('${file.fileInfo}')" mce_href="javascript:showInfo('${file.fileInfo}')"style="color:#049ed0;text-decoration:underline;cursor:pointer;">${fn:substring(file.fileInfo, 0, 10)}...</a> </c:when> <c:otherwise> ${file.fileInfo} </c:otherwise> </c:choose> </td> <td > ${file.fileSize} </td> <td style="text-align:center" mce_style="text-align:center"> ${file.fileTimes} </td> <td> ${file.fileIp} </td> <td > ${file.fileUptime} </td> <td class="indent"> <a href="javascript:download('${file.fileSavename}')">下载</a> <a href="javascript:del('${file.fileSavename}')" mce_href="javascript:del('${file.fileSavename}')">删除</a> </td> </tr> </c:forEach> </tbody> </c:if> </table> <c:if test="${not empty pageList}"> ${footer} </c:if> </form> </body> </html>
(3)uploadfile.jsp(文件上传页面)
<%@ page contentType="text/html;charset=gbk" pageEncoding="gbk"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core"prefix="c"%>
<%@ page isELIgnored="false"%>
<html>
<head>
<title>上传文件</title>
<link type="text/css" rel="stylesheet" href="<%=request.getContextPath()%>/css/style.css">
<script type="text/javascript">
function checkForm(form){
if(form.file1.value.match(/^/s*/)&&form.file2.value.match(/^/s*/)){
document.getElementById("messageid").innerHTML="<img src='<%=request.getContextPath()%>/image/error.gif'/><font color='red'>上传路径不能为空!</font>";
return false;
}else if(!form.file1.value.match(/^/s*/)){
if(form.tag1.value.match(/^/s*/)){
document.getElementById("tag1id").innerHTML="<img src='<%=request.getContextPath()%>/image/error.gif'/><font color='red'>关键字不能为空!</font>";
}
}
return true;
}
</script>
</head>
<body bgcolor="#E1E1E1">
<script type="text/javascript">
history.go(1);
</script>
<center>
<form action="<c:url value='/fileUpDownLoad.do?method=uploadFile'/>" enctype="multipart/form-data" method="post" >
<table width="100%" border="1" class="TableStyle">
<tr class="column_title">
<td >
<font color="#215DC6">●每个文件长度最大允许为20兆!</font><br>
<div id="messageid">
<c:if test="${!empty message}">
<font color='red'>${message}</font>
</c:if>
</div>
<b class="column_title">文件路径1:</b><br>
<input type="file" name="file1" size="60" ><br>
<b class="column_title">文件描述1:</b><br>
<textarea rows="5" cols="69" name="fileinfo1"></textarea><br>
<hr color="#049ED0">
<b class="column_title">文件路径2:</b><br>
<input type="file" name="file2" size="60" ><br>
<b class="column_title">文件描述2:</b><br>
<textarea rows="5" cols="69" name="fileinfo2"></textarea><br>
<input type="submit" value="上传文件"/>
<input type="button" value="返回列表" onclick="window.opener.location.href='<c:url value="/fileUpDownLoad.do?method=getFileList"/>';window.close();"/>
<input type="button" onclick="window.close();"value="关闭">
<br><br>
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
(4)fileinfo.jsp(文件信息预览页面)
<%@ page language="java"pageEncoding="gbk" isELIgnored="false"%> <% String path = request.getContextPath(); %> <html> <head> <title>查看文件的信息</title> </head> <body bgcolor="#F4F4F4"> <mce:script type="text/javascript"><!-- history.go(1); // --></mce:script> <h1>文件的描述信息</h1> <div style="color:#049ed0;" mce_style="color:#049ed0;">${info}</div> </body> </html>
(5)zxc.js
function alertWin(title, msg, w, h){ var titleheight = "20px"; var bordercolor = "#666699"; var titlecolor = "#FFFFFF"; var titlebgcolor = "#1d5798"; var bgcolor = "#FFFFFF"; var iWidth = document.documentElement.clientWidth; var iHeight = document.documentElement.clientHeight; var bgObj = document.createElement("div"); bgObj.style.cssText = "position:absolute;left:0px;top:0px;width:"+iWidth+"px;height:"+Math.max(document.body.clientHeight, iHeight)+"px;filter:Alpha(Opacity=10);opacity:0.1;background-color:#000000;z-index:101;"; document.body.appendChild(bgObj); var msgObj=document.createElement("div"); msgObj.style.cssText = "position:absolute;font:11px '宋体';top:"+(iHeight-h)/2+"px;left:"+(iWidth-w) /2+"px;width:"+w+"px;height:"+h+"px;text-align:center;border:1px solid "+bordercolor+";background-color:"+bgcolor+";padding:1px;line-height:22px;z-index:102;"; document.body.appendChild(msgObj); var table = document.createElement("table"); msgObj.appendChild(table); table.style.cssText = "margin:0px;border:0px;padding:0px;"; table.cellSpacing = 0; var tr = table.insertRow(-1); var titleBar = tr.insertCell(-1); titleBar.style.cssText = "width:100%;height:"+titleheight+"px;text-align:left;padding:3px;margin:0px;font:bold 13px '宋体';color:"+titlecolor+";border:1px solid " + bordercolor + ";cursor:move;background-color:" + titlebgcolor; titleBar.style.paddingLeft = "10px"; titleBar.innerHTML = title; var moveX = 0; var moveY = 0; var moveTop = 0; var moveLeft = 0; var moveable = false; var docMouseMoveEvent = document.onmousemove; var docMouseUpEvent = document.onmouseup; titleBar.onmousedown = function() { var evt = getEvent(); moveable = true; moveX = evt.clientX; moveY = evt.clientY; moveTop = parseInt(msgObj.style.top); moveLeft = parseInt(msgObj.style.left); document.onmousemove = function() { if (moveable) { var evt = getEvent(); var x = moveLeft + evt.clientX - moveX; var y = moveTop + evt.clientY - moveY; if ( x > 0 &&( x + w < iWidth) && y > 0 && (y + h < iHeight) ) { msgObj.style.left = x + "px"; msgObj.style.top = y + "px"; } } }; document.onmouseup = function () { if (moveable) { document.onmousemove = docMouseMoveEvent; document.onmouseup = docMouseUpEvent; moveable = false; moveX = 0; moveY = 0; moveTop = 0; moveLeft = 0; } }; } var closeBtn = tr.insertCell(-1); closeBtn.style.cssText = "cursor:pointer; padding:2px;background-color:" + titlebgcolor; closeBtn.innerHTML = "<span style="font-size:15pt; color:"+titlecolor+";" mce_style="font-size:15pt; color:"+titlecolor+";">x</span>"; closeBtn.onclick = function(){ document.body.removeChild(bgObj); document.body.removeChild(msgObj); } var msgBox = table.insertRow(-1).insertCell(-1); msgBox.style.cssText = "font:10pt '瀹嬩綋';"; msgBox.colSpan = 2; msgBox.innerHTML = document.getElementById("logincontent").innerHTML; function getEvent() { return window.event || arguments.callee.caller.arguments[0]; } } function $(id){ return document.getElementById(id); } function refresh(){ $("imgCode").src="<%=path%>/servlet/textBufferedImage?timestampt="+new Date().getTime(); alert($("imgCode").src); } function del(name){ if(confirm("你确定要删除该文件吗?")){ window.location.href=$("path").value+"/fileUpDownLoad.do?method=deleteFile&filesavename="+name; } } function query(){ window.location.href=$("path").value+"/fileUpDownLoad.do?method=getFileList"; } function download(name){ var url=$("path").value+"/fileUpDownLoad.do?method=downloadFile&downfilename="+name; window.location.href=url; } window.onload=function(){ var tab= document.getElementById("me"); var trs=tab.getElementsByTagName("tr"); for(var i=0;i<trs.length;i++){ trs[i].style.backgroundColor="#E6F2FA"; } } function checkCurrentPage(input,totalPages){ if(input.match(/^/D*$/)){ alert("只能输入数字!"); document.getElementById("jumpPageBox").value=document.getElementById("pages").value; document.getElementById("jumpPageBox").focus(); }else if(input>totalPages||input.value<=0){ alert("对不起,你输入的页码有误!"); document.getElementById("jumpPageBox").value=document.getElementById("pages").value; document.getElementById("jumpPageBox").focus(); } } function showInfo(info){ var width=400; var height=300; windowX=(screen.width-width)/2; windowY=(screen.height-height)/2; features="top="+windowY+",left="+windowX+",width="+width+",height="+height+",menubar=no,resizable=no"; window.open($("path").value+"/fileUpDownLoad.do?method=showFileInfo&info="+info,"",features); } function openUpwin(){ var width=700; var height=500; windowX=(screen.width-width)/2; windowY=(screen.height-height)/2; features="top="+windowY+",left="+windowX+",width="+width+",height="+height+",menubar=no,resizable=no"; window.open("uploadfile.jsp","",features); } function quit(){ window.location.href=$("path").value+"/fileUpDownLoad.do?method=logout"; }
2.公用类和javabean
(1)DBAccess.java(数据库连接)
package bean; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBAccess { /** * @param args */ public DBAccess(){ } public static Connection getConnection(){ try { Class.forName("com.mysql.jdbc.Driver"); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block System.out.println("驱动程序未找!"); e.printStackTrace(); } String url="jdbc:mysql://localhost:3306/file?characterEncoding=gbk"; String user="root"; String password="123"; Connection conn=null; try { conn=DriverManager.getConnection(url, user, password); } catch (SQLException e) { // TODO Auto-generated catch block System.out.println("数据库连接出错啦!"); e.printStackTrace(); } System.out.println("Connection连接成功!"); return conn; } public static void main(String[] args) { // TODO Auto-generated method stub Connection connection=getConnection(); } }
(2)FileInfo.java(文件信息bean)
package bean; public class FileInfo implements java.io.Serializable { // Fields private String fileId; private String fileSavename; private String fileName; private String fileType; private String fileSize; private String fileInfo; private String fileUptime; private String fileIp; private long fileTimes; private String fileTag; /** default constructor */ public FileInfo() { } /** minimal constructor */ public FileInfo(String fileId) { this.fileId = fileId; } /** full constructor */ public FileInfo(String fileId, String fileSavename, String fileName, String fileType, String fileSize, String fileInfo, String fileUptime, String fileIp,long fileTimes,String fileTag) { this.fileId = fileId; this.fileSavename = fileSavename; this.fileName = fileName; this.fileType = fileType; this.fileSize = fileSize; this.fileInfo = fileInfo; this.fileUptime = fileUptime; this.fileIp = fileIp; this.fileTimes=fileTimes; this.fileTag=fileTag; } // Property accessors public String getFileId() { return this.fileId; } public void setFileId(String fileId) { this.fileId = fileId; } public String getFileSavename() { return this.fileSavename; } public void setFileSavename(String fileSavename) { this.fileSavename = fileSavename; } public String getFileName() { return this.fileName; } public void setFileName(String fileName) { this.fileName = fileName; } public String getFileType() { return this.fileType; } public void setFileType(String fileType) { this.fileType = fileType; } public String getFileSize() { return this.fileSize; } public void setFileSize(String fileSize) { this.fileSize = fileSize; } public String getFileInfo() { return this.fileInfo; } public void setFileInfo(String fileInfo) { this.fileInfo = fileInfo; } public String getFileUptime() { return this.fileUptime; } public void setFileUptime(String fileUptime) { this.fileUptime = fileUptime; } public String getFileIp() { return this.fileIp; } public void setFileIp(String fileIp) { this.fileIp = fileIp; } public void setFileTimes(long fileTimes) { this.fileTimes = fileTimes; } public long getFileTimes() { return fileTimes; } public void setFileTag(String fileTag) { this.fileTag = fileTag; } public String getFileTag() { return fileTag; } }
(3)PageListData.java(分页参数分装bean)
package bean; import java.util.ArrayList; import java.util.List; import java.util.Locale; import javax.servlet.http.HttpServletRequest; public class PageListData { // 分页结果集 private List dataArray = null; // 记录总数 private int count = 0; // 每页显示记录数 private int pageSize = 0; // 当前页数 private int page = 1; public PageListData() { } public List getDataArray() { return dataArray; } public void setDataArray(List dataArray) { this.dataArray = dataArray; } // 记录总数 public int getCount() { return count; } public void setCount(int count) { this.count = count; } // 总页数 public int getPageCount() { if(count%pageSize==0){ return count/pageSize; }else{ return count/pageSize+1; } } // 每页显示 录数 public int getPageSize() { return pageSize; } public void setPageSize(int pageSize) { this.pageSize = pageSize; } // 当前页数 public int getPage() { return page; } public void setPage(int page) { this.page = page; } /** * 封装分页栏函数 必需被包含在某个Form之中 * @param request HttpServletRequest * @return String pages 当前页号 pageSize 每页显示行数 */ public String getFooter(HttpServletRequest request) { String previous = "上一页"; String next ="下一页"; StringBuffer pageStr = new StringBuffer(""); pageStr.append("<center><p class='pages'>"); int nTotalPages = getPageCount(); //总页数 int nCurrentPage = getPage(); //当前页 int nPrevPage = getPage() - 1; //上一页 int nNextPage = getPage() + 1; //下一页 int first = 0; int last = 0; if (nCurrentPage > 1){ pageStr.append("<a onclick='document.getElementById(/"pages/").value=" + nPrevPage + ";document.getElementById(/"pages/").form.submit();' class='prevpage' style="cursor: pointer;" mce_style="cursor: pointer;" ><strong>" + previous +"</strong></a> "); } for (int i = 1; i <= nTotalPages; i++) { if (i == nCurrentPage){ pageStr.append("<span style="padding:1px 8px 1px 8px;color:#fff;text-decoration:none!important;background:url(./images/pgback.png) no-repeat center center;" mce_style="padding:1px 8px 1px 8px;color:#fff;text-decoration:none!important;background:url(images/pgback.png) no-repeat center center;">" + i + "</span> "); } else { if(nCurrentPage == 1 && (i == 2 || i==3)) { pageStr.append("<a id='Pagelist' onclick='document.getElementById(/"pages/").value="+ i +";document.getElementById(/"pages/").form.submit();' style="cursor: pointer;" mce_style="cursor: pointer;">" + i + "</a> "); } else if (i != 1 && nCurrentPage >= 5 && i < nCurrentPage) { if(first == 0) { pageStr.append("<span class='pgempty'>...</span>"); first = 1; } if(nCurrentPage == nTotalPages && i == nTotalPages - 1) { pageStr.append("<a id='Pagelist' onclick='document.getElementById(/"pages/").value="+ i +";document.getElementById(/"pages/").form.submit();' style="cursor: pointer;" mce_style="cursor: pointer;">" + i + "</a> "); } } else if( i <= nTotalPages && nCurrentPage <= nTotalPages - 4 && i > (nCurrentPage + 1)) { if(last == 0) { pageStr.append("<span class='pgempty'>...</span>"); last = 1; } if(i==nTotalPages){ pageStr.append("<a id='Pagelist' onclick='document.getElementById(/"pages/").value="+ i +";document.getElementById(/"pages/").form.submit();' style="cursor: pointer;" mce_style="cursor: pointer;">" + i + "</a> "); } } else { pageStr.append("<a id='Pagelist' onclick='document.getElementById(/"pages/").value="+ i +";document.getElementById(/"pages/").form.submit();' style="cursor: pointer;" mce_style="cursor: pointer;">" + i + "</a> "); } } } if (nCurrentPage < nTotalPages) { pageStr.append("<a class='nextpage'style='cursor: pointer;' onclick='document.getElementById(/"pages/").value=" + nNextPage + ";document.getElementById(/"pages/").form.submit();'><strong>" + next +"</strong></a></center>"); } pageStr.append("</p>"); pageStr.append("<input type='hidden' value='" + nCurrentPage + "' name='pages' id='pages' />"); pageStr.append("<input type='hidden' value='" + pageSize + "' name='pageSize' id='pageSize' />"); return pageStr.toString(); } public String getFooter1(HttpServletRequest request) { StringBuffer pageStr = new StringBuffer(""); pageStr.append("<center><p class='pages'>"); int totalPages = getPageCount(); //总页数 int currentPage = getPage(); //当前页 int totalcount=getCount();//总记录数 int prevPage = getPage() - 1; //上一页 int nextPage = getPage() + 1; //下一页 pageStr.append("<span style="color:#049ed0;" mce_style="color:#049ed0;">共有"+totalcount+"条记录</span> "); pageStr.append("<span style="color:#049ed0;" mce_style="color:#049ed0;">第"+currentPage+"页/共"+totalPages+"页</span> "); if(currentPage>1) pageStr.append("<span><a style="cursor: pointer;text-decoration:underline;color:#049ed0;" mce_style="cursor: pointer;text-decoration:underline;color:#049ed0;"onclick='document.getElementById(/"pages/").value=1;document.getElementById(/"pages/").form.submit();'>首页</a></span> "); if(currentPage==1) pageStr.append("<span style="color:#049ed0;" mce_style="color:#049ed0;">首页</span> "); if(currentPage>1) pageStr.append("<span><a style="cursor: pointer;text-decoration:underline;color:#049ed0;" mce_style="cursor: pointer;text-decoration:underline;color:#049ed0;" onclick='document.getElementById(/"pages/").value="+prevPage+";document.getElementById(/"pages/").form.submit();'>上一页</a></span> "); if(currentPage<=1) pageStr.append("<span style="color:#049ed0;" mce_style="color:#049ed0;">上一页</span> "); if(currentPage<totalPages) pageStr.append("<span><a style="cursor: pointer;text-decoration:underline;color:#049ed0;" mce_style="cursor: pointer;text-decoration:underline;color:#049ed0;" onclick='document.getElementById(/"pages/").value="+nextPage+";document.getElementById(/"pages/").form.submit();'>下一页</a></span> "); if(currentPage>=totalPages) pageStr.append("<span style="color:#049ed0;" mce_style="color:#049ed0;">下一页</span> "); if(currentPage<totalPages) pageStr.append("<span><a style="cursor: pointer;text-decoration:underline;color:#049ed0;" mce_style="cursor: pointer;text-decoration:underline;color:#049ed0;" onclick='document.getElementById(/"pages/").value="+totalPages+";document.getElementById(/"pages/").form.submit();'>末页</a></span> "); if(currentPage==totalPages) pageStr.append("<span style="color:#049ed0;" mce_style="color:#049ed0;">末页</span> "); pageStr .append("<span style="color:#049ed0;" mce_style="color:#049ed0;">跳转至第:<input type='text' value='" + currentPage + "'id='jumpPageBox' size='4' onblur='checkCurrentPage(document.getElementById(/"jumpPageBox/").value,"+totalPages+")'/>页<input style="color:#049ed0;" mce_style="color:#049ed0;" type='button' value='跳转' onclick='document.getElementById(/"pages/").value=document.getElementById(/"jumpPageBox/").value;document.getElementById(/"pages/").form.submit();'/></span>"); pageStr.append("</p></center>"); pageStr.append("<input type='hidden' value='" + currentPage + "' name='pages' id='pages' />"); pageStr.append("<input type='hidden' value='" + pageSize + "' name='pageSize' id='pageSize' />"); return pageStr.toString(); } }
(4)StringHandler.java(字符串处理)
package bean; import java.text.SimpleDateFormat; import java.util.Date; public class StringHandler { public static String timeTostr(Date date){ String strDate=""; SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); strDate=format.format(date); return strDate; } public static String getSerial(Date date,int index){ long msel=date.getTime(); //��ȡ������ SimpleDateFormat fm=new SimpleDateFormat("MMddyyyyHHmmssSS"); //����ת������ msel+=index; //ͨ��һ��ֵ�ı������ date.setTime(msel); //ͨ��ı��ĺ����������������� String serials=fm.format(date); //ת������ʱ�������Ϊ��MMddyyyyHHmmssSS����ʽ return serials; } public static String changehtml(String str){ String change=""; if(str!=null&&!str.equals("")){ change=str.replace("&","&"); change=change.replace(" "," "); change=change.replace("<","<"); change=change.replace(">",">"); change=change.replace("/"","""); change=change.replace("/r/n","<br>"); } return change; } }
(5)User.java
package bean; public class User { private int id; private String username; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
(6)TextBufferedImage.java(验证码servlet)
package servlet; import java.awt.Color; import java.awt.Font; import java.awt.Graphics2D; import java.awt.image.BufferedImage; import java.io.IOException; import java.io.OutputStream; import java.util.Random; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import com.sun.image.codec.jpeg.JPEGCodec; import com.sun.image.codec.jpeg.JPEGImageEncoder; public class TextBufferedImage extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { //产生随机密码 resp.setHeader("Cache-Control","no-cache"); HttpSession session = req.getSession(); String randomPassword = getRandom(4); System.out.println("randomPassword="+randomPassword); session.setAttribute("randomCode", randomPassword); OutputStream out = resp.getOutputStream(); try { JPEGImageEncoder encode = JPEGCodec.createJPEGEncoder(out); BufferedImage bi = CreateBufferedImage(randomPassword); encode.encode(bi); } catch (Exception e) { e.printStackTrace(); } } /** * 把随机码写到图片上返回 * * @param randomPassword //随机码 * @return */ private BufferedImage CreateBufferedImage(String randomPassword) { int width = 80; int height = 20; BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2d = bufferedImage.createGraphics(); g2d.clearRect(0, 0, width, height); // 设定背景色 g2d.setColor(getRandColor(200,250)); g2d.fillRect(0, 0, width, height); // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到 Random random = new Random(); g2d.setColor(getRandColor(160,200)); g2d.setFont(getFont()); for (int i=0;i<155;i++) { int x = random.nextInt(width); int y = random.nextInt(height); int xl = random.nextInt(12); int yl = random.nextInt(12); g2d.drawLine(x,y,x+xl,y+yl); } // 取随机产生的认证码(4位数字) String sRand=""; for (int i=0;i<4;i++){ String rand = randomPassword.substring(i, i+1); sRand+=rand; // 将认证码显示到图象中 g2d.setColor(new Color(20+random.nextInt(110),20+random.nextInt(110),20+random.nextInt(110)));//调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成 g2d.drawString(rand,14*i+12,17); } g2d.dispose(); return bufferedImage; } private Color getRandColor(int fc, int bc) {// 给定范围获得随机颜色 Random random = new Random(); if (fc > 255) fc = 255; if (bc > 255) bc = 255; int r = fc + random.nextInt(bc - fc); int g = fc + random.nextInt(bc - fc); int b = fc + random.nextInt(bc - fc); return new Color(r, g, b); } private Font getFont() { Random random = new Random(); Font font[] = new Font[5]; font[0] = new Font("Ravie", Font.PLAIN, 20); font[1] = new Font("Antique Olive Compact", Font.PLAIN, 20); font[2] = new Font("Forte", Font.PLAIN, 20); font[3] = new Font("Wide Latin", Font.PLAIN, 20); font[4] = new Font("Gill Sans Ultra Bold", Font.PLAIN, 20); return font[random.nextInt(5)]; } /** * 产生随机码(字母+数字) * * @param length * 随机码长度 * @return 随机码 */ private String getRandom(int length) { String randomCode = ""; for (int i = 0; i < length; i++) { randomCode += getRandChar(); } return randomCode; } public String getRandChar() { int rand = (int) Math.round(Math.random() * 2); long itmp = 0; char ctmp = '/u0000'; // 根据rand的值来决定来生成一个大写字母、小写字母和数字 switch (rand) { // 生成大写字母 case 1: itmp = Math.round(Math.random() * 25 + 65); ctmp = (char) itmp; return String.valueOf(ctmp); // 生成小写字母 case 2: itmp = Math.round(Math.random() * 25 + 97); ctmp = (char) itmp; return String.valueOf(ctmp); // 生成数字 default: itmp = Math.round(Math.random() * 9); return String.valueOf(itmp); } } }
3.数据层
(1)UserDAO.java
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import bean.DBAccess; import bean.User; public class UserDAO { public User checkLogin(String username, String password) { String sql = "select * from user where username=? and password=?"; PreparedStatement ps = null; ResultSet rs = null; Connection conn = null; User user=null; try { conn = DBAccess.getConnection(); ps = conn.prepareStatement(sql); ps.setString(1, username); ps.setString(2, password); rs = ps.executeQuery(); if (rs.next()) { if (rs.getString("username").equals(username) && rs.getString("password").equals(password)) { user=new User(); user.setId(rs.getInt("id")); user.setUsername(rs.getString("username")); user.setPassword(rs.getString("password")); } } rs.close(); ps.close(); conn.close(); } catch (SQLException e) { e.printStackTrace(); } return user; } }
(2)FileDAO.java
package dao; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import bean.DBAccess; import bean.FileInfo; public class FileDAO { DBAccess db = new DBAccess(); public boolean isExsitSameFileName(String filename, HttpServletRequest request) { boolean flag = false; PreparedStatement ps = null; ResultSet rs = null; Connection connection = db.getConnection(); String sql = "select * from file where filename=?"; try { ps = connection.prepareStatement(sql); ps.setString(1, filename); rs = ps.executeQuery(); if (rs.next()) { FileInfo fileInfo = new FileInfo(); fileInfo.setFileId(rs.getString("fileid")); fileInfo.setFileInfo(rs.getString("fileinfo")); fileInfo.setFileIp(rs.getString("fileip")); fileInfo.setFileName(rs.getString("filename")); fileInfo.setFileSavename(rs.getString("filesavename")); fileInfo.setFileSize((rs .getString("filesize"))); fileInfo.setFileTag(rs.getString("filetag")); fileInfo.setFileTimes(Integer.parseInt(rs .getString("filetimes"))); fileInfo.setFileType(rs.getString("filetype")); fileInfo.setFileUptime(rs.getString("fileuptime")); java.io.File f = new java.io.File(request.getSession() .getServletContext().getRealPath("/") + fileInfo.getFileSavename()); if (f.isFile()) flag = true; } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { if (rs != null) rs.close(); if (ps != null) ps.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } } return flag; } public boolean saveFile(FileInfo fileInfo) { boolean flag = false; PreparedStatement ps = null; Connection connection = db.getConnection(); String sql = "insert into file(fileId,fileSavename,fileName,fileType,fileSize,fileInfo,fileUptime,fileIp,fileTimes,fileTag) " + "values(?,?,?,?,?,?,?,?,?,?)"; try { ps = connection.prepareStatement(sql); ps.setString(1, fileInfo.getFileId()); ps.setString(2, fileInfo.getFileSavename()); ps.setString(3, fileInfo.getFileName()); ps.setString(4, fileInfo.getFileType()); ps.setString(5, String.valueOf(fileInfo.getFileSize())); String fileString = fileInfo.getFileInfo(); // fileString.replaceAll("/n", "").replaceAll("@", ""); ps.setString(6, fileString); ps.setString(7, fileInfo.getFileUptime()); ps.setString(8, fileInfo.getFileIp()); ps.setString(9, String.valueOf(fileInfo.getFileTimes())); ps.setString(10, fileInfo.getFileTag()); int i = ps.executeUpdate(); if (i == 1) flag = true; } catch (Exception e) { e.printStackTrace(); } finally { try { ps.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } } return flag; } public Map queryFile(HttpServletRequest request,int currentPage,int pageSize) { boolean flag = false; Map map=new HashMap(); PreparedStatement ps = null; PreparedStatement ps1 = null; PreparedStatement ps2=null; ResultSet rs = null; ResultSet rs2=null; int totalcount=0; List list = new ArrayList<FileInfo>(); Connection connection = db.getConnection(); String sql1 = "select * from file order by fileuptime desc"; String sql2 = "delete from file where filesavename=?"; String sql3="select count(*)from file"; try { ps = connection.prepareStatement(sql1); rs = ps.executeQuery(); if ((currentPage - 1) * pageSize != 0) rs.absolute((currentPage - 1) * pageSize); int i=0; while (rs.next()&&i++ < pageSize) { FileInfo fileInfo = new FileInfo(); fileInfo.setFileId(rs.getString("fileid")); fileInfo .setFileInfo(formatString(rs.getString("fileinfo"), 15)); fileInfo.setFileIp(rs.getString("fileip")); String filename = rs.getString("filename"); fileInfo.setFileName(filename); fileInfo.setFileSavename(rs.getString("filesavename")); Double filesize=Double.parseDouble(rs.getString("filesize")); fileInfo.setFileSize(formatFileSize(filesize)); fileInfo.setFileTag(rs.getString("filetag")); fileInfo.setFileTimes(Integer.parseInt(rs .getString("filetimes"))); fileInfo.setFileType(rs.getString("filetype")); fileInfo.setFileUptime(rs.getString("fileuptime")); java.io.File f = new java.io.File(request.getSession() .getServletContext().getRealPath("/") + fileInfo.getFileSavename()); if (f.isFile()) list.add(fileInfo); else { ps1 = connection.prepareStatement(sql2); ps1.setString(1, fileInfo.getFileSavename()); ps1.executeUpdate(); ps1.close(); } } rs.close(); ps.close(); ps2=connection.prepareStatement(sql3); rs2=ps2.executeQuery(); while(rs2.next()){ totalcount=rs2.getInt(1); } map.put("resultList",list); map.put("totalcount", totalcount); rs2.close(); ps2.close(); } catch (Exception e) { e.printStackTrace(); } return map; } public FileInfo findFileByName(String filesavename) { PreparedStatement ps = null; ResultSet rs = null; Connection connection = db.getConnection(); FileInfo fileInfo = null; String sql = "select * from file where filesavename=?"; try { ps = connection.prepareStatement(sql); ps.setString(1, filesavename); rs = ps.executeQuery(); if (rs.next()) { fileInfo = new FileInfo(); fileInfo.setFileId(rs.getString("fileid")); fileInfo .setFileInfo(formatString(rs.getString("fileinfo"), 15)); fileInfo.setFileIp(rs.getString("fileip")); fileInfo.setFileName(rs.getString("filename")); fileInfo.setFileSavename(rs.getString("filesavename")); fileInfo.setFileSize((rs .getString("filesize"))); fileInfo.setFileTag(rs.getString("filetag")); fileInfo.setFileTimes(Integer.parseInt(rs .getString("filetimes"))); fileInfo.setFileType(rs.getString("filetype")); fileInfo.setFileUptime(rs.getString("fileuptime")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { rs.close(); ps.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } } return fileInfo; } public FileInfo findFileById(String fileid) { PreparedStatement ps = null; ResultSet rs = null; Connection connection = db.getConnection(); FileInfo fileInfo = null; String sql = "select * from file where fileid=?"; try { ps = connection.prepareStatement(sql); ps.setString(1, fileid); rs = ps.executeQuery(); if (rs.next()) { fileInfo = new FileInfo(); fileInfo.setFileId(rs.getString("fileid")); fileInfo .setFileInfo(formatString(rs.getString("fileinfo"), 15)); fileInfo.setFileIp(rs.getString("fileip")); fileInfo.setFileName(rs.getString("filename")); fileInfo.setFileSavename(rs.getString("filesavename")); fileInfo.setFileSize((rs .getString("filesize"))); fileInfo.setFileTag(rs.getString("filetag")); fileInfo.setFileTimes(Integer.parseInt(rs .getString("filetimes"))); fileInfo.setFileType(rs.getString("filetype")); fileInfo.setFileUptime(rs.getString("fileuptime")); } } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { rs.close(); ps.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } } return fileInfo; } public boolean deleteFile(String filesavename) { boolean flag = false; PreparedStatement ps = null; Connection connection = db.getConnection(); String sql = "delete from file where filesavename=?"; try { ps = connection.prepareStatement(sql); ps.setString(1, filesavename); int i = ps.executeUpdate(); if (i == 1) flag = true; } catch (Exception e) { e.printStackTrace(); } finally { try { ps.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } } return flag; } public void addUpTimes(Long times, String filesavename) { PreparedStatement ps = null; Connection connection = db.getConnection(); String sql = "update file set filetimes=? where filesavename=?"; try { ps = connection.prepareStatement(sql); ps.setString(1, String.valueOf(times + 1)); ps.setString(2, filesavename); ps.executeUpdate(); } catch (Exception e) { e.printStackTrace(); } finally { try { ps.close(); connection.close(); } catch (Exception e) { e.printStackTrace(); } } } public String formatString(String str, int len) { str =(str == null || str.trim().equals(""))? "" : str; int forEach = str.length() / len; int yushu = str.length() % len; StringBuffer buffer = new StringBuffer(); int i = 0; if (yushu != 0) { for (; i < forEach; i++) { buffer.append(str.substring(i * len, (i + 1) * len)).append( "<br/>"); } buffer.append(str.substring(i * len)); } else { for (; i < forEach; i++) { if (i < forEach - 1) { buffer.append(str.substring(i * len, (i + 1) * len)) .append("<br/>"); } else { buffer.append(str.substring(i * len)).append("<br/>"); } } } return buffer.toString(); } public static String formatFileSize(Double size){ String result=""; int flag=(int)(size/1024); int remain=(int)(size%1024); if(flag<1) result=new java.text.DecimalFormat("#.00").format(size)+" KB"; else if(flag==1) result="1 M"; else{ if(remain==0) result=flag+" M"; else result=new java.text.DecimalFormat("#.00").format(size/1024)+" M"; } return result; } }
4.业务逻辑层
(1)LoginAction.java
/* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package com.zxc.struts.action; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.Action; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import bean.User; import dao.UserDAO; public class LoginAction extends Action { public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws IOException { // TODO Auto-generated method stub String username = request.getParameter("username"); String password = request.getParameter("password"); String randomCode = request.getSession().getAttribute("randomCode") == null ? "" : request.getSession().getAttribute("randomCode").toString(); String randomCodePage = request.getParameter("randcode") == null ? "" : request.getParameter("randcode"); String forward = ""; if (randomCode.equalsIgnoreCase((randomCodePage.trim()))) { User user = new UserDAO().checkLogin(username, password); if (user != null) { request.getSession().setAttribute("user", user); return new ActionForward("/fileUpDownLoad.do?method=getFileList"); } else { return mapping.findForward("failure"); } } else { return mapping.findForward("failure"); } } }
(2)FileUpDownLoadAction.java
/* * Generated by MyEclipse Struts * Template path: templates/java/JavaClass.vtl */ package com.zxc.struts.action; import java.io.BufferedInputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.util.ArrayList; import java.util.Date; import java.util.List; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessage; import org.apache.struts.action.ActionMessages; import org.apache.struts.actions.DispatchAction; import bean.FileInfo; import bean.PageListData; import bean.StringHandler; import com.jspsmart.upload.File; import com.jspsmart.upload.Files; import com.jspsmart.upload.SmartUpload; import com.jspsmart.upload.SmartUploadException; import dao.FileDAO; /** * MyEclipse Struts Creation date: 01-12-2010 * * XDoclet definition: * * @struts.action parameter="method" */ public class FileUpDownLoadAction extends DispatchAction { private FileDAO service = new FileDAO(); ActionMessages messages = new ActionMessages(); /** * Method execute * * @param mapping * @param form * @param request * @param response * @return ActionForward */ // 文件上传 public ActionForward uploadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { // TODO Auto-generated method stub String message = ""; long maxsize = 1024 * 1024 * 10; String filedir = request.getSession().getServletContext().getRealPath( "/"); System.out.println("filedir" + filedir); try { SmartUpload myup = new SmartUpload(); myup.initialize(this.getServlet(), request, response); myup.setAllowedFilesList("pdf,doc,txt,rar,jar"); myup.setTotalMaxFileSize(maxsize); myup.upload(); Files files = myup.getFiles(); int count = files.getCount(); Date date = new Date(); // String path = request.getContextPath(); for (int i = 0; i < count; i++) { com.jspsmart.upload.File file = files.getFile(i); if (!file.isMissing()) { if (service .isExsitSameFileName(file.getFileName(), request)) { System.out.println(file.getFileName()); message = "<img src="" + path + "/image/error.gif" mce_src="" + path + "/image/error.gif"/>" + "您上传的文件<" + file.getFileName() + ">名已经存在,请重新选择!"; } else { int filesize = file.getSize() / 1024; if (filesize == 0) { message = "<img src="" + path + "/image/error.gif" mce_src="" + path + "/image/error.gif"/>" + "文件<" + file.getFileName() + ">是0字节的文件,请上传非空文件!"; } else if (filesize > 1024 * 20) { message = "<img src="" + path + "/image/error.gif" mce_src="" + path + "/image/error.gif"/>" + "文件<" + file.getFileName() + ">已经超过20兆了,请上传小于20兆的文件!"; } else { String filename = file.getFileName(); String filetype = file.getContentType().trim(); String savename = StringHandler.getSerial(date, i) + "." + file.getFileExt(); String fileinfo = myup.getRequest().getParameter( "fileinfo" + (i + 1)); System.out.println(fileinfo); String filetag = myup.getRequest().getParameter( "tag" + (i + 1)); String uptime = StringHandler.timeTostr(date); FileInfo filebean = new FileInfo(); filebean.setFileName(filename); filebean.setFileSavename(savename); filebean.setFileType(filetype); filebean.setFileSize(String.valueOf(filesize)); filebean.setFileInfo(fileinfo); filebean.setFileUptime(uptime); filebean.setFileTag(filetag); // filebean.setFileTimes(filetimes); String IP = request.getRemoteAddr(); String originIP = request .getHeader("x-forwarded-for"); if (originIP == null || originIP.length() == 0) { filebean.setFileIp(IP); } else { filebean.setFileIp(originIP); } String savepath = filedir + savename; java.io.File f = new java.io.File(filedir); if (!f.exists()) f.mkdirs(); file.saveAs(savepath, File.SAVEAS_AUTO); if (service.saveFile(filebean)) { message += "<img src="" + path + "/image/success.gif" mce_src="" + path + "/image/success.gif"/>" + "文件 <b>" + file.getFilePathName() + "</b> 上传成功!<br>"; } else { message += "上传失败!"; } } } } } } catch (java.lang.SecurityException e1) { if(e1.getMessage().startsWith("Total File")){ message="●您上传的文件太大!" ; }else{ message = "●上传的文件格式错误,只能上传格式为pdf,doc,txt,rar和jar类型的文件!"; } e1.printStackTrace(); } catch (Exception e2) { System.out.println("文件上传失败!"); e2.printStackTrace(); } catch (java.lang.OutOfMemoryError e3) { message = "●您上传的文件太大!"; e3.printStackTrace(); } request.setAttribute("message", message); return mapping.findForward("success"); } // 获取文件列表 public ActionForward getFileList(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { int currPage = request.getParameter("pages")==null?1:Integer.parseInt(request.getParameter("pages")); int pageSize = request.getParameter("pageSize")==null?10:Integer.parseInt(request.getParameter("pageSize")); Map map = service.queryFile(request,currPage,pageSize); List list=new ArrayList(); int totalcount=0; if(map!=null){ list=(ArrayList)map.get("resultList"); totalcount=map.get("totalcount")==null?0:(Integer)map.get("totalcount"); } if (list != null && !list.isEmpty()) { PageListData pageListData = new PageListData(); pageListData.setCount(totalcount); pageListData.setPage(currPage); pageListData.setPageSize(pageSize); pageListData.setDataArray(list); request.setAttribute("footer", pageListData.getFooter1(request)); request.setAttribute("pageList", pageListData); return mapping.findForward("list"); } else { String message = "没有文件可以显示!"; request.setAttribute("message", message); return mapping.findForward("list"); } } // 文件下载 public ActionForward downloadFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String downfilename = request.getParameter("downfilename"); FileInfo file = service.findFileByName(downfilename); String filedir = request.getSession().getServletContext().getRealPath( "/"); if (file != null) { SmartUpload mydown = new SmartUpload(); try { mydown.initialize(this.getServlet(), request, response); mydown.setContentDisposition(null); mydown.downloadFile(filedir + downfilename, file.getFileType(), file.getFileName()); service.addUpTimes(file.getFileTimes(), file.getFileSavename()); } catch (ServletException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SmartUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } else { String message = "下载文件出错啦!"; request.setAttribute("message", message); return mapping.findForward("show"); } } // 删除文件 public ActionForward deleteFile(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { String filesavename = request.getParameter("filesavename"); FileInfo file = service.findFileByName(filesavename); java.io.File f = new java.io.File(request.getSession() .getServletContext().getRealPath("/") + file.getFileSavename()); if (service.deleteFile(filesavename)) { boolean flag = f.delete(); if (flag) { String message = "<mce:script language='javascript'><!-- " + "alert('删除成功!');" + " // --></mce:script>"; request.setAttribute("mode", message); return new ActionForward( "/fileUpDownLoad.do?method=getFileList"); } else { String message = "删除磁盘文件出错啦!"; request.setAttribute("message", message); return mapping.findForward("show"); } } else { String message = "<mce:script language='javascript'><!-- " + "alert(文件删除失败!');" + " // --></mce:script>"; request.setAttribute("mode", message); return new ActionForward("/fileUpDownLoad.do?method=getFileList"); } } public ActionForward showFileInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { request.setAttribute("info", request.getParameter("info")); return mapping.findForward("info"); } //退出系统 public ActionForward logout(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { request.getSession(true).removeAttribute("user"); request.getSession().invalidate(); return mapping.findForward("logout"); } public ActionForward a(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) { // byte[] pdfContent = null; // String pdfID="123"; // pdfContent = "sdfsdffsfsdfsdfsdfsdfsdsdfsdffsdfsdsdf".getBytes(); // InputStream inputs=new ByteArrayInputStream(pdfContent); // BufferedInputStream buff = new BufferedInputStream(inputs); // int filesize = pdfContent.length; try { // 假数据 String downfilename = request.getParameter("downfilename"); FileInfo fileinfo = service.findFileByName(downfilename); String path = request.getSession().getServletContext().getRealPath( "/"); String docName = path + downfilename; // 创建file对象 java.io.File file = new java.io.File(docName); // 读出文件到i/o流 FileInputStream fis = new FileInputStream(file); BufferedInputStream buff = new BufferedInputStream(fis); int filesize = (int) file.length(); response.reset(); response.setContentType(fileinfo.getFileType()); response.setHeader("Content-disposition", "attachment;filename=" + fileinfo.getFileName()); // 要下载的文件的大小 response.setContentLength(filesize); // 从response对象中得到输出流,准备下载 OutputStream out = response.getOutputStream(); // 相当于我们的缓存 byte[] b = new byte[1024]; // 该值用于计算当前实际下载了多少字节 int k = 0; // 开始循环下载 while (k < filesize) { int j = buff.read(b, 0, 1024); k += j; // 将b中的数据写到客户端的内存 out.write(b, 0, j); } // 将写入到客户端的内存的数据,刷新到磁盘 out.flush(); } catch (Exception e) { e.printStackTrace(); } return null; } }
5.过滤器
(1)EncodingFilter.java(处理字符编码)
package filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; public class EncodingFilter implements Filter { protected FilterConfig config; protected String Encoding = null; public void init(FilterConfig config) throws ServletException { this.config = config; this.Encoding = config.getInitParameter("Encoding"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (request.getCharacterEncoding() == null) { if (Encoding != null) { request.setCharacterEncoding(Encoding); response.setCharacterEncoding(Encoding); } } chain.doFilter(request, response); } public void destroy() { } }
(2)UserLoginFilter.java(session过滤器)
package filter; import java.io.IOException; import javax.servlet.Filter; import javax.servlet.FilterChain; import javax.servlet.FilterConfig; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; public class UserLoginFilter implements Filter { public void destroy() { } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest httpServletRequest = (HttpServletRequest) request; HttpServletResponse httpServletResponse = (HttpServletResponse) response; String requesturi = httpServletRequest.getRequestURI(); HttpSession session = httpServletRequest.getSession(); Object currentUser = session.getAttribute("user"); if (currentUser == null && !requesturi.endsWith("/login.do") && !requesturi.endsWith("/logout.do") && !requesturi.endsWith("/login.jsp") && !requesturi.endsWith(httpServletRequest.getContextPath() + "/") ) { httpServletResponse.sendRedirect(httpServletRequest.getContextPath()+"/login.jsp"); return; } chain.doFilter(request, response); } public void init(FilterConfig filterConfig) throws ServletException { } }
6.配置文件
(1)struts-config.properties
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd"> <struts-config> <form-beans /> <global-exceptions /> <global-forwards /> <action-mappings > <action parameter="method" path="/fileUpDownLoad" scope="request" type="com.zxc.struts.action.FileUpDownLoadAction" validate="false"> <forward name="success" path="/uploadfile.jsp"/> <forward name="input" path="/uploadfile.jsp"/> <forward name="show" path="/result.jsp"/> <forward name="list" path="/index.jsp"/> <forward name="logout" path="/login.jsp"/> <forward name="info" path="/fileinfo.jsp"/> </action> <action path="/login" type="com.zxc.struts.action.LoginAction" > <forward name="success" path="/index.jsp" /> <forward name="failure" path="/login.jsp" /> </action> </action-mappings> <message-resources parameter="com.zxc.struts.ApplicationResources" /> </struts-config>
(2)web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.5" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <servlet> <servlet-name>action</servlet-name> <servlet-class>org.apache.struts.action.ActionServlet</servlet-class> <init-param> <param-name>config</param-name> <param-value>/WEB-INF/struts-config.xml</param-value> </init-param> <init-param> <param-name>debug</param-name> <param-value>3</param-value> </init-param> <init-param> <param-name>detail</param-name> <param-value>3</param-value> </init-param> <load-on-startup>0</load-on-startup> </servlet> <servlet-mapping> <servlet-name>action</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>TextBufferedImage</servlet-name> <servlet-class>servlet.TextBufferedImage</servlet-class> </servlet> <servlet> <description>This is the description of my J2EE component</description> <display-name>This is the display name of my J2EE component</display-name> <servlet-name>judgeCode</servlet-name> <servlet-class>servlet.judgeCode</servlet-class> </servlet> <servlet-mapping> <servlet-name>TextBufferedImage</servlet-name> <url-pattern>/servlet/textBufferedImage</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>judgeCode</servlet-name> <url-pattern>/servlet/judgeCode</url-pattern> </servlet-mapping> <!--过滤器 --> <filter> <filter-name>Filter</filter-name> <filter-class> filter.EncodingFilter<!-- 过滤器类 --> </filter-class> <init-param> <param-name>Encoding</param-name> <param-value>gbk</param-value> </init-param> </filter> <filter-mapping> <filter-name>Filter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- session过滤器,过滤未登录的非法请求 --> <filter> <filter-name>userLoginFilter</filter-name> <filter-class>filter.UserLoginFilter</filter-class> </filter> <filter-mapping> <filter-name>userLoginFilter</filter-name> <url-pattern>*.do</url-pattern> <dispatcher>FORWARD</dispatcher> <dispatcher>REQUEST</dispatcher> </filter-mapping> <filter-mapping> <filter-name>userLoginFilter</filter-name> <url-pattern>*.jsp</url-pattern> <dispatcher>FORWARD</dispatcher> <dispatcher>REQUEST</dispatcher> </filter-mapping> <listener> <listener-class> filter.SessionListener </listener-class> </listener> <welcome-file-list> <welcome-file>login.jsp</welcome-file> </welcome-file-list> </web-app>
三.运行效果图:
(1)登录
(2)首页
(3)文件上传页面
备注:此工程压缩包我已上传csdn,有兴趣的话可搜索updownload去下载