[英]How to perform validation on @RequestParam in Spring
I'm a newbie in java spring.我是 java spring 的新手。 I have checked for solutions online and I can't seem to get my hands on anything helpful.
我已经在线检查了解决方案,但我似乎无法获得任何有用的信息。
I have a form that has been bound to an Entity, however, I have a field in that form that was not bound, which I receive as a requestParam.我有一个已绑定到实体的表单,但是,我在该表单中有一个未绑定的字段,我将其作为 requestParam 接收。 So when the field is submitted I need to validate that parameter to ensure it's not empty.
因此,当提交该字段时,我需要验证该参数以确保它不为空。
@PostMapping("/store")
public String store(@Valid Quote quote,BindingResult result, Model model,@RequestParam(required=false) String [] tagsFrom) {
if(result.hasErrors()) {
model.addAttribute("jsontags", returnTagsAsJson(tagRepo.findAll()));
return "admin/quotes/create";
}
List<Tag> listtags = new ArrayList<Tag> ();
for(String tag : tagsFrom) {
Tag theTag = new Tag();
theTag.setTag(tag);
theTag.setCreatedAt(new Date());
theTag.setUpdatedAt(new Date());
if(tagRepo.findByTag(tag) == null) {
tagRepo.save(theTag);
}
listtags.add(tagRepo.findByTag(tag));
}
quote.setTags(listtags);
quoteRepo.save(quote);
return "redirect:/dashboard/quotes";
}
What I have tried;我尝试过的; I created a custom validation and added the annotation to the parameter but that gave an error "The annotation @EmptyArrayString is disallowed for this location"
我创建了一个自定义验证并将注释添加到参数中,但出现错误“此位置不允许使用注释 @EmptyArrayString”
public String store(@Valid Quote quote,BindingResult result, Model model,
@RequestParam(required=false) @EmptyArrayString String [] tagsFrom)
I have tried using @NotEmpty
on the parameter which throws NullPointerException
我尝试在引发
NullPointerException
的参数上使用@NotEmpty
I need a solution that allows me to display the error on the HTML form like this我需要一个解决方案,让我可以像这样在 HTML 表单上显示错误
<span th:if="${#fields.hasErrors('tags')}"
th:errors="${quote.tags}" class="errors">
</span>
So when the field is submitted I need to validate that parameter to ensure it's not empty.
因此,当提交该字段时,我需要验证该参数以确保它不为空。
,@RequestParam(required=false) String [] tagsFrom
By default, required
is set to true.默认情况下,
required
设置为 true。 So, if the URL must have the param, you shouldn't do required=false
.因此,如果 URL 必须具有参数,则不应执行
required=false
。
String [] tagsFrom
implies you expect a bunch of tag params. String [] tagsFrom
意味着您期望一堆标签参数。 But, is it of the form但是,它的形式是
http://localhost:xxx?param=1,2,3
or http://localhost:xxx?param=1,2,3
或http://localhost:xxx?param1=1¶m2="stringvalue"
? http://localhost:xxx?param1=1¶m2="stringvalue"
?
For the first one, you can have the mapping method as:对于第一个,您可以将映射方法设置为:
public String store(...@RequestParam List<String> param)
For the second one, you can do:对于第二个,您可以执行以下操作:
public String store(...@RequestParam Map<String,String> allQueryParameters)
You can then do your necessary validations.然后,您可以进行必要的验证。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.