spring mvc 文件上传 和 异常页面处理
文件上传的传统方式
1. 导入文件上传的jar包
<dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>1.3.1</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency>
2. 编写文件上传的JSP页面
<form action="user/fileupload1" method="post" enctype="multipart/form-data"> 选择文件:<input type="file" name="upload"/><br> <input type="submit" value="上传"> </form>
3. 编写文件上传的Controller控制器
/** * 传统文件上传 * @return */ @RequestMapping("/fileupload1") public String fileupload1(HttpServletRequest request) throws Exception { System.out.println("文件上传1..."); // 使用fileupload组件完成文件上传 // 上传的目的地 String path = request.getSession().getServletContext().getRealPath("/uploads/"); // 判断该路径是否存在 File file = new File(path); if(!file.exists()){ file.mkdirs(); } // 解析request对象,获取上传文件项 DiskFileItemFactory factory = new DiskFileItemFactory(); ServletFileUpload upload = new ServletFileUpload(factory); // 解析request List<FileItem> items = upload.parseRequest(request); // 遍历 for(FileItem item:items){ // 进行判断:当前item是否是上传文件项 if(item.isFormField()){ // 是普通表单项,不用处理 }else { // 是上传文件项 // 获取上传文件名称 String filename = item.getName(); // 完成文件上传 item.write(new File(path,filename)); // 删除临时文件 item.delete(); } } return "success"; }
SpringMVC方式文件上传
1. SpringMVC框架提供了MultipartFile对象,该对象表示上传的文件,要求变量名称必须和表单fifile标签的name属性名称相同
![](https://img2020.cnblogs.com/blog/1510654/202004/1510654-20200419110635669-973869199.bmp)
1.jsp页面
<h3>springmvc文件上传</h3> <form action="user/fileupload2" method="post" enctype="multipart/form-data"> 选择文件:<input type="file" name="upload"/><br> <input type="submit" value="上传"> </form>
2.编写控制器代码
/** * springmvc文件上传 * @param request * @param upload :文件上传项,这个和jsp页面的文件选择域中的name属性必须一致 * @return * @throws Exception */ @RequestMapping("/fileupload2") public String fileupload2(HttpServletRequest request, MultipartFile upload) throws Exception { System.out.println("文件上传2..."); // 上传的目的地 String path = request.getSession().getServletContext().getRealPath("/uploads/"); // 判断该路径是否存在 File file = new File(path); if(!file.exists()){ file.mkdirs(); } // 获得文件名 String filename = upload.getOriginalFilename(); // 完成文件上传 upload.transferTo(new File(path,filename)); return "success"; }
3.springmvc.xml配置文件解析器对象
<!-- 配置文件解析器对象,要求id名称必须是multipartResolver --> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!--文件最大size-->
<property name="maxUploadSize" value="10485760"/>
</bean>
异常处理
1. 异常处理思路
Controller调用service,service调用dao,异常都是向上抛出的,最终有DispatcherServlet找异常处理器进行异常的处理。
2.自定义异常类SysException
package cn.itcast.exception; public class SysException extends Exception{ private String msg; public SysException(String msg) { this.msg = msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
2.控制器触发异常:
@RequestMapping("testException") public String testException()throws SysException{ System.out.println("testException执行了..."); try { // 模拟异常 int a=10/0; } catch (Exception e) { e.printStackTrace(); // 抛出自定义异常 System.out.println("查询用户出现异常"); throw new SysException("查询用户出现异常。。。"); } return "success"; }
3.异常处理器处理异常
/** * 异常处理器 */ public class SysExceptionResolver implements HandlerExceptionResolver { @Override public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception ex) { // 获取异常对象 SysException e = null; if(ex instanceof SysException){ e = (SysException)ex; }else { e = new SysException("系统正在维护"); } ModelAndView mv = new ModelAndView(); mv.addObject("errorMsg",e.getMsg()); mv.setViewName("error"); return mv; } }
4.配置异常处理器
<!-- 配置异常处理器 -->
<bean id="sysExceptionResolver" class="cn.itcast.exception.SysExceptionResolver"/>
5.还需要失败页面error.jsp
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
<%-- Created by IntelliJ IDEA. User: ASUS Date: 2020/4/19 Time: 10:48 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %> <html> <head> <title>Title</title> </head> <body> ${errorMsg} </body> </html>