iis服务器助手广告广告
返回顶部
首页 > 资讯 > 精选 >使用Spring MVC怎么对参数进行校验
  • 100
分享到

使用Spring MVC怎么对参数进行校验

springmvc 2023-05-31 08:05:07 100人浏览 独家记忆
摘要

本篇文章为大家展示了使用spring mvc怎么对参数进行校验,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。1. 内嵌异常处理如果只是这个controller的异常做单独处理,那么就适合绑定这个co

本篇文章为大家展示了使用spring mvc怎么对参数进行校验,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

1. 内嵌异常处理

如果只是这个controller的异常做单独处理,那么就适合绑定这个controller本身的异常。

具体做法是使用注解@ExceptionHandler.

在这个controller中添加一个方法,并添加上述注解,并指明要拦截的异常。

@RequestMapping(value = "saveOrUpdate", method = RequestMethod.POST)public String saveOrUpdate(httpservletResponse response, @RequestBody Order order){ CodeMsg result = null; try { result = orderService.saveOrUpdate(order); } catch (Exception e) { logger.error("save failed.", e); return this.renderString(response, CodeMsg.error(e.getMessage())); } return this.renderString(response, result);}@ResponseBody@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(HttpMessageNotReadableException.class)public CodeMsg messageNotReadable(HttpMessageNotReadableException exception, HttpServletResponse response){ LOGGER.error("请求参数不匹配。", exception); return CodeMsg.error(exception.getMessage());}

这里saveOrUpdate是我们想要拦截一样的请求,而messageNotReadable则是处理异常的代码。
@ExceptionHandler(HttpMessageNotReadableException.class)表示我要拦截何种异常。在这里,由于springMVC默认采用jackson作为JSON序列化工具,当反序列化失败的时候就会抛出HttpMessageNotReadableException异常。具体如下:

{ "code": 1, "msg": "Could not read jsON: Failed to parse Date value '2017-03-' (fORMat: \"yyyy-MM-dd HH:mm:ss\"): Unparseable date: \"2017-03-\" (through reference chain: com.test.modules.order.entity.Order[\"serveTime\"]); nested exception is com.fasterxml.jackson.databind.JsonMappingException: Failed to parse Date value '2017-03-' (format: \"yyyy-MM-dd HH:mm:ss\"): Unparseable date: \"2017-03-\" (through reference chain: com.test.modules.order.entity.Order[\"serveTime\"])", "data": ""}

这是个典型的jackson反序列化失败异常,也是造成我遇见过的400原因最多的。通常是日期格式不对。

另外, @ResponseStatus(HttpStatus.BAD_REQUEST)这个注解是为了标识这个方法返回值的HttpStatus code。我设置为400,当然也可以自定义成其他的。

2. 批量异常处理

看到大多数资料写的是全局异常处理,我觉得对我来说批量更合适些,因为我只是希望部分controller被拦截而不是全部。

springmvc提供了@ControllerAdvice来做批量拦截。

第一次看到注释这么少的源码,忍不住多读几遍。

Indicates the annotated class assists a "Controller".

表示这个注解是服务于Controller的。

Serves as a specialization of {@link Component @Component}, allowing for implementation classes to be autodetected through classpath scanning.

用来当做特殊的Component注解,允许使用者扫描发现所有的classpath。

It is typically used to define {@link ExceptionHandler @ExceptionHandler}, * {@link InitBinder @InitBinder}, and {@link ModelAttribute @ModelAttribute} * methods that apply to all {@link RequestMapping @RequestMapping} methods.

典型的应用是用来定义xxxx.

