为什么javax验证在DTO类中不起作用?

huangapple go评论64阅读模式
英文:

Why javax validation not working in DTO class?

问题

以下是翻译好的内容:

我正在尝试学习 Spring Boot但是我在表单验证过程中遇到了问题我已经按照这里的说明进行了操作[1]

这是我的控制器类

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

@Controller
public class TalentCategoryController {

    @GetMapping("talent-category")
    public ModelAndView create(CreateTalentCategoryRequest talentCategory) {
        ModelAndView model = new ModelAndView();
        model.setViewName("talent-category/create");
        model.addObject("talentCategory", talentCategory);
        return model ; 
    }

    @Autowired
    TalentCategoryService talentCategoryService ; 

    @RequestMapping(path="talent-category", method = RequestMethod.POST, consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
    public ModelAndView store(@Valid @ModelAttribute CreateTalentCategoryRequest talentCategory, BindingResult result) {
        // result.hasErrors is false
        if(result.hasErrors()) { 
            System.out.println("Validation working");
            ModelAndView model = new ModelAndView();            
            model.setViewName("talent-category/create");
            return model; 
        }
        System.out.println("Validation not working");
        talentCategoryService.store();
        return null ; 
    }

}

DTO 类

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import lombok.Data;

@Data
public class CreateTalentCategoryRequest {
    
    @NotBlank(message="不能为空")
    @Size(min=10, max=30)
    private String name ; 
    
    @NotBlank(message="不能为空")
    private String status  ; 

    @NotBlank(message="不能为空")
    private String approved ; 
    
    @NotBlank(message="不能为空")
    private String sort_order ;

}

视图

<form th:object="${talentCategory}" name="create-talent-category" method="POST" th:action="@{/talent-category}">
    <div class="row">
        <div class="col-4">
            <div class="form-group">
                <label for="name">名称</label>
                <input th:field="*{name}" type="text" class="form-control form-control-sm" id="name" placeholder="类别名称" />
                <p class="alert alert-danger" th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></p>
            </div>
        </div>
        
        <div class="col-2">
            <div class="form-group">
                <label for="sort_order">排序顺序</label>
                <input type="text" class="form-control form-control-sm" id="sort_order" placeholder="例如:1" />
            </div>
        </div>
        
        
        <div class="col-2">
            <div class="form-group">
                <label for="status">状态</label>
                 <select name="status" id="status" class="form-control form-control-sm">
                    <option selected>选择...</option>
                    <option value="1">活动</option>
                    <option value="0">停用</option>
                 </select>
            </div>
        </div>
        
        <div class="col-2">
            <div class="form-group">
                <label for="approved">已批准</label>
                 <select name="approved" id="approved" class="form-control form-control-sm">
                    <option selected>选择...</option>
                    <option value="1"></option>
                    <option value="0"></option>
                 </select>
            </div>
        </div>
    </div>
    
