当前位置: 首页 > news >正文

SpringMVC的架构有什么优势?——异常处理与文件上传(五)

前言

在这里插入图片描述
「作者主页」:雪碧有白泡泡
「个人网站」:雪碧的个人网站
「推荐专栏」

java一站式服务
React从入门到精通
前端炫酷代码分享
★ 从0到英雄,vue成神之路★
uniapp-从构建到提升
从0到英雄,vue成神之路
解决算法,一个专栏就够了
架构咱们从0说
★ 数据流通的精妙之道★
★后端进阶之路★

请添加图片描述

文章目录

  • 前言
  • 异常处理
    • 1. 异常处理(Exception Handling):
    • 2. 配置异常处理器(Exception Handler Configuration):
    • 3. 处理HTTP错误码(Handle HTTP Status Codes):
  • 文件上传
    • 1. 配置文件上传(Configure File Upload):
    • 2. 处理文件上传(Handle File Upload):
    • 3. 处理多个文件上传(Handle Multiple File Upload):
  • Restful支持
    • 1. 创建Restful控制器(Create Restful Controller):
    • 2. 配置Restful消息转换器(Configure Restful Message Converters)

在这里插入图片描述

异常处理

异常处理是任何应用程序必不可少的组件。Spring MVC提供了一种方便的机制来捕获和处理异常,并返回友好的错误信息。
异常处理是任何应用程序必不可少的组件。在Web应用程序中,当遇到异常时,通常会返回HTTP错误码和对应的错误信息,这对于终端用户来说并不友好。Spring MVC提供了一种方便的机制来捕获和处理异常,并返回友好的错误信息。

下面我们将深入探讨Spring MVC异常处理的核心概念和相应Java代码示例。

1. 异常处理(Exception Handling):

在Spring MVC框架中,我们可以使用@ControllerAdvice注解定义一个全局的异常处理类。该类可以定义多个方法,每个方法都处理一个特定类型的异常,并返回友好的错误信息。

@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(SQLException.class)public ModelAndView handleSQLException(HttpServletRequest request, SQLException ex) {ModelAndView modelAndView = new ModelAndView();modelAndView.addObject("exception", ex.getMessage());modelAndView.addObject("url", request.getRequestURL());modelAndView.setViewName("error");return modelAndView;}@ExceptionHandler(Exception.class)public ModelAndView handleException(HttpServletRequest request, Exception ex) {ModelAndView modelAndView = new ModelAndView();modelAndView.addObject("exception", ex.getMessage());modelAndView.addObject("url", request.getRequestURL());modelAndView.setViewName("error");return modelAndView;}
}

在上面的示例中,我们定义了一个名为GlobalExceptionHandler的全局异常处理类,并在其中定义了两个方法:handleSQLException()和handleException()。这两个方法分别处理SQLException和Exception类型的异常。在处理过程中,我们使用ModelAndView对象来设置错误信息,并返回"error"视图。

2. 配置异常处理器(Exception Handler Configuration):

在Spring MVC框架中,我们可以使用SimpleMappingExceptionResolver类来配置异常处理器。

@Bean
public SimpleMappingExceptionResolver exceptionResolver() {SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();Properties mappings = new Properties();mappings.put("org.springframework.dao.DataAccessException", "dataAccessFailure");mappings.put("org.springframework.security.access.AccessDeniedException", "accessDenied");mappings.put("java.lang.Exception", "error");resolver.setExceptionMappings(mappings);return resolver;
}

在上面的示例中,我们定义了一个exceptionResolver Bean,并通过Properties对象设置了三个异常类型和对应的视图名称。例如,当遇到DataAccessException类型的异常时,将返回"dataAccessFailure"视图。

3. 处理HTTP错误码(Handle HTTP Status Codes):

在Spring MVC框架中,我们可以使用@ExceptionHandler注解和ResponseEntity类来处理HTTP错误码。

@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(ResourceNotFoundException.class)public ResponseEntity<Object> handleResourceNotFoundException(ResourceNotFoundException ex) {ApiError apiError = new ApiError(HttpStatus.NOT_FOUND, ex.getMessage(), ex);return new ResponseEntity<>(apiError, HttpStatus.NOT_FOUND);}@ExceptionHandler(Exception.class)public ResponseEntity<Object> handleException(Exception ex) {ApiError apiError = new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), ex);return new ResponseEntity<>(apiError, HttpStatus.INTERNAL_SERVER_ERROR);}
}