One of {@link #annotations()}, {@link #basePackageClasses()}, * {@link #basePackages()} or its alias {@link #value()} * may be specified to define specific subsets of Controllers * to assist. When multiple selectors are applied, OR logic is applied - * meaning selected Controllers should match at least one selector.

这几个参数指定了扫描范围。

the default behavior (i.e. if used without any selector), * the {@code @ControllerAdvice} annotated class will * assist all known Controllers.

默认扫描所有的已知的的Controllers。

Note that those checks are done at runtime, so adding many attributes and using * multiple strategies may have negative impacts (complexity, performance).

注意这个检查是在运行时做的,所以注意性能问题,不要放太多的参数。

说的如此清楚,以至于用法如此简单。

@ResponseBody@ControllerAdvice("com.api")public class ApiExceptionHandler extends BaseClientController { private static final Logger LOGGER = LoggerFactory.getLogger(ApiExceptionHandler.class);  @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(UnexpectedTypeException.class) public CodeMsg unexpectedType(UnexpectedTypeException exception, HttpServletResponse response){  LOGGER.error("校验方法太多,不确定合适的校验方法。", exception);  return CodeMsg.error(exception.getMessage()); } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(HttpMessageNotReadableException.class) public CodeMsg messageNotReadable(HttpMessageNotReadableException exception, HttpServletResponse response){  LOGGER.error("请求参数不匹配,request的json格式不正确", exception);  return CodeMsg.error(exception.getMessage()); } @ResponseStatus(HttpStatus.BAD_REQUEST) @ExceptionHandler(Exception.class) public CodeMsg ex(MethodArgumentNotValidException exception, HttpServletResponse response){  LOGGER.error("请求参数不合法。", exception);  BindingResult bindingResult = exception.getBindingResult();  String msg = "校验失败";  return new CodeMsg(CodeMsGConstant.error, msg, getErrors(bindingResult)); } private Map<String, String> getErrors(BindingResult result) {  Map<String, String> map = new HashMap<>();  List<FieldError> list = result.getFieldErrors();  for (FieldError error : list) {   map.put(error.getField(), error.getDefaultMessage());  }  return map; }}

3. Hibernate-validate

使用参数校验如果不catch异常就会返回400. 所以这个也要规范一下。

1 引入hibernate-validate

<dependency>  <groupId>org.hibernate</groupId>  <artifactId>hibernate-validator</artifactId>  <version>5.0.2.Final</version> </dependency>
<mvc:annotation-driven validator="validator" /><bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> <property name="validationMessageSource" ref="messageSource"/></bean>

2 使用

在实体类字段上标注要求

public class AlipayRequest { @NotEmpty private String out_trade_no; private String subject; @DecimalMin(value = "0.01", message = "费用最少不能小于0.01") @DecimalMax(value = "100000000.00", message = "费用最大不能超过100000000") private String total_fee;  @NotEmpty(message = "订单类型不能为空") private String business_type; //....}

controller里添加@Valid

@RequestMapping(value = "sign", method = RequestMethod.POST) public String sign(@Valid @RequestBody AlipayRequest params ){  .... }

4.错误处理

前面已经提到,如果不做处理的结果就是400,415. 这个对应Exception是MethodArgumentNotValidException,也是这样:

@ResponseStatus(HttpStatus.BAD_REQUEST)@ExceptionHandler(Exception.class)public CodeMsg ex(MethodArgumentNotValidException exception, HttpServletResponse response){ LOGGER.error("请求参数不合法。", exception); BindingResult bindingResult = exception.getBindingResult(); String msg = "校验失败"; return new CodeMsg(CodeMsgConstant.error, msg, getErrors(bindingResult));}private Map<String, String> getErrors(BindingResult result) { Map<String, String> map = new HashMap<>(); List<FieldError> list = result.getFieldErrors(); for (FieldError error : list) {  map.put(error.getField(), error.getDefaultMessage()); } return map;}

返回结果:

{ "code": 1, "msg": "校验失败", "data": { "out_trade_no": "不能为空", "business_type": "订单类型不能为空" }}

大概有这么几个限制注解:

上述内容就是使用Spring MVC怎么对参数进行校验,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注编程网精选频道。

--结束END--

本文标题: 使用Spring MVC怎么对参数进行校验

本文链接: https://www.lsjlt.com/news/224412.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • 使用Spring MVC怎么对参数进行校验
    本篇文章为大家展示了使用Spring MVC怎么对参数进行校验,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。1. 内嵌异常处理如果只是这个controller的异常做单独处理,那么就适合绑定这个co...
    99+
    2023-05-31
    springmvc
  • SpringBoot接口怎么对参数进行校验
    今天小编给大家分享一下SpringBoot接口怎么对参数进行校验的相关知识点,内容详细,逻辑清晰,相信大部分人都还太了解这方面的知识,所以分享这篇文章给大家参考一下,希望大家阅读完这篇文章后有所收获,下面我们一起来了解一下吧。什么是不优雅的...
    99+
    2023-07-02
  • Springboot怎么使用filter对request body参数进行校验
    这篇文章主要为大家展示了“Springboot怎么使用filter对request body参数进行校验”,内容简而易懂,条理清晰,希望能够帮助大家解决疑惑,下面让小编带领大家一起研究并学习一下“Springboot怎么使用fil...
    99+
    2023-06-29
  • 如何对参数进行校验
    本篇内容主要讲解“如何对参数进行校验”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“如何对参数进行校验”吧!背景大部分的方法和构造函数对传入的参数值有一些限制,比...
    99+
    2022-10-19
  • SpringBoot怎么进行参数校验
    这篇文章主要讲解了“SpringBoot怎么进行参数校验”,文中的讲解内容简单清晰,易于学习与理解,下面请大家跟着小编的思路慢慢深入,一起来研究和学习“SpringBoot怎么进行参数校验”吧!介绍在日常的接口开发中,为了防止非法参数对业务...
    99+
    2023-06-30
  • Springboot如何使用filter对requestbody参数进行校验
    目录使用filter对request body参数进行校验通过filter修改body参数的思路知识点步骤使用filter对request body参数进行校验 @Slf4j pub...
    99+
    2022-11-13
  • 使用spring MVC怎么传递对象参数
    本篇文章为大家展示了使用spring MVC怎么传递对象参数,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。采用@ModelAttribute注解的方式,接收方式如下:@RequestMapping(...
    99+
    2023-05-31
    springmvc
  • SpringBoot接口如何对参数进行校验
    目录前言什么是不优雅的参数校验实现案例POM请求参数封装Controller中获取参数绑定结果校验结果进一步理解Validation分组校验?@Validate和@Valid什么区别...
    99+
    2022-11-13
  • Spring Boot使用 Hibernate-Validator校验参数时的长度校验
    今天在使用Validator框架数据验证的时候碰到了三个类似的注解,都是用来限制长度,但是用法上有区别: 1,@Size和@Length @Datapublic class LoginVo { @Length(min = 5, ma...
    99+
    2023-09-26
    spring boot hibernate java
  • Spring Boot参数校验及分组校验的使用教程
    目录一  前言1  什么是validator二  注解介绍1  validator内置注解三  使用1  单参数校验2&n...
    99+
    2022-11-12
  • 使用SpringMVC怎么实现对数据进行校验
    使用SpringMVC怎么实现对数据进行校验?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。一、导入jar包若要实现数据校验功能,需要导入必要的jar包,主要包括以下几个:c...
    99+
    2023-05-31
    springmvc
  • Spring Boot怎么实现请求参数校验
    这篇文章主要介绍了Spring Boot怎么实现请求参数校验的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇Spring Boot怎么实现请求参数校验文章都会有所收获,下面我们一...
    99+
    2022-10-19
  • 使用@Valid+BindingResult进行controller参数校验方式
    目录@Valid+BindingResult进行controller参数校验Controller层方法的参数校验全局统一异常拦截器@Valid+BindingResult进行cont...
    99+
    2022-11-12
  • 如何使用@Valid+BindingResult进行controller参数校验
    这篇文章主要介绍“如何使用@Valid+BindingResult进行controller参数校验”,在日常操作中,相信很多人在如何使用@Valid+BindingResult进行controller参数校验问题上存在疑惑,小编查阅了各式资...
    99+
    2023-06-21
  • 怎么在Spring boot中利用validation进行校验
    这篇文章主要为大家详细介绍了怎么在Spring boot中利用validation进行校验,文中示例代码介绍的非常详细,具有一定的参考价值,发现的小伙伴们可以参考一下:前言接触springboot一年多,是时候摆脱这种校验方式了233 ,每...
    99+
    2023-06-06
  • SpringBoot怎么使用validation做参数校验
    这篇文章主要介绍了SpringBoot怎么使用validation做参数校验的相关知识,内容详细易懂,操作简单快捷,具有一定借鉴价值,相信大家阅读完这篇SpringBoot怎么使用validation做参数校验文章都会有所收获,下面我们一起...
    99+
    2023-06-30
  • SpringBoot参数校验之@Valid怎么使用
    这篇文章主要介绍“SpringBoot参数校验之@Valid怎么使用”的相关知识,小编通过实际案例向大家展示操作过程,操作方法简单快捷,实用性强,希望这篇“SpringBoot参数校验之@Valid怎么使用”文章能帮助大家解决问题。依赖&l...
    99+
    2023-07-02
  • 参数校验Spring的@Valid注解有什么用
    小编给大家分享一下参数校验Spring的@Valid注解有什么用,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!参数校验Spring的@Valid注解@Valid ...
    99+
    2023-06-20
  • Java怎么使用责任链默认优雅地进行参数校验
    本篇内容介绍了“Java怎么使用责任链默认优雅地进行参数校验”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!前言项目中参数校验十分重要,它可以...
    99+
    2023-07-05
  • SpringBoot参数校验Validator框架怎么使用
    这篇“SpringBoot参数校验Validator框架怎么使用”文章的知识点大部分人都不太理解,所以小编给大家总结了以下内容,内容详细,步骤清晰,具有一定的借鉴价值,希望大家阅读完这篇文章能有所收获,下面我们一起来看看这篇“SpringB...
    99+
    2023-07-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作