春季4和百里香叶形式验证

时间:2015-05-12 13:11:42

标签: java spring-mvc thymeleaf

任何人都可以使用Spring MVC和thymeleaf-spring4库来提供用于验证HTML表单的示例Java代码(例如:表单属性不为null,最小和最大大小)吗?

2 个答案:

答案 0 :(得分:1)

最简单的是,您需要使用所需的约束来注释您的@Entity public class User { @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @NotNull private String login; @Size(min=2, max=30) private String firstName; @Min(18) private int age; } 对象(在本例中为用户):

javax.validation.constraints

这些注释来自@Valid

在此之后你需要修改你的控制器,你需要澄清你的控制器该对象必须是@RequestMapping(method=RequestMethod.POST) public String registerUser(@Valid final User user, final BindingResult bindingResult) { if (bindingResult.hasErrors()) { return "form"; } // Your code return "redirect:/userList"; }

BindingResult

错误存储在<span th:if="${#fields.hasErrors('login')}" th:errors="*{login}"></span>

最后显示错误:

ModelAndView

修改

返回@RequestMapping(method=RequestMethod.POST) public ModelAndView registerUser(@Valid final User user, final BindingResult bindingResult) { if (bindingResult.hasErrors()) { ModelAndView mav = new ModelAndView("form"); mav.addObject(bindingResult); return mav; } }

RewriteCond %{HTTP_HOST} ^www2\.sitea\.com$ [OR]
RewriteCond %{HTTP_HOST} ^www\.www2\.sitea\.com$ [NC]
RewriteRule ^(.*)$ http://www2.siteb.com/$1 [R=301,L]

这些是java验证API的最新maven依赖项

1.dependency groupId javax.validation artifactId validation-api 版本 1.1.0.Final

2.dependency groupId org.hibernate artifactId hibernate-validator 版本 5.0.1.Final

答案 1 :(得分:0)

看看这个:

  1. 首先是对象......

    public class PruebaFormCommand {
    
    @NotEmpty
    @Size(min = 3, max = 50)
    private String textoPrueba;
    
    public String getTextoPrueba() {
        return textoPrueba;
    }
    
    public void setTextoPrueba(String textoPrueba) {
        this.textoPrueba = textoPrueba;
    }
    
    }
    
  2. 然后,控制器:

    @Controller
    public class PruebaFormController {
    
    @RequestMapping("/pruebaform")
    public String pruebaForm(Model model){
    
        model.addAttribute("pruebaFormCommand", new PruebaFormCommand());
    
        return "pruebaform";
    }
    
    @RequestMapping(value = "/dopruebaform", method = RequestMethod.POST)
    public String doPruebaForm(@Valid PruebaFormCommand pruebaFormCommand, BindingResult bindingResult){
    
        if (bindingResult.hasErrors()) {
            return "pruebaform";
        }
    
        return "pruebaformcomplete";
    
    }
    
    }
    
  3. 然后,HTML:

  4. <!DOCTYPE html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
        <meta charset="UTF-8"/>
    
        <link href="../static/css/bootstrap-3.3.4-dist/css/bootstrap.min.css" rel="stylesheet" media="screen"
              th:href="@{/css/bootstrap-3.3.4-dist/css/bootstrap.min.css}"/>
    
        <script src="../static/js/jquery-2.1.4.min.js"
                th:src="@{/js/jquery-2.1.4.min.js}"></script>
    
        <link th:href="@{/css/custom.css}" rel="stylesheet" media="screen"/>
        <title>Checkout</title>
    </head>
    <body>
    <div class="container">
        <h2>PRUEBA Form</h2>
    
        <form class="form-horizontal" th:object="${pruebaFormCommand}" th:action="@{/dopruebaform}" method="post">
    
            <div th:if="${#fields.hasErrors('*')}" class="alert alert-danger">
                <p th:text="#{pruebaFormCommand.hasErrors}">Error Message</p>
            </div>
    
            <div class="form-group" th:class="${#fields.hasErrors('textoPrueba')} ? 'form-group has-error' : 'form-group'">
                <label class="col-sm-2 control-label">Meteme algo payo:</label>
                <div class="col-sm-10">
                    <input type="text" class="form-control" th:field="*{textoPrueba}" th:errorclass="has-error"/>
    
                    <span class="help-block" th:if="${#fields.hasErrors('textoPrueba')}">
                           <ul>
                               <li th:each="err : ${#fields.errors('textoPrueba')}" th:text="${err}" />
                           </ul>
                    </span>
                </div>
            </div>
    
            <div class="row">
                <button type="submit" class="btn btn-default">Submit</button>
            </div>
        </form>
    </div>
    </body>
    </html>

    1. 最后,请添加message.properties:
    2.   

      pruebaFormCommand.hasErrors = Porfa corrige los errores:   NotEmpty.pruebaFormCommand.textoPrueba = {0}caracteresmínimo....   Size.pruebaFormCommand.textoPrueba = {0} debe tener entre {2} y {1} caracteres