Spring MVC文件上传及全局异常处理器

添加依赖


<dependency>
    <groupId>commons-fileuploadgroupId>
    <artifactId>commons-fileuploadartifactId>
    <version>1.3.1version>
dependency>

配置文件上传解析器


<bean id="multipartResolver" 
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="5242880" />
    <property name="defaultEncoding" value="UTF-8" />
bean>

测试

  • 编写controller

    @Controller
    @RequestMapping("/account")
    public class AccountController {
    
        @RequestMapping(path="/upload")
        public String upload(HttpServletRequest request, 
                                 MultipartFile upload,Model model) throws IOException {
            System.out.println("springmvc方式的文件上传");
            //获取要上传的文件目录
            String path = 
                request.getSession().getServletContext().getRealPath("/uploads");
            System.out.println("path:"+path);
            //根据文件上传的目录创建File对象,如果不存在则创建1个File对象
            File file = new File(path);
            if(!file.exists()){
                //创建一个file对象
                file.mkdirs();
            }
            //获取文件上传名称
            String filename = upload.getOriginalFilename();
            //完成文件上传
            upload.transferTo(new File(path,filename));
    
            model.addAttribute("msg", "欢迎你 springmvc");
            return "success";
        }
    }
    
  • 在index.jsp里面定义超链接

        <form action="/account/upload" method="post" enctype="multipart/form-data">
            文件: <input type="file" name="upload">input>
            <input type="submit" value="提交">
        form>
    

全局异常处理器

如果不加以异常处理,错误信息肯定会抛在浏览器页面上,这样很不友好,所以必须进行异常处理。

异常处理思路

系统的dao、service、controller出现都通过throws Exception向上抛出,最后由springmvc前端控制器交由异常处理器进行异常处理,如下图:

创建异常处理器

@Component
public class CustomExceptionResolver implements HandlerExceptionResolver {

	@Override
	public ModelAndView resolveException(HttpServletRequest request,
					HttpServletResponse response, Object handler, Exception ex) {
		ModelAndView modelAndView = new ModelAndView();
		modelAndView.addObject("message", ex.getMessage());
		modelAndView.setViewName("error");
		return modelAndView;
	}

}

测试

  • 编写controller
@Controller
@RequestMapping("/account")
public class AccountController {

   @RequestMapping("/findAccount14")
    public String findAccount14(Model model) {
        model.addAttribute("msg", "欢迎你 springmvc");
        //模拟异常信息
        int i = 10/0;
        return "success";
    }
}
  • 在index.jsp里面定义超链接
<a href="/account/findAccount14">异常处理器a>

你可能感兴趣的:(spring)