利用HttpServletRequest与HttpServletResponse下载资源

继续上一篇HttpServletRequest和HttpServletResponse的学习,应用于下载网页上提供的文件资源.

链接在这:HttpServletRequest和HttpServletResponse的初步学习

1.下载资源有三种方式

  • 直接以超链接的方式下载,让tomcat的默认Servlet(DefaultServlet)去提供下载,DefaultServlet专门用于处理放在tomcat服务器上的静态资源。
  • 手动编码提供下载
  • 手动编码提供下载带有中文名字的资源

样例代码给出~

index.html

<!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>
HttpServletResponse,下载资源<br>
1.直接以超链接的方式下载<br>
<a href="download/a.jpg">a.jpg</a><br>
<a href="download/b.jpg">b.jpg</a><br>
<a href="download/c.jpg">c.jpg</a><br>

2.手动编码提供下载<br>
<a href="Download?filename=a.jpg">a.jpg</a><br>
<a href="Download?filename=b.jpg">b.jpg</a><br>
<a href="Download?filename=c.jpg">c.jpg</a><br>

3.手动编码提供下载带有中文名字的资源<br>
<a href="Download?filename=a.jpg">a.jpg</a><br>
<a href="Download?filename=b.jpg">b.jpg</a><br>
<a href="Download?filename=c.jpg">c.jpg</a><br>
<a href="Download?filename=快乐.jpg">快乐.jpg</a><br>

</body>
</html>

 

对应的Servlet代码给出~

Download.java

 

package cw.Servlet;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import sun.misc.BASE64Encoder;

/**
 * Servlet implementation class Download
 */
public class Download extends HttpServlet {
	protected void doGet(HttpServletRequest request, 
                    HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//获取要下载的文件名字
		String filename=request.getParameter("filename");	
		
		//来一个get请求,这个filename有中文
		filename=new String(filename.getBytes("ISO-8859-1"),"UTF-8");
		System.out.println("filename="+filename);
		
		//获取这个文件在tomcat里面的绝对路径地址
		String path=getServletContext().getRealPath("Download/"+filename);
		
		/*
		 * 如果文件的名字带有中文,需要队整个文件名进行编码处理
		 * 针对浏览器类型,对文件名字做编码处理,如果是IE,或者是chrome,使用URLEncoding编码
		 * 如果是Firefox,使用Base64编码
		 */
		//对中文的名字进行编码处理
		
		//获取来访的客户端类型
		String client_type=request.getHeader("User-Agent");
		if(client_type.contains("Firefox")){
			filename=firefox(filename);		//调用编码处理过后filename的firefox函数
		}else{
			filename=URLEncoder.encode(filename,"UTF-8");	
		}
		
		//让浏览器收到资源时,以下载的方式提醒用户,而不是直接展示
		response.setHeader("Content-Disposition", "attachment;filename="+filename);
		
		//转换成输入流
		InputStream is=new FileInputStream(path);
		OutputStream os=response.getOutputStream();
		int len=0;
		byte[] buffer=new byte[1024];
		while((len=is.read(buffer))!=-1){
			os.write(buffer,0,len);
		}
		os.close();
		is.close();
	}
	protected void doPost(HttpServletRequest request, 
                HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
	
	public String firefox(String name){
		BASE64Encoder base64=new BASE64Encoder();
		try{
			return "=?UTF-8?B?"+new String(base64.encode(name.getBytes("UTF-8")))+"?=";
		}catch(UnsupportedEncodingException e){
			e.printStackTrace();
			throw new RuntimeException();
		}
	}
}

 

2.地址重定向与请求转发的区别

  • 重定向:地址上显示的是最后的那个资源的路径地址

localhost:9000/JavaWeb_1/login_success.html

1).请求次数最少有两次,服务器在第一次请求后,会返回302以及一个地址,浏览器再根据这个地址执行第二次访问
2).可以跳转到任意路径,不是自己的工程也可以跳
3).执行两次请求,效率较低
4).后续的请求,没法使用上一次的request存储的数据,或者没法使用上一次的request对象,因为是两次不同的请求

  • 请求转发:地址上显示的请求servlet的地址

localhost:9000/JavaWeb_1/loginS?username=admin&password=123&登陆=提交

1).请求次数只有一次,因为是服务器内部帮客户端执行了后续的工作
2).只能跳转到自己项目的资源路径
3).因为只执行一次请求,所以效率较高
4).可以使用上一次的request对象

 

样例代码给出~

login.html

<!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>
	<h2>请输入登陆信息</h2>
	<!-- <form action="LoginServlet" method="get"> -->
	<!-- <form action="HServlet" method="get"> -->
	<form action="loginS" method="get">
		账号:<input type="text" name="username" />
		密码:<input type="text" name="password" />
		<input type="submit" name="登陆" />
	</form>	
</body>
</html>

 

login_success.html

 

<!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>
	<h2>登陆成功!</h2>
	
</body>
</html>

 

loginS.java

 

package cw.Servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class loginS
 */
public class loginS extends HttpServlet {

	protected void doGet(HttpServletRequest request, 
        HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.setContentType("text/html;charset=UTF-8");
		String username=request.getParameter("username");
		String password=request.getParameter("password");
		if("admin".equals(username)&&"123".equals(password)){
			response.getWriter().write("登陆成功!");
			//1.重定向
			/*	早期的写法
			response.setStatus(302);
			response.setHeader("location", "login_success.html");
			*/
		
			//重定向的写法:重新定位方向
			//response.sendRedirect("login_success.html");
			//2.请求转发的写法
			request.getRequestDispatcher("login_success.html").forward(request, response);
		}else{
			response.getWriter().write("登陆失败!");
		}
	}

	protected void doPost(HttpServletRequest request,
         HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章