如何检查@RequestParam是否为空 避免提交空表单时程序崩溃
解决方案
- 调整
@RequestParam注解配置,适配空值提交
基础类型int无法接收null值,空表单提交时Spring找不到对应参数会尝试将空串转为int,直接抛出类型转换异常。你可以给@RequestParam添加required = false和defaultValue属性规避这个问题,同时字符串类型的参数也建议加上required = false,避免参数缺失时直接报错:
注意现有代码的空值判断存在空指针风险,参数为null时调用@PostMapping("/formPost") public String processForm ( Model model, @RequestParam(required = false) String productName, @RequestParam(required = false) String brandName, @RequestParam(required = false) String frameType, @RequestParam(required = false) String color, @RequestParam(required = false) String size, @RequestParam(required = false) String lensType, @RequestParam(required = false, defaultValue = "0") int price ) {equals("")会直接抛出异常,建议用org.springframework.util.StringUtils的hasText()方法判断,所有参数为空的校验逻辑可以改成:if (!StringUtils.hasText(productName) && !StringUtils.hasText(brandName) && !StringUtils.hasText(frameType) && !StringUtils.hasText(color) && !StringUtils.hasText(size) && !StringUtils.hasText(lensType) && price == 0) { return "displayGlasses"; } - 用包装类型
Integer替换基本类型int
如果你不想设置默认值,可以把price的类型改成Integer,空提交时price会被赋值为null,你可以自行判断空值逻辑,不会触发类型转换异常,参数写法如下:
对应的校验逻辑可以调整为判断price是否为null或者0即可。@RequestParam(required = false) Integer price - 全局捕获参数异常统一处理
如果多个接口都有类似的空表单提交场景,可以加一个全局异常处理器,捕获MissingServletRequestParameterException、TypeMismatchException这类参数相关异常,直接跳转至指定页面,不需要每个接口单独处理:@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler({MissingServletRequestParameterException.class, TypeMismatchException.class}) public String handleParamError() { return "displayGlasses"; } } - 用Spring Validation简化参数校验
不需要手动挨个写if判断参数是否为空,引入Spring Validation依赖后,给参数加校验注解即可,校验不通过时自动处理跳转,代码更简洁。
内容的提问来源于stack exchange,提问作者Mathew Boyd
相关产品推荐
相关产品推荐