在上面的示例中,我们定义了一个名为GlobalExceptionHandler的全局异常处理类,并在其中定义了两个方法:handleResourceNotFoundException()和handleException()。这两个方法分别处理ResourceNotFoundException和Exception类型的异常。在处理过程中,我们创建了一个ApiError对象,并将其作为ResponseEntity的返回值。这样可以返回HTTP错误码和对应的错误信息。

通过以上的介绍,我们可以看出,异常处理是Spring MVC框架中非常重要的一种机制,它允许开发者捕获和处理异常,并返回友好的错误信息。只有深入理解异常处理的概念,并熟练掌握相应的Java代码技巧,才能够在实际开发中灵活运用Spring MVC框架,构建高效、可靠、易于维护的Web应用程序。

文件上传

Spring MVC提供了一种简单的机制来处理文件上传。通过使用MultipartResolver接口,可以轻松处理多个文件同时上传等情况。
文件上传是Web应用程序中非常常见的功能,Spring MVC提供了一种简单的机制来处理文件上传。通过使用MultipartResolver接口,可以轻松处理多个文件同时上传等情况。

下面我们将深入探讨Spring MVC文件上传的核心概念和相应Java代码示例。

1. 配置文件上传(Configure File Upload):

在Spring MVC框架中,我们需要配置一个MultipartResolver Bean来处理文件上传请求。

@Bean
public MultipartResolver multipartResolver() {CommonsMultipartResolver resolver = new CommonsMultipartResolver();resolver.setMaxUploadSizePerFile(1024 * 1024); // 1MBreturn resolver;
}

在上面的示例中,我们定义了一个multipartResolver Bean,并设置最大文件上传大小为1MB。

2. 处理文件上传(Handle File Upload):

在Spring MVC框架中,我们可以使用@RequestParam注解将上传的文件绑定到Java对象上。

@Controller
@RequestMapping("/file")
public class FileController {@PostMapping("/upload")public String upload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {if (file.isEmpty()) {redirectAttributes.addFlashAttribute("message", "Please select a file to upload");return "redirect:/file";}try {byte[] bytes = file.getBytes();Path path = Paths.get("uploads/" + file.getOriginalFilename());Files.write(path, bytes);redirectAttributes.addFlashAttribute("message", "File uploaded successfully");} catch (IOException e) {e.printStackTrace();}return "redirect:/file";}
}

在上面的示例中,我们定义了一个名为FileController的控制器类,并在其中定义了一个upload()方法。该方法使用@RequestParam注解将上传的文件绑定到MultipartFile对象上,并通过RedirectAttributes对象将消息传递给视图。在处理过程中,我们使用Files.write()方法将上传的文件写入到服务器本地磁盘。

3. 处理多个文件上传(Handle Multiple File Upload):

在Spring MVC框架中,我们可以使用@RequestParam注解和List类型将多个上传的文件绑定到Java对象上。

@Controller
@RequestMapping("/file")
public class FileController {@PostMapping("/multi-upload")public String multiUpload(@RequestParam("files") List<MultipartFile> files, RedirectAttributes redirectAttributes) {if (files.isEmpty()) {redirectAttributes.addFlashAttribute("message", "Please select a file to upload");return "redirect:/file";}try {for (MultipartFile file : files) {byte[] bytes = file.getBytes();Path path = Paths.get("uploads/" + file.getOriginalFilename());Files.write(path, bytes);}redirectAttributes.addFlashAttribute("message", "Files uploaded successfully");} catch (IOException e) {e.printStackTrace();}return "redirect:/file";}
}

在上面的示例中,我们定义了一个名为FileController的控制器类,并在其中定义了一个multiUpload()方法。该方法使用@RequestParam注解将多个上传的文件绑定到List对象上,并通过RedirectAttributes对象将消息传递给视图。在处理过程中,我们使用for循环遍历所有上传的文件,并将它们写入到服务器本地磁盘。

通过以上的介绍,我们可以看出,文件上传是Spring MVC框架中非常重要的一种机制,它允许开发者轻松处理多个文件同时上传等情况。只有深入理解文件上传的概念,并熟练掌握相应的Java代码技巧,才能够在实际开发中灵活运用Spring MVC框架,构建高效、可靠、易于维护的Web应用程序。

Restful支持

Spring MVC对Restful风格的Web服务提供了良好的支持。通过使用@RestController注解,可以轻松创建RESTful Web服务。
RESTful架构风格是Web服务的一种设计风格,它使用HTTP协议中的GET、POST、PUT和DELETE等方法来实现资源的创建、读取、更新和删除操作。Spring MVC对Restful风格的Web服务提供了良好的支持。通过使用@RestController注解,可以轻松创建RESTful Web服务。

