springBoot + Thymeleaf:验证电子邮件

问题描述 投票:0回答:1

我有这个物体:

@Builder
@Data
@AllArgsConstructor
@NoArgsConstructor
public class NatalChartDataPayload {
    String langCode;
    @NotEmpty(message = "Email cannot be empty")
    @Email(message = "Invalid email format")
    String email;
    String city;
    String place;
  }

还有这个控制器:

@GetMapping({"/data"})
    public String data (Model model) {
        model.addAttribute("months", Month.values());
        model.addAttribute("data",   NatalChartDataPayload.builder().build());
        return "natalChartData";

    }

   

   

      @PostMapping("/create")
            public String createNatalChart ( @Valid @ModelAttribute NatalChartDataPayload data, BindingResult result, Model model) {
        
                if (result.hasErrors()) {
                    return "natalChartData";
                }
        
                User user = new User();
        
                user.setEmail(data.getEmail());
               
                if (data.getPlace()==null ||
                        data.getPlace().isEmpty() ||
                        data.getEmail()==null ||
                        data.getEmail().isEmpty()) {
                    return "redirect:/natalchart/data";
                }
    ..

但是当电子邮件不正确时,我会出现此错误:

... 124 common frames omitted
2024-04-20 06:46:32.854 ERROR [] o.a.c.c.C.[.[.[.[dispatcherServlet]@log(175) - Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed: org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/natalChartData.html]")] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'data' available as request attribute
    at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
    at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:926)
    at org.thymeleaf.spring6.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:232)
    at org.thymeleaf.spring6.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:306)
    at org.thymeleaf.spring6.util.FieldUtils.getBindStatus(FieldUtils.java:253)
    at org.thymeleaf.spring6.util.FieldUtils.getBindStatus(FieldUtils.java:227)
    at org.thymeleaf.spring6.util.FieldUtils.checkErrors(FieldUtils.java:212)
    at org.thymeleaf.spring6.util.FieldUtils.hasErrors(FieldUtils.java:71)
    at org.thymeleaf.spring6.expression.Fields.hasErrors(Fields.java:58)
    at java.base/jdk.internal.reflect.DirectMethodHandleAccessor.invoke(DirectMethodHandleAccessor.java:103)
    at java.base/java.lang.reflect.Method.invoke(Method.java:580)
    }

这里是模板:

 <form method="post" th:action="@{/natalchart/create}" th:object="${data}">
          <div class="row">
            <div class="col-lg-8">
                <h4>Enter your birth details to create your natal chart</h4>

              <p>&nbsp;</p>
              <p>&nbsp;</p>

              <div th:if="${#fields.hasErrors('email')}" th:errors="*{email}">Email Error</div>

                <div>

                  <label for="language">PDF Report Language</label>
                  <select th:field="*{langCode}">
                    <option value="en">English</option>
                    <option value="es">Spanish</option>
                    <option value="fr">French</option>
                    <option value="pt">Portuguese</option>
                  </select><br><br>

                  <label for="email">Email</label>
                  <input id="email" name="email" placeholder="email" th:field="*{email}"  /><br><br>

                  <!-- Label and select fields for day, month, and year of birth -->
                  <label for="dayOfBirth">Date of Birth:</label>
                  <select id="dayOfBirth" th:field="*{dayOfBirth}">
                    <option th:each="day : ${#numbers.sequence(1, 31)}" th:text="${day}" th:value="${day}"></option>
                  </select>
                  <select id="monthOfBirth" th:field="*{monthOfBirth}">
                    <option th:each="month : ${months}" th:text="${month}" th:value="${month.getValue()}"></option>
                  </select>
                  <select id="yearOfBirth" th:field="*{yearOfBirth}">
                    <option th:each="year : ${#numbers.sequence(1900, 2025)}" th:text="${year}" th:value="${year}"></option>
                  </select>
                  <br><br>
                  <!-- Label and select fields for hour and minute of birth -->
                  <label for="hourOfBirth">Time of Birth:</label>
                  <select id="hourOfBirth" th:field="*{hourOfBirth}">
                    <option th:each="hour : ${#numbers.sequence(0, 23)}" th:text="${hour}" th:value="${hour}"></option>
                  </select>
                  <select id="minuteOfBirth" th:field="*{minuteOfBirth}">
                    <option th:each="minute : ${#numbers.sequence(0, 59)}" th:text="${minute}" th:value="${minute}"></option>
                  </select>
                  <br><br>
                  <label for="hint">Place of birth (Select one of the list)</label>
                  <input id="hint"  name="hint"   th:field="*{city}" /><br><br>
                  <input id="place" name="place" th:field="*{place}" type="hidden"/>

                </div>




          </div>


            <div class="col-lg-4">
              <div class="blog-sidbar">


                    <div class="d-flex justify-content-between mt-20">
                      <button class="fill-btn" data-text="Send Message" type="submit">create PDF Natal Chart Report</button>
                    </div>


              </div>
            </div>

        </div>

          </form>
java spring spring-boot thymeleaf spring-thymeleaf
1个回答
0
投票

您使用 html 表单发送的数据与您的 NatalChartDataPayload 类不匹配(没有出生日期、出生分钟和其他字段),因此 BindingResult 无法将其接收到的数据映射到 NatalChartDataPayload 对象。

也许,您可以创建一个 dto 类,其中的字段与您的 html 表单匹配,然后再试一次。

© www.soinside.com 2019 - 2024. All rights reserved.