jsp里面写java方法_如何在jsp中写一个java方法

一般用在jsp中写java方法

代码如下:

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;

}

%>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值