• SpringMVC学习(六)SpringMVC实现文件上传、SpringMVC的异常处理



    1、SpringMVC实现文件上传

    导入文件上传的jar包

    <dependency>
      <groupId>commons-fileuploadgroupId>
      <artifactId>commons-fileuploadartifactId>
      <version>1.3.1version>
    dependency>
    <dependency>
      <groupId>commons-iogroupId>
      <artifactId>commons-ioartifactId>
      <version>2.4version>
    dependency>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    在Springmvc.xml配置文件上传解析器

    
     <bean id="multipartResolver"
           class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
     
     <property name="maxUploadSize" value="8388608" />
     bean>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    编写文件上传的html页面

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Titletitle>
    head>
    <body>
    <h3>文件上传h3>
    
    <form id="addForm"  action="/SpringMvc/file/upload" method="post" enctype="multipart/form-data">
        选择文件:<input type="file" name="file" width="120px">
        <input type="submit" value="上传">
    form>
    
    <div id="upMenu" class="white_content">
        <form id="downForm"   lay-filter="updata" action="/SpringMvc/file/down" method="get">
            <input type="text" id="filename" name="filename">
            <input type="submit" value="下载">
        form>
        <input type="button" value="完成"/>
    div>
    
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    controller层

    @Controller
    @RequestMapping("/file")
    public class FileController {
    
    
        /**
         * 文件上传功能
         * @param file
         * @return
         * @throws IOException
         */
        @RequestMapping(value="/upload",method= RequestMethod.POST)
        @ResponseBody
        public  String upload(@RequestParam("file") MultipartFile file, HttpServletRequest request) throws IOException {
            // uploads文件夹位置
            String rootPath = request.getSession().getServletContext().getRealPath("WEB-INF/upload");
            // 原始名称
            String originalFileName = file.getOriginalFilename();
            // 新文件
            File newFile = new File(rootPath + File.separator  + File.separator + originalFileName);
            // 判断目标文件所在目录是否存在
            if( !newFile.getParentFile().exists()) {
                // 如果目标文件所在的目录不存在,则创建父目录
                newFile.getParentFile().mkdirs();
            }
            System.out.println(newFile);
            // 将内存中的数据写入磁盘
            file.transferTo(newFile);
            return  "{\"data\":\"success\"}";
        }
    
        /**
         * 文件下载功能
         * @param request
         * @param response
         * @throws Exception
         */
        @RequestMapping("/down")
        public void down(HttpServletRequest request, HttpServletResponse response) throws Exception{
            String filename = request.getParameter("filename");
            System.out.println(filename);
            //模拟文件,myfile.txt为需要下载的文件
            String fileName = request.getSession().getServletContext().getRealPath("WEB-INF/upload")+"/"+filename;
            //获取输入流
            InputStream bis = new BufferedInputStream(new FileInputStream(new File(fileName)));
            //假如以中文名下载的话
           // String filename = "下载文件.txt";
            //转码,免得文件名中文乱码
            filename = URLEncoder.encode(filename,"UTF-8");
            //设置文件下载头
            response.addHeader("Content-Disposition", "attachment;filename=" + filename);
            //1.设置文件ContentType类型,这样设置,会自动判断下载文件类型
            response.setContentType("multipart/form-data");
            BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());
            int len = 0;
            while((len = bis.read()) != -1){
                out.write(len);
                out.flush();
            }
            out.close();
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62

    2、SpringMVC的异常处理

    1. 异常处理思路

    Controller调用service,service调用dao,异常都是向上抛出的,最终有DispatcherServlet找异常处理器进行异常的处理。

    2. SpringMVC的异常处理

    ①:使用自己处理异常
    controller代码

    /**
     * 自己处理异常
     * @return
     */
    @RequestMapping("/findAll")
    public String findAll(Model model){
        try {
            System.out.println("执行了...");
            // 模拟异常
            int a = 10/0;
        }catch (Exception e){
            model.addAttribute("errorMsg","系统正在维护,请联系管理员");
            return "404";
        }
        return "suc";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16

    404页面

    DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>错误提示页面title>
    head>
    <body>
    <h1>404  <b th:text="${errorMsg}">b>h1>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    ②:使用自己处理异常
    controller代码

    /**
     * 使用异常处理器方式
     * @return
     */
    @RequestMapping("/findAll2")
    public String findAll2(){
        System.out.println("执行了...");
        //模拟异常
        int a = 10 / 0;
        return "suc";
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    自定义异常类

    public class SysException extends Exception{
        // 提示消息
        private String message;
    
        public SysException(String message){
            this.message = message;
        }
    
        @Override
        public String getMessage() {
            return message;
        }
    
        public void setMessage(String message) {
            this.message = message;
        }
    
        @Override
        public String toString() {
            return "SysException{" +
                    "message='" + message + '\'' +
                    '}';
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24

    自定义异常处理器

    /**
     * 异常处理器
     */
    public class SysExceptionResolver implements HandlerExceptionResolver {
    
        /**
         * 程序出现了异常,调用异常处理器中的方法
         * @param httpServletRequest
         * @param httpServletResponse
         * @param o
         * @param e e是Throwable的实例异常对象,用在catch语句中,相当于一个形参,一旦try捕获到了异常,那么就将这个异常信息交给e
         * @return
         */
        public ModelAndView resolveException(HttpServletRequest httpServletRequest,
                                             HttpServletResponse httpServletResponse, Object o, Exception e) {
    
    
            e.printStackTrace(); //在命令行打印异常信息在程序中出错的位置及原因。
            // 做强转
            SysException exception = null;
            // 判断
            if(e instanceof SysException){
                exception = (SysException)e;
            }else{
                exception = new SysException("系统正在维护,请联系管理员");
    
            }
            // 存入异常提示信息
            ModelAndView mv = new ModelAndView();
            mv.addObject("errorMsg",exception.getMessage());
            // 设置跳转的页面
            mv.setViewName("404");
            return mv;
        }
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36

    配置异常处理器

    
    <bean id="sysExceptionResolver" class="com.qcby.conf.SysExceptionResolver" />
    
    • 1
    • 2
  • 相关阅读:
    聚观早报 | 中国新能源车企组团“出海”;盒马鲜生门店突破350家
    8.idea 使用 docker 构建 java web 项目
    显示支付结果_WebSocket实现_方案2
    DASCTF X GFCTF 2022十月挑战赛 - pwn
    4.矩阵的几何意义、变基与迹
    性能测试度量指标
    sql-labs(11-20)
    大数据培训课程MapTask工作机制
    wget命令
    软件开发进度中,如何进行高风险预警管理?
  • 原文地址:https://blog.csdn.net/m0_51963973/article/details/126199133