下面我们将深入探讨Spring MVC Restful的核心概念和相应Java代码示例。

1. 创建Restful控制器(Create Restful Controller):

在Spring MVC框架中,我们可以使用@RestController注解定义一个Restful控制器类。该类中的每个方法都将返回JSON数据或XML数据。

@RestController
@RequestMapping("/api")
public class UserController {@Autowiredprivate UserService userService;@GetMapping("/users")public List<User> getAllUsers() {return userService.getAllUsers();}@PostMapping("/users")public User createUser(@RequestBody User user) {return userService.saveUser(user);}@GetMapping("/users/{id}")public User getUserById(@PathVariable Long id) {return userService.getUserById(id);}@PutMapping("/users/{id}")public User updateUser(@PathVariable Long id, @RequestBody User user) {User oldUser = userService.getUserById(id);oldUser.setName(user.getName());oldUser.setEmail(user.getEmail());oldUser.setPassword(user.getPassword());return userService.saveUser(oldUser);}@DeleteMapping("/users/{id}")public void deleteUserById(@PathVariable Long id) {userService.deleteUserById(id);}
}

在上面的示例中,我们定义了一个名为UserController的Restful控制器类,并在其中定义了五个方法:getAllUsers()、createUser()、getUserById()、updateUser()和deleteUserById()。这些方法分别处理HTTP GET、POST、PUT和DELETE请求,并返回JSON或XML格式的数据。

2. 配置Restful消息转换器(Configure Restful Message Converters)

在Spring MVC框架中,我们需要配置一个HttpMessageConverters Bean来处理Restful Web服务的请求和响应。

@Bean
public HttpMessageConverters converters() {MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();List<MediaType> supportedMediaTypes = new ArrayList<>();supportedMediaTypes.add(MediaType.APPLICATION_JSON);supportedMediaTypes.add(MediaType.APPLICATION_XML);jsonConverter.setSupportedMediaTypes(supportedMediaTypes);return new HttpMessageConverters(jsonConverter);
}

在上面的示例中,我们定义了一个converters Bean,并将MappingJackson2HttpMessageConverter对象添加到其中。该对象支持处理JSON和XML格式的数据。

通过以上的介绍,我们可以看出,Restful风格的Web服务是Spring MVC框架中非常重要的一种机制,它允许开发者使用HTTP协议中的GET、POST、PUT和DELETE等方法来实现资源的创建、读取、更新和删除操作。只有深入理解Restful的概念,并熟练掌握相应的Java代码技巧,才能够在实际开发中灵活运用Spring MVC框架,构建高效、可靠、易于维护的Web应用程序。

http://www.lryc.cn/news/122155.html

相关文章:

  • 【java面向对象中static关键字】
  • 系统学习Linux-Redis集群
  • 【每日随笔】帝王心术 ② ( 如何培养下一代 | 重点培养孩子某一项特长 | 价值观培养 | 独立思考 | 人性和谋略教育 | 资源传承 | 人生指引 )
  • Git简介
  • STM32入门学习之定时器输入捕获
  • 贪心算法:基础入门篇
  • 【Windows10下启动RocketMQ报错:找不到或无法加载主类 Files\Java\jdk1.8.0_301\lib\dt.jar】解决方法
  • 深入篇【Linux】学习必备:进程理解(从底层探究进程概念/进程创建/进程状态/进程优先级)
  • Python 潮流周刊#15:如何分析 FastAPI 异步请求的性能?
  • 基于Java+SpringBoot+Vue的网吧管理系统设计与实现(源码+LW+部署文档等)
  • redis设置database 不生效剖析
  • 汽车及汽车零部件行业云MES解决方案
  • 算法工程师-机器学习面试题总结(4)
  • Linux学习之awk函数
  • Redis的数据结构到底是一种什么样的结构?
  • eclipse 导入项目js报错问题
  • 《HeadFirst设计模式(第二版)》第七章代码——外观模式
  • 前端杂项-个人总结八股文的背诵方案
  • 利用 3D 地理空间数据实现Cesium的沉浸式环境
  • 微服务——ES实现自动补全
  • 北斗+5G 织就精确定位的“天罗地网”
  • Ansible Roles详解
  • 微服务学习笔记-基本概念
  • Linux查看GPU显卡/CPU内存/硬盘信息
  • SQLAlchemy 入门:Python 中的 SQL 工具包和 ORM
  • react Hook+antd封装一个优雅的弹窗组件
  • HICP学习--BGP综合小实验
  • grafana中利用变量来添加dashboard详情页地址实现点击跳转
  • 正则表达式练习
  • leetcode做题笔记73矩阵置零