Java文件下载异常处理_SpringMVC 上传下载 异常处理

SpringMVC 上传下载 异常处理

上一章节对SpringMVC的表单验证进行了详细的介绍,本章节介绍SpringMVC文件的上传和下载(重点),国际化以及异常处理问题。这也是SpringMVC系列教程中的最后一节,文章底部会提供该系列的源码地址。

首先看效果图(文件上传,下载和异常处理)

bVXied?w=841&h=547

pom.xml,文件上传和下载是需要两个jar包: commons-fileupload.jar 和 commons-io.jar

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

4.0.0

com.springmvc

springmvc

0.0.1-SNAPSHOT

war

maven-compiler-plugin

1.7

1.7

UTF-8

4.1.3.RELEASE

org.springframework

spring-webmvc

${spring.version}

org.springframework

spring-context

${spring.version}

org.springframework

spring-aop

${spring.version}

org.springframework

spring-core

${spring.version}

org.springframework

spring-web

${spring.version}

javax.servlet

javax.servlet-api

4.0.0

provided

javax.servlet

jstl

1.2

taglibs

standard

1.1.2

javax.servlet.jsp

jsp-api

2.2

provided

org.hibernate

hibernate-validator

5.4.1.Final

javax.validation

validation-api

1.1.0.Final

commons-fileupload

commons-fileupload

1.3.1

commons-io

commons-io

2.4

SpringMVC配置文件

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xmlns:context="http://www.springframework.org/schema/context"

xmlns:mvc="http://www.springframework.org/schema/mvc"

xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd

http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

class="org.springframework.context.support.ResourceBundleMessageSource">

class="org.springframework.web.servlet.i18n.SessionLocaleResolver">

class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor">

class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">

exception

FileUploadController.java 文件上传,下载和国际化知识点

国际化步骤

第一步,在SpringMVC配置文件中配置 SessionLocaleResolver(bean的id必须是localeResolver) 和 LocaleChangeInterceptor(bean放在mvc:interceptors 拦截器中)两个bean。

第二步,视图页面引入 fmt 标签,并用 设置值。

第三步,语言切换的链接,其格式:English。

第四步,创建链接的目标方法,其参数为Locale 类型参数。

第五步,准备语言文件,i18n_en_US.properties 和 i18n_zh_CN.properties,配置xxx的对应语言。

文件上传和下载

第一步,在SpringMVC配置文件中配置 CommonsMultipartResolver,并设置默认编码格式和最大尺寸

第二步,视图页面创建一个form表单,并设置 enctype="multipart/form-data"

第三步,目标方法接收参数的类型为 MultipartFile ,然后是文件流的操作。

第四步,看代码吧!

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.io.OutputStream;

import java.util.Locale;

import java.util.Map;

import javax.servlet.ServletContext;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.context.support.ResourceBundleMessageSource;

import org.springframework.http.HttpHeaders;

import org.springframework.http.HttpStatus;

import org.springframework.http.ResponseEntity;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

import org.springframework.web.multipart.MultipartFile;

@Controller

