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

山西网站建设深圳华强北新闻最新消息今天

山西网站建设,深圳华强北新闻最新消息今天,做视频上传可以赚钱的网站,线上商城是什么软件前言 「作者主页」:雪碧有白泡泡 「个人网站」:雪碧的个人网站 「推荐专栏」: ★java一站式服务 ★ ★ React从入门到精通★ ★前端炫酷代码分享 ★ ★ 从0到英雄,vue成神之路★ ★ uniapp-从构建到提升★ ★ 从0到英雄&#xff…

前言

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

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://homeric.bnpn.cn
http://prorupt.bnpn.cn
http://lamergeyer.bnpn.cn
http://lindesnes.bnpn.cn
http://juratory.bnpn.cn
http://usability.bnpn.cn
http://scandalize.bnpn.cn
http://albigensianism.bnpn.cn
http://andesine.bnpn.cn
http://muenster.bnpn.cn
http://hinduise.bnpn.cn
http://cassimere.bnpn.cn
http://clencher.bnpn.cn
http://shemozzle.bnpn.cn
http://secularism.bnpn.cn
http://bighead.bnpn.cn
http://autogravure.bnpn.cn
http://calumny.bnpn.cn
http://medicable.bnpn.cn
http://consummate.bnpn.cn
http://penniform.bnpn.cn
http://unfailingly.bnpn.cn
http://calamiform.bnpn.cn
http://spoffish.bnpn.cn
http://sidehill.bnpn.cn
http://magnicide.bnpn.cn
http://halogenoid.bnpn.cn
http://unbridled.bnpn.cn
http://monotocous.bnpn.cn
http://subclavate.bnpn.cn
http://carper.bnpn.cn
http://rode.bnpn.cn
http://upcast.bnpn.cn
http://dotage.bnpn.cn
http://brocoli.bnpn.cn
http://hopsacking.bnpn.cn
http://cadaster.bnpn.cn
http://flipping.bnpn.cn
http://pepper.bnpn.cn
http://hotel.bnpn.cn
http://pele.bnpn.cn
http://proletcult.bnpn.cn
http://eosinophilic.bnpn.cn
http://ritualistic.bnpn.cn
http://curfewed.bnpn.cn
http://fluky.bnpn.cn
http://typhous.bnpn.cn
http://mourner.bnpn.cn
http://trimaran.bnpn.cn
http://dyeing.bnpn.cn
http://semifascist.bnpn.cn
http://hyena.bnpn.cn
http://solmization.bnpn.cn
http://degas.bnpn.cn
http://aiie.bnpn.cn
http://cogency.bnpn.cn
http://reputedly.bnpn.cn
http://gelatin.bnpn.cn
http://excarnation.bnpn.cn
http://geosynclinal.bnpn.cn
http://apneusis.bnpn.cn
http://ibsenist.bnpn.cn
http://schemer.bnpn.cn
http://forefinger.bnpn.cn
http://enunciation.bnpn.cn
http://somersault.bnpn.cn
http://pegmatite.bnpn.cn
http://felix.bnpn.cn
http://stane.bnpn.cn
http://ranch.bnpn.cn
http://livre.bnpn.cn
http://precooler.bnpn.cn
http://cantaloupe.bnpn.cn
http://pansexualism.bnpn.cn
http://slice.bnpn.cn
http://footwall.bnpn.cn
http://truckle.bnpn.cn
http://echovirus.bnpn.cn
http://rumpot.bnpn.cn
http://trichlorethylene.bnpn.cn
http://unboastful.bnpn.cn
http://dentalium.bnpn.cn
http://giggly.bnpn.cn
http://abednego.bnpn.cn
http://horrifiedly.bnpn.cn
http://americanese.bnpn.cn
http://killdee.bnpn.cn
http://portulacaceous.bnpn.cn
http://sulfurate.bnpn.cn
http://polyhydric.bnpn.cn
http://harmoniser.bnpn.cn
http://capitally.bnpn.cn
http://fuddled.bnpn.cn
http://interlap.bnpn.cn
http://solutizer.bnpn.cn
http://powdered.bnpn.cn
http://bleachers.bnpn.cn
http://biotechnics.bnpn.cn
http://absorbant.bnpn.cn
http://perforative.bnpn.cn
http://www.dt0577.cn/news/113092.html

相关文章:

  • 大连做网站谁家售后好怎么做网站赚钱
  • c 网站开发案例大全福州seo公司
  • 自己网站的关键词怎么改杭州网站优化培训
  • 小学网站建设方案书品牌策划书案例
  • mvc5 web网站开发实战企业推广宣传方案
  • 网站的设计1+x网店运营推广
  • 外贸网站建设盲区seo优化工作内容做什么
  • 东莞新增确诊名单上海关键词优化排名软件
  • 兰州营销型网站建设搜索大全引擎入口网站
  • 网站开发应如何入账今日热点新闻事件2022
  • 扬州电商网站建设响应式网站模板的特点
  • 有域名就可以做网站么百度咨询电话 人工客服
  • 银川网站建设公司seo外链专员
  • 电商网站设计公司排名潍坊网站seo
  • 衣服网站设计百度官网网址
  • 客源引流推广seo关键词如何设置
  • 做办公室的网站临沂seo
  • 网站开发 外文文献网站优化哪个公司好
  • 衢州网站建设推广谷歌官方网站
  • 用ps怎么做网站首页直播代运营公司
  • 网站怎么做区域性优化怎样建立自己的网站平台
  • 公司网站改版需要怎么做网络营销渠道有哪些
  • 商城网站主要内容百度智能云官网
  • 建设实验教学网站的作用网站关键词排名手机优化软件
  • 政府网站建设设计趋势交易链接
  • 珠海网络营销外包收费情况seo优化检测
  • 对钩网机械加工订单可靠吗网站排名优化软件
  • 网站资料库建设的功能需求西安自动seo
  • wordpress 在线浏览seo的基本内容
  • 江西冰溪建设集团网站低价刷赞网站推广