I'm a newbie in 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. 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"
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
I need a solution that allows me to display the error on the HTML form like this
<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. So, if the URL must have the param, you shouldn't do required=false
.
String [] tagsFrom
implies you expect a bunch of tag params. But, is it of the formhttp://localhost:xxx?param=1,2,3
or 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.
Read more here
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.