java - 如何使用字符串参数向 Spring Boot 休息端点添加验证?
问题描述
如何使用 String 参数验证 Spring Boot Rest 端点,这是我的端点示例。
@ResponseBody
@RequestMapping(value = "/getProfile", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> getProfile(@RequestBody @Valid @NotEmpty String profileId){}
甚至认为我添加@valid
并@NonEmpty
约束它没有得到验证。
但它适用于其他课程。例如,
@ResponseBody
@RequestMapping(value = "/saveProfiles", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
public ResponseEntity<Object> saveProfiles(@RequestBody @Valid PersistProfilesRequest request){}
这里 PersistProfilesRequest 类中应用了约束的所有字段都在正确验证。
使用 String 和 Map 等 java 类的方法参数不会进行验证。
我正在使用spring boot 1.3.0
休眠验证器。
如何使用字符串参数向休息端点添加验证?
编辑
我正在使用junit和mockmvc来测试端点,下面是测试用例
@Test
public void testGetProfile() throws Exception{
String profileId = " ";
this.mockMvc.perform(post("/getProfile").content(profileId).accept(MediaType.APPLICATION_JSON).contentType("application/json"))
.andDo(print())
.andExpect(status().isInternalServerError());
}
解决方案
您可以尝试使用 @Validated 注释您的控制器类。就我而言,它有所帮助。
@Validated
@RestController
@RequestMapping(path = "/api/somethin")
public class LegacyRestController {
推荐阅读
- sublimetext - Sublime Text 3 插件 HTML 弹出窗口渲染
- google-chrome - Google Chrome Inspector 的图像大小是什么意思?
- python - Python字典排序列表
- sql - 思考具有两个外键的一对多或多对多关系的正确方法是什么?
- visual-studio-code - visual studio code + ubuntu + 中文名字Short
- python - 如何使用 ffmpeg-python 将视频剪切到一定长度并添加介绍视频?
- c++ - c++ winsock接受抛出的异常
- php - PHP,fopen() 无法从站点的根目录创建新文件
- asp.net - Recaptcha 停止在我的一半网站上工作?
- node.js - 从 github 克隆一个 electronjs 存储库并收到错误“找不到模块”