标签8)displayName:等价于web.xml配置文件中的 value :等价于web.xml配置文件中的 标签displayName:等价于web.xml配置文件中的
文件2:
定义UploadServlet,实现上传功能;注解内容如下:
@WebServlet("/uploadServelt")@MultipartConfig( location = "E:\\\upload",//文件存放路径 maxFileSize = 8388608,//最大上传文件大小 fileSizeThreshold = 819200,//当数据量大于该值时,内容将被写入文件。 maxRequestSize = -1 //针对该 multipart/form-data 请求最大数量,默认值为 -1,表示没有限制。以字节为单位。 )
定义UploadServlet,实现上传功能;核心代码如下 :
//获取所有上传文件对应的Part对象 Collectionparts = request.getParts(); //遍历上传文件对应的part对象,将文件写入上传文件目录 for (Iterator iterator = parts.iterator(); iterator.hasNext();) { Part part = iterator.next(); //获取content-disposition请求头,提取文件名称 String cotentDisposition = part.getHeader("content-disposition"); System.out.println("cotent-disposition="+cotentDisposition); String fileName = null; //使用正则表达是部分匹配,获取上传文件名称 Pattern pattern = Pattern.compile("filename=".+""); Matcher matcher = pattern.matcher(cotentDisposition); if(matcher.find()){ fileName = matcher.group(); System.out.println("fileName="+fileName); fileName = fileName.substring(10, fileName.length()-1); System.out.println("subFileName="+fileName); } if(fileName!=null){ part.write(fileName); }
定义过滤器,解决文件名统一编码问题;核心代码如下 :
public void init(FilterConfig filterConfig) throws ServletException { //初始化 glEncoding = filterConfig.getInitParameter("encoding"); } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { if (glEncoding != null) { // request编码 request.setCharacterEncoding(glEncoding); // response编码 response.setContentType("text/html;charset=" + glEncoding); } // 传给下一个过滤器 chain.doFilter(request, response); }
四.常见问题
Servlet3.0的非阻塞特性是什么意思?如何实现?Servlet3.0中有哪几个常用的注解类型?Servlet3.0对文件上传进行了哪些支持?
五.总结
Servlet3.0中增加了非阻塞特性支持,可以在web.xml中或者使用注解进行配置,使得Servlet可以异步处理请求;Servlet3.0可以使用注解替代web.xml的部分内容,常用的注解类型有@WebServlet、@WebFilter、@WebListener、@WebInitParam。Servlet3.0中对文件上传进行了支持,提供了Part接口以及@MultipartConfig注解,可以方便地实现文件上传;
閱讀更多 跟老司機學Java 的文章