    <div class="row">
        <div class="col-12">
            <button name="create" class="btn btn-sm btn-primary">创建</button>
        </div>
    </div>
 </form>

请注意,这是翻译后的代码部分,只包括代码内容,不包含额外的回答。如有其他问题,请随时提问。

英文:

I am trying to learn the spring boot. And, I am stuck on the form validation process. I have followed the process as instructed here.

Here is my controller class

import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
@Controller
public class TalentCategoryController {
@GetMapping(&quot;talent-category&quot;)
public ModelAndView create(CreateTalentCategoryRequest talentCategory) {
ModelAndView model = new ModelAndView();
model.setViewName(&quot;talent-category/create&quot;);
model.addObject(&quot;talentCategory&quot;, talentCategory);
return model ; 
}
@Autowired
TalentCategoryService talentCategoryService ; 
@RequestMapping(path=&quot;talent-category&quot;, method = RequestMethod.POST, consumes = {MediaType.APPLICATION_FORM_URLENCODED_VALUE})
public ModelAndView store(@Valid @ModelAttribute CreateTalentCategoryRequest talentCategory, BindingResult result) {
// result.hasErrors is false
if(result.hasErrors()) { 
System.out.println(&quot;Validation working&quot;);
ModelAndView model = new ModelAndView();			
model.setViewName(&quot;talent-category/create&quot;);
return model; 
}
System.out.println(&quot;Validation not working&quot;);
talentCategoryService.store();
return null ; 
}
}

DTO class :

import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
import lombok.Data;
@Data
public class CreateTalentCategoryRequest {
@NotBlank(message=&quot;Cannot be empty&quot;)
@Size(min=10, max=30)
private String name ; 
@NotBlank(message=&quot;Cannot be empty&quot;)
private String status  ; 
@NotBlank(message=&quot;Cannot be empty&quot;)
private String approved ; 
@NotBlank(message=&quot;Cannot be empty&quot;)
private String sort_order ;
}

View :

&lt;form th:object=&quot;${talentCategory}&quot; name=&quot;create-talent-category&quot; method=&quot;POST&quot; th:action=&quot;@{/talent-category}&quot;&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;col-4&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label for=&quot;name&quot;&gt;Name&lt;/label&gt;
&lt;input th:field=&quot;*{name}&quot; type=&quot;text&quot;  class=&quot;form-control form-control-sm&quot; id=&quot;name&quot; placeholder=&quot;Category Name&quot; /&gt;
&lt;p class=&quot;alert alert-danger&quot; th:if=&quot;${#fields.hasErrors(&#39;name&#39;)}&quot; th:errors=&quot;*{name}&quot;&gt;&lt;/p&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;col-2&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label for=&quot;sort_order&quot;&gt;Sort Order&lt;/label&gt;
&lt;input type=&quot;text&quot; class=&quot;form-control form-control-sm&quot; id=&quot;sort_order&quot; placeholder=&quot;Eg : 1&quot; /&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;col-2&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label for=&quot;status&quot;&gt;Status&lt;/label&gt;
&lt;select name=&quot;status&quot; id=&quot;status&quot; class=&quot;form-control form-control-sm&quot;&gt;
&lt;option selected&gt;Choose...&lt;/option&gt;
&lt;option value=&quot;1&quot;&gt;Active&lt;/option&gt;
&lt;option value=&quot;0&quot;&gt;Passive&lt;/option&gt;
&lt;/select&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;col-2&quot;&gt;
&lt;div class=&quot;form-group&quot;&gt;
&lt;label for=&quot;approved&quot;&gt;Approved&lt;/label&gt;
&lt;select name=&quot;approved&quot; id=&quot;approved&quot; class=&quot;form-control form-control-sm&quot;&gt;
&lt;option selected&gt;Choose...&lt;/option&gt;
&lt;option value=&quot;1&quot;&gt;Yes&lt;/option&gt;
&lt;option value=&quot;0&quot;&gt;No&lt;/option&gt;
&lt;/select&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;div class=&quot;row&quot;&gt;
&lt;div class=&quot;col-12&quot;&gt;
&lt;button name=&quot;create&quot; class=&quot;btn btn-sm btn-primary&quot;&gt;Create&lt;/button&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/form&gt;

When a form is submitted with all the fields empty, the request is not redirect to the form(prints validation not working in console).

答案1

得分: 1

如果您使用的是Spring版本2.3+,请确保您具有以下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-validation</artifactId>
</dependency>
英文:

if you are using spring version 2.3+ , make sure you have following dependency

<!-- language: lang-xml -->

&lt;dependency&gt;
&lt;groupId&gt;org.springframework.boot&lt;/groupId&gt;
&lt;artifactId&gt;spring-boot-starter-validation&lt;/artifactId&gt;
&lt;/dependency&gt;

huangapple
  • 本文由 发表于 2020年8月29日 20:41:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63647076.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定