1. 程式人生 > >如何在jsp中寫一個java方法

如何在jsp中寫一個java方法

一般用<%!  %>在jsp中寫java方法

程式碼如下:

<%@ page language="java" import="java.util.*,java.net.URLEncoder,java.text.SimpleDateFormat,java.util.Date,java.io.*,org.apache.commons.fileupload.disk.*,org.apache.commons.fileupload.servlet.ServletFileUpload,org.apache.commons.fileupload.FileItem,org.apache.commons.fileupload.FileUploadException" pageEncoding="UTF-8" contentType="text/html"%>  
<%@page import="java.sql.*,java.io.PrintWriter"%>
<%
try{
//得到要下載的檔名
String fileName = request.getParameter("filename");
fileName = new String(fileName.getBytes("iso8859-1"),"UTF-8");
//上傳的檔案都是儲存在/WEB-INF/upload目錄下的子目錄當中
//String fileSaveRootPath=this.getServletContext().getRealPath("/WEB-INF/upload");
String fileSaveRootPath="E://upload";
//通過檔名找出檔案的所在目錄
String path = findFileSavePathByFileName(fileName,fileSaveRootPath);
//String path = fileSaveRootPath;
//得到要下載的檔案
System.out.println("fileName==="+fileName);
File file = new File(path + "\\" + fileName);
//如果檔案不存在
if(!file.exists()){
request.setAttribute("message", "您要下載的資源已被刪除!!");
request.getRequestDispatcher("/upload/Message.jsp").forward(request, response);
return;
}
//處理檔名
String realname = fileName;
//設定響應頭,控制瀏覽器下載該檔案
response.setHeader("content-disposition", "attachment;filename=" + URLEncoder.encode(realname, "UTF-8"));
//讀取要下載的檔案,儲存到檔案輸入流
FileInputStream in = new FileInputStream(path + "\\" + fileName);
//建立輸出流
OutputStream ou = response.getOutputStream();
//建立緩衝區
byte buffer[] = new byte[1024];
int len = 0;
//迴圈將輸入流中的內容讀取到緩衝區當中
while((len=in.read(buffer))>0){
//輸出緩衝區的內容到瀏覽器,實現檔案下載
ou.write(buffer, 0, len);
}
//關閉檔案輸入流
in.close();
//關閉輸出流
ou.close();
response.flushBuffer();  
out.clear();  
out = pageContext.pushBody(); 
}catch(IllegalStateException e){  
	System.out.println(e.getMessage());  
	e.printStackTrace();  
}
%>
<%!
/**
* @Method: findFileSavePathByFileName
* @Description: 通過檔名和儲存上傳檔案根目錄找出要下載的檔案的所在路徑
* @param filename 要下載的檔名
* @param saveRootPath 上傳檔案儲存的根目錄,也就是/WEB-INF/upload目錄
* @return 要下載的檔案的儲存目錄
*/ 
public String findFileSavePathByFileName(String filename,String saveRootPath){
int hashcode = filename.hashCode();
int dir1 = hashcode&0xf; //0--15
int dir2 = (hashcode&0xf0)>>4; //0-15
//String dir = saveRootPath + "\\" + dir1 + "\\" + dir2; //upload\2\3 upload\3\5
String dir = saveRootPath;
File file = new File(dir);
if(!file.exists()){
//建立目錄
file.mkdirs();
}
return dir;
}

%>