1. 实现一个加强的HttpServletResponse类,须要继承javax.servlet.http.HttpServletRequestWrapper类,经过重写本身须要加强的方法来实现(这种模式就叫作装饰者模式),使用该加强类在加上过滤器就能够实现无编码转换处理代码。javascript
public class MyRequest extends HttpServletRequestWrapper{ private HttpServletRequest req; public MyRequest(HttpServletRequest request) { super(request); req=request; } @Override public String getParameter(String name) { //解决编码问题,不管是post仍是get请求,都不须要在业务代码中对编码再处理 String method=req.getMethod(); if("get".equalsIgnoreCase(method)){ try { String str=req.getParameter(name); byte[] b=str.getBytes("iso8859-1"); String newStr=new String(b, "utf-8"); return newStr; } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } }else if("post".equalsIgnoreCase(method)){ try { req.setCharacterEncoding("utf-8"); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } //绝对不能删除此行代码,由于此行代码返回的就是编码以后的数据 return super.getParameter(name); } }
在过滤器中应用html
public class FilterTest4 implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException {} @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //生成加强的HttpServletRequest对象 HttpServletRequest req=(HttpServletRequest) request; MyRequest myReq=new MyRequest(req); //将加强的HttpServletRequest对象传入过滤器执行链中,在后面传入的request对象都会是加强的HttpServletRequest对象 chain.doFilter(myReq, response); } @Override public void destroy() {} }
1. JavaWeb中实现文件上传:java
<html> <head> <title>My JSP 'upload.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <form action="" method="post" enctype="multipart/form-data"> <input type="text" name="name"> 请选择文件:<input type="file" name="upload"> <input type="submit" value="上传"> </form> </body> </html>
import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.FileItem; import org.apache.commons.fileupload.FileUploadException; import org.apache.commons.fileupload.disk.DiskFileItemFactory; import org.apache.commons.fileupload.servlet.ServletFileUpload; public class UploadServlet extends HttpServlet{ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { /** * 1. 建立磁盘文件项工厂类 DiskFileItemFactory * 2. 建立核心解析Request类 ServletFileUpload * 3. 开始解析Request对象中的数据,并返回一个List集合 * 4. List中包含表单中提交的内容 * 5. 遍历集合,获取内容 */ DiskFileItemFactory fac=new DiskFileItemFactory(); ServletFileUpload upload=new ServletFileUpload(fac); upload.setHeaderEncoding("utf-8");//防止中文的文件名乱码 try { List<FileItem> fileItems = upload.parseRequest(req); for(FileItem item:fileItems){ //有多是普通文本项,好比<input type="text">标签提交上来的字符串 //也有多是<input type="submit" value="上传">上传的文件 //文件项与普通项有不一样的API来处理 //首先判断是普通文本项仍是文件项, if(item.isFormField()){ //true表示普通文本项 //获取文本项的name属性值 String name=item.getFieldName(); //获取对应的文本 String value=item.getString("utf-8");//防止中文乱码 System.out.println(name+":"+value); }else{ //false表示文件项 //先获取文件名称 String name=item.getName(); //获取文件项的输入流 InputStream in=item.getInputStream(); //获取服务器端文件存储的目标磁盘路径 String path=getServletContext().getRealPath("/upload"); System.out.println(path); //获取输出流,输出到本地文件中 OutputStream out=new FileOutputStream(path+"/"+name); //写入数据 int len=0; byte[] b=new byte[1024]; while((len=in.read(b))!=-1){ out.write(b,0,len); } in.close(); out.close(); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
注意:在文件上传时,会将form表单的属性enctype属性值为"multipart/form-data",当提交到服务端后,没法使用 req.getParameter(name) 方法来获取到内容,只有经过上面的方法来获取文本项。算法
2. 文件上传相关核心类:apache
//改进上面的文件上传代码,添加一个临时文件 public class UploadServlet extends HttpServlet{ @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { DiskFileItemFactory fac=new DiskFileItemFactory(); fac.setSizeThreshold(1024*1024);//设置缓冲区为1mb //设置临时文件的本地磁盘存储路径 File repository=new File(getServletContext().getRealPath("/temp")); fac.setRepository(repository); ServletFileUpload upload=new ServletFileUpload(fac); upload.setHeaderEncoding("utf-8");//防止中文的文件名乱码 try { List<FileItem> fileItems = upload.parseRequest(req); for(FileItem item:fileItems){ if(item.isFormField()){ String name=item.getFieldName(); String value=item.getString(); String value=item.getString("utf-8");//防止中文乱码 System.out.println(name+":"+value); }else{ String name=item.getName(); InputStream in=item.getInputStream(); String path=getServletContext().getRealPath("/upload"); System.out.println(path); OutputStream out=new FileOutputStream(path+"/"+name); int len=0; byte[] b=new byte[1024]; while((len=in.read(b))!=-1){ out.write(b,0,len); } in.close(); out.close(); } } } catch (FileUploadException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
3. 实现多文件上传(须要js技术):主要是更改jsp页面,经过js代码来添加多个文件进行上传,服务器代码无需更改浏览器
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8" contentType="text/html; charset=utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>My JSP 'upload.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <script type="text/javascript"> function run(){ var div=document.getElementById("divId"); div.innerHTML+= "<div><input type='file' name='upload'><input type='button' value='删除' onclick='del(this)'></div>" } function del(presentNode){ var div=document.getElementById("divId"); div.removeChild(presentNode.parentNode); } </script> <div> 多文件上传<br/> <form action="/Servlet/upload" method="post" enctype="multipart/form-data"> <input type="button" value="添加" onclick="run()"><br/> <div id="divId"> </div> <input type="submit" value="上传"> </form> </div> </body> </html>
4. 关于文件上传的一些问题:缓存
1. 传统文件下载方式有超连接下载或者后台程序下载两种方式。经过超连接下载时,若是浏览器能够解析,那么就会直接打开,若是不能解析,就会弹出下载框;然后台程序下载就必须经过两个响应头和一个文件的输入流。服务器
2. 后台程序下载:app
import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * @ClassName:DownLoadServlet * @Description:文件下载 * @author: * @date:2018年9月16日 */ public class DownLoadServlet extends HttpServlet{ @Override protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { //获取请求参数,知道要下载那个文件 String filename=req.getParameter("filename"); //设置响应头 String contentType=getServletContext().getMimeType(filename);//依据文件名自动获取对应的Content-Type头 res.setContentType(contentType); res.setHeader("Content-Dispotition", "attachment;filename="+filename);//设置该头,以附件形式打开下载 //获取文件的输入流 String path=getServletContext().getRealPath("/download")+"/"+filename; FileInputStream in=new FileInputStream(new File(path)); OutputStream out= res.getOutputStream(); byte[] b=new byte[1024]; int len=0; while((len=in.read(b))!=-1){ out.write(b,0,len); } in.close(); out.close(); } }