public class FileUploadController {

@Autowired

private ResourceBundleMessageSource messageSource;

/**

* 国际化

* 第一步,在SpringMVC配置文件中,配置 SessionLocaleResolver 和 LocaleChangeInterceptor

* 第二步,准备语言文件,i18n_en_US.properties 和 i18n_zh_CN.properties

* 第三步,目标方法中,参数加入Locale对象。

*/

@RequestMapping("/fileUpload")

public String fileUpload(Locale locale) {

// String val = messageSource.getMessage("file", null, locale);

// System.out.println(val);

return "fileUpload";

}

// MultipartFile 上传文件必用的变量类型

@RequestMapping("/testFileUpload")

public String testFileUpload(@RequestParam("desc") String desc, @RequestParam("file") MultipartFile file,

Map map, HttpServletRequest request) {

InputStream in = null;

OutputStream out = null;

String fileName = file.getOriginalFilename(); // 获取文件名

try {

String realPath = request.getServletContext().getRealPath("uploads/");

in = file.getInputStream();

byte[] buffer = new byte[1024];

String filePath = realPath + "/" + fileName; // 文件上传路径

out = new FileOutputStream(filePath);

int len = 0;

while ((len = in.read(buffer)) != -1) {

out.write(buffer, 0, len);

}

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (null != out) {

out.close();

}

if (null != in) {

in.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

map.put("fileName", fileName);

return "fileUpload";

}

// 不适合大文件的下载,适用于简单的下载场景。

@RequestMapping("/downLoadFile")

public ResponseEntity downLoadFile(@RequestParam("fileName") String fileName, HttpSession session) {

byte [] body = null;

ServletContext servletContext = session.getServletContext();

InputStream in = null;

ResponseEntity response = null;

try {

in = servletContext.getResourceAsStream("/uploads/"+fileName);

body = new byte[in.available()];

in.read(body);

HttpHeaders headers = new HttpHeaders();

headers.add("Content-Disposition", "attachment;filename="+fileName);

HttpStatus statusCode = HttpStatus.OK;

response = new ResponseEntity(body, headers, statusCode);

} catch (IOException e) {

e.printStackTrace();

} finally {

try {

if (null != in) {

in.close();

}

} catch (IOException e) {

e.printStackTrace();

}

}

return response;

}

}

fileUpload.jsp 文件上传下载前端页面

SpringMVC 快速入门

常用的三种异常处理

@ExceptionHandler 注解

第一步,创建一个用注解@ControllerAdvice 修饰的切面类(也可以是普通类)。

第二步,创建一个目标方法,并用注解@ExceptionHandler 修饰,value值是一个数组,值是异常类。

第三步,目标方法的的参数必须有Exception 类型的参数,用于获取运行时发生的异常。

第四步,目标方法若想把异常返回给页面,可以用ModelAndView 类型作为返回值,而不能用Map作为参数返回。

@ResponseStatus 注解

第一步,创建一个被注解@ResponseStatus 修饰的自定义异常类,value值是状态码,reason值是字符串。

第二步,在目标方法执行时抛出自定义异常。

SimpleMappingExceptionResolver Bean

第一步,在SpringMVC的配置文件中 配置Bean SimpleMappingExceptionResolver 。

第二步,设置exceptionAttribute 模型Model,必须和页面上的值一致。

第三步,设置exceptionMappings 视图View,只有当异常触发时跳转到视图页面。

注意细节,看代码

StudyExceptionHandlerAdvice.java 切面类

import org.springframework.web.bind.annotation.ControllerAdvice;

import org.springframework.web.bind.annotation.ExceptionHandler;

import org.springframework.web.servlet.ModelAndView;

/**

* 1 @ExceptionHandler 注解修饰的方法可以放在普通类中,也可以放在切面类中(@ControllerAdvice 注解修饰的类)。前者表示只处理当前类的异常,后者表示处理全局的异常。

* 2 @ExceptionHandler 注解修饰的方法参数中,不能有Map,否则会提示:。若希望把异常信息返回给前端,可以使用ModelAndView

* 3 @ExceptionHandler 注解修饰的多个方法中,优先级原则是就近原则(和异常精度越近的异常,优先执行)。

*/

@ControllerAdvice

public class StudyExceptionHandlerAdvice {

@ExceptionHandler({ArithmeticException.class})

public ModelAndView handleArithmeticException(Exception exception){

System.out.println("ArithmeticException 出异常了: " + exception);

ModelAndView mv = new ModelAndView("exception");

mv.addObject("exception", "ArithmeticException 出异常了: " + exception);

return mv;

}

/*@ExceptionHandler({RuntimeException.class})

public ModelAndView handleRuntimeException(Exception exception){

System.out.println("RuntimeException 出异常了: " + exception);

ModelAndView mv = new ModelAndView("exception");

mv.addObject("exception", "RuntimeException 出异常了: " + exception);

return mv;

}*/

}

ResponseStatusException.java 自定义异常类

import org.springframework.http.HttpStatus;

import org.springframework.web.bind.annotation.ResponseStatus;

@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "ResponseStatusException : 自定义异常原因")

public class ResponseStatusException extends RuntimeException{

}

StudyExceptionController.java 异常处理测试类

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;

@Controller

public class StudyExceptionController {

@RequestMapping("/exception")

public String exception(){

return "exception";

}

@RequestMapping("/simpleMappingExceptionResolver")

public String simpleMappingExceptionResolver(@RequestParam("num") int num){

String [] args = new String[10];

System.out.println("通过配置bean,来处理某一种异常导致的所有问题。" + args[num]);

return "exception";

}

@RequestMapping(value="/testResponseStatus")

public String testResponseStatus(@RequestParam("num") Integer num){

System.out.println("@ResponseStatus 自定义异常");

if (0 == num) {

throw new ResponseStatusException();

}

return "exception";

}

@RequestMapping("/testExceptionHandler")

public String testExceptionHandler(@RequestParam("num") Integer num){

System.out.println("@ExceptionHandler - result: " + (10 / num));

return "exception";

}

}

exception.jsp 异常处理前端页面

SpringMVC 快速入门

SpringMVC 异常处理


@ExceptionHandler : testExceptionHandler?num=0


SimpleMappingExceptionResolver : simpleMappingExceptionResolver?num=20


@ResponseStatus : testResponseStatus?num=0


${exception}

到这里,SpringMVC的教程就结束了,有什么好的建议和问题,可以提出来。大家一起成长!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
对于Spring MVC来说,文件上传和下载是常见的功能之一。下面是关于如何实现文件上传和下载的基本步骤: 1. 文件上传: - 在Spring MVC的配置文件中,添加`CommonsMultipartResolver`来解析文件上传请求。 - 创建一个表单页面,使用`enctype="multipart/form-data"`属性,确保可以上传文件。 - 在Controller中创建一个处理文件上传请求的方法,使用`@RequestParam("file") MultipartFile file`注解来接收文件。 - 在方法内部,可以通过`file.getInputStream()`来获取文件的输入流,进而实现上传操作。 2. 文件下载: - 在Controller中创建一个处理文件下载请求的方法。 - 在方法内部,使用`HttpServletResponse`对象设置响应头信息,包括`Content-Disposition`和`Content-Type`。 - 通过`response.getOutputStream()`获取输出流,并将文件的内容写入输出流。 需要注意的是,为了确保文件上传和下载的安全性,可以进行一些额外的处理,例如限制文件类型、大小等。 以下是一个示例代码,用于演示文件上传和下载: ```java @Controller public class FileController { @Autowired private ServletContext servletContext; @RequestMapping(value = "/upload", method = RequestMethod.POST) public String upload(@RequestParam("file") MultipartFile file) { try { String fileName = file.getOriginalFilename(); String filePath = servletContext.getRealPath("/uploads/") + fileName; file.transferTo(new File(filePath)); return "redirect:/success"; } catch (Exception e) { e.printStackTrace(); return "redirect:/error"; } } @RequestMapping(value = "/download", method = RequestMethod.GET) public void download(HttpServletResponse response) { try { String fileName = "example.txt"; String filePath = servletContext.getRealPath("/downloads/") + fileName; File file = new File(filePath); InputStream inputStream = new FileInputStream(file); response.setHeader("Content-Disposition", "attachment; filename=" + fileName); response.setContentType("application/octet-stream"); IOUtils.copy(inputStream, response.getOutputStream()); response.flushBuffer(); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } } ``` 上述代码中,`servletContext.getRealPath()`方法用于获取文件的实际路径,`IOUtils.copy()`方法用于将文件内容写入输出流。 请注意,上述示例仅为演示目的,实际应用中可能需要进行更多的异常处理、文件校验等操作。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值