【问题标题】:How to perform validation on @RequestParam in Spring如何在 Spring 中对 @RequestParam 执行验证
【发布时间】:2020-11-18 11:58:00
【问题描述】:

我是 java spring 的新手。我已经在网上查看了解决方案,但似乎找不到任何有用的东西。

我有一个已绑定到实体的表单,但是,我在该表单中有一个未绑定的字段,我将其作为 requestParam 接收。 因此,当提交该字段时,我需要验证该参数以确保它不为空。

    @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";
    }

我尝试过的; 我创建了一个自定义验证并将注释添加到参数中,但出现错误“此位置不允许使用注释 @EmptyArrayString”

public String store(@Valid Quote quote,BindingResult result, Model model,
      @RequestParam(required=false) @EmptyArrayString String [] tagsFrom)

我尝试在抛出NullPointerException的参数上使用@NotEmpty

我需要一个解决方案,让我可以像这样在 HTML 表单上显示错误

 <span th:if="${#fields.hasErrors('tags')}" 
                    th:errors="${quote.tags}" class="errors">
 </span>

【问题讨论】:

  • 创建一个专用的表单对象,保存所有需要的信息,然后转换回Quote并复制数据。
  • 我认为这更符合我的要求。我在什么时候转换回报价。假设我将 forn 绑定到 QuoteForm 对象。以及如何对报价对象进行验证?
  • 为什么要验证Quote对象,验证表单对象(对于有效输入)。
  • 非常感谢。这刚刚解决了我的问题。

标签: java spring spring-boot jpa thymeleaf


【解决方案1】:

因此,当提交该字段时,我需要验证该参数以确保它不为空。

,@RequestParam(required=false) String [] tagsFrom

默认情况下,required 设置为 true。因此,如果 URL 必须具有参数,则不应使用 required=false

String [] tagsFrom 表示您期望一堆 tag 参数。但是,它是
http://localhost:xxx?param=1,2,3 还是
http://localhost:xxx?param1=1&amp;param2="stringvalue" 的形式?

对于第一个,您可以将映射方法设置为:
public String store(...@RequestParam List&lt;String&gt; param)

对于第二个,您可以:
public String store(...@RequestParam Map&lt;String,String&gt; allQueryParameters)

然后您可以进行必要的验证。

阅读更多here

【讨论】:

    猜你喜欢
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多