✿抽取出工具类 [文件上传工具类]:出现异常[文件格式错误],且错误信息需要显示到注册界面(跳转)
-------工具类:不建议在工具类里进行控制界面跳转【那是servlet的职责】
❀解决:通过定义异常类处理,将异常抛出给调用工具类的那个servlet,然后servlet再捕获自定义的异常,然后控制界面跳转。
❀ 工具类[FileUtil]
package com.shan.upload; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.List; import java.util.Scanner; import java.util.UUID; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; 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; import org.apache.commons.io.FilenameUtils; public class FileUtil { // 允许接收的图片类型 private static final String ALLOWED_IMAGE_TYPE = "png;gif;jpg;jpeg;jiff"; public static void upload(HttpServletRequest req) throws IOException { req.setCharacterEncoding("utf-8"); // 解析检查请求 boolean isMultipart = ServletFileUpload.isMultipartContent(req); if (!isMultipart) { return; } // 创建FileItemFactory对象---目的是为了创建FileItem对象【FileItem对象是form表单的表单控件的封装】 DiskFileItemFactory factory = new DiskFileItemFactory(); // 创建文件上传 ServletFileUpload upload = new ServletFileUpload(factory); // 解析请求 List<FileItem> items; try { items = upload.parseRequest(req); for (FileItem item : items) { String filedName = item.getFieldName(); if (item.isFormField()) { // 普通表单控件 String value = item.getString(); } else { // ---------------判断文件格式是否允许 // 判断方式一:采用拓展名进行判断 String[] allowedImageTtype = ALLOWED_IMAGE_TYPE.split(";"); String ext = FilenameUtils.getExtension(item.getName()); // 将数组转化为list集合,这样就可以直接利用人家的contain方法,不用自己写遍历 // ---------------文件格式错误,抛出自定义的异常类型LoginException---------- if (!Arrays.asList(allowedImageTtype).contains(ext)) { throw new LoginException("亲,请上传正确的图片格式!"); } // ----------------------------------- // 避免文件名相同的覆盖【使用唯一的UUID】 String fileName = UUID.randomUUID().toString() + "." + FilenameUtils.getExtension(item.getName()); // 保存到当前应用下["/" 表示是当前应用-webapp] // 获取servletContext 当前类是servlet类的话,即可通过super获取,否则就通过请求获取 String dir = req.getServletContext().getRealPath("/upload"); item.write(new File(dir, fileName));// 把二进制数据写到哪个文件中 } } } catch (LoginException e) { //因为除了自定义的错误外还有其他错误的存在,一般要使用最大的错误类型Exception 捕获 //需要在最大错误类型Exception之前捕获下咱自定义的错误 LoginException,然后将它往外抛,抛给调用者[UploadServlet] throw e; } catch (Exception e) { e.printStackTrace(); } } }
❀ 自定义异常类[LoginExcption]
package com.shan.upload; public class LoginException extends RuntimeException{ private static final long serialVersionUID = 1L; /** * @param message 异常的信息 * @param cause 异常的根本原因 */ public LogicException(String message, Throwable cause) { super(message, cause); } /** * @param message 错误信息 */ public LogicException(String message) { super(message); } }
❀ 上传文件类[UploadServlet]
package com.shan.upload; import java.io.File; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Scanner; import java.util.UUID; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; 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; import org.apache.commons.io.FilenameUtils; @WebServlet("/upload") public class UploadServlet extends HttpServlet{ @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException { req.setCharacterEncoding("utf-8"); try { FileUtil.upload(req); }catch (LoginException e) { //捕获自定义的异常,获取错误信息,然后控制界面跳转 String errorMsg = e.getMessage(); req.setAttribute("errorMsg", errorMsg); req.getRequestDispatcher("/input.jsp").forward(req, resp); } } }
//✿ 捕获A错误类型,为了使用B异常处理,在捕获A错误类型后,抛成B异常
.......} catch(FileSizeLimitExceededException e) { //捕获A错误类型,为了使用B异常处理,在捕获A错误类型后,抛成B异常 throw new LoginException("亲,单个文件大小不能超过1kb", e); }catch (LogicException e) { throw e; //将错误进行往外抛,抛给调用者【UploadServlet】 } catch (Exception e) { e.printStackTrace(); }