为什么Thymelaf在渲染时为每个循环提供错误



我正试图在网页loginform.html上打印错误,但th:each="e: ${#fields.errors('email')}"th:text="${e} ";

这是我的loginform.html代码

<!doctype html>
<html lang="en" xmlns:th="http://www.thymeleaf.org/">
<head>
<meta charset="UTF-8" />
<title>Log In</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">

</head>
<body>
<form th:action="@{/process}" method="post" th:object="${User}">

<div class="form-group">
<label for="username2">User name</label>
<input type="text" class="form-control" id="username2" placeholder="username" name="username"/>
<!-- <div  th:each="e : ${#fields.errors('username')}" th:text="${e}"  class="invalid-feedback">

</div> -->   
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email address</label>
<input type="email" class="form-control" name="email" aria-describedby="emailHelp" placeholder="Enter email">
<small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
<p  th:each="e:${#fields.errors('email')}" th:text="${e}"></p>
</div>

<div class="form-group form-check">
<input type="checkbox" class="form-check-input"  name="agreed">
<label class="form-check-label" for="exampleCheck1">Check me out</label>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
</form>

</body>
</html>

控制器代码:

package com.validation.controller;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.validation.BindingResult;
import com.validation.entities.User;
@Controller
public class FormController {

@GetMapping("/form")
public String form()
{


return "loginform";

}


@PostMapping("/process")
public String process(@Valid @ModelAttribute("User") User user,BindingResult result )
{

if(result.hasErrors())
{
System.out.println(result);

return "loginform";
}

return "success";
}

}

User.java代码:

package com.validation.entities;
import java.util.List;
import javax.validation.constraints.AssertTrue;
import javax.validation.constraints.Email;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
public class User {

@NotBlank(message="User name can't be blank")
@Size( min=3,max=12 ,message="User name must be between 3-12 chars.")
private String username;

@Email(regexp="^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$", message="invalid email")
private String email;

@AssertTrue
private boolean agreed;

//public List<Integer> list= List.of(1,2,3,4,5);

public boolean isAgreed() {
return agreed;
}
public void setAgreed(boolean agreed) {
this.agreed = agreed;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
@Override
public String toString() {
return "User [username=" + username + ", email=" + email + "]";
}
public void setEmail(String email) {
this.email = email;
}
}

,错误为:白标签错误页此应用程序没有/error的显式映射,因此您将其视为回退。

2021年12月8日星期三11:15:55 IST出现意外错误(类型=内部服务器错误,状态=500)。在模板解析过程中发生错误(模板:"类路径资源[templates/loginform.html]")org.thimeleaf.exceptions.TemplateInput异常:模板分析过程中发生错误(模板:"类路径资源[templates/loginform.html]")网址:org.thymelaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplate Parser.java:241)网址:org.thymelaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplate Parser.java:100)网址:org.thymelaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666)网址:org.thymelaf.TemplateEngine.produce(TemplateEngine.java:1098)网址:org.thymelaf.TemplateEngine.produce(TemplateEngine.java:1072)网址:org.thymelaf.spring5.view.ThymeleafView.renderFragment(ThymelafView.java:366)网址:org.thymelaf.spring5.view.ThymeleafView.render(ThymelafView.java:190)位于org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1400)位于org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1145)位于org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1084)网址:org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963)网址:org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)网址:org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)位于javax.servlet.httpHttpServlet.service(HttpServlet.java:655)网址:org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)位于javax.servlet.httpHttpServlet.service(HttpServlet.java:764)网址:org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)网址:org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)网址:org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)网址:org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)网址:org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)网址:org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)网址:org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequest filter.java:119)网址:org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)网址:org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)网址:org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)网址:org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequest filter.java:119)网址:org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)网址:org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)网址:org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncoding filter.java:201)网址:org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequest filter.java:119)网址:org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)网址:org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)网址:org.apache.catalina.core.StandardWrapperValv.invoke(StandardWrapperValve.java:197)网址:org.apache.catalina.core.StandardContextValv.invoke(StandardContextValv.java:97)网址:org.apache.catalina.authenticator.AuthenticatorBase.ioke(AuthenticatorBase.java:540)网址:org.apache.catalina.core.StandardHostValv.invoke(StandardHostValv.java:135)网址:org.apache.catalina.vals.ErrorReportValve.ioke(ErrorReportValve.java:92)网址:org.apache.catalina.core.StandardEngineValv.invoke(StandardEngineValv.java:78)网址:org.apache.catalina.connecter.CoyoteAdapter.service(Coyotedapter.java:357)网址:org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382)网址:org.apache.coyote.AbstractProcessorLight.produce(AbstractProcessorLight.java:65)网址:org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895)网址:org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722)网址:org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)网址:org.apache.tomcat.util.threads.ThreadPoolExecutior.runWorker(ThreadPoolExecutior.java:1191)网址:org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659)网址:org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)位于java.base/java.lang.Thread.run(线程.java:834)导致原因:org.attoparser.ParseException:评估SpringEL表达式时出现异常:"#fields.errors('mail')";(模板:"loginform"-第28行,第11列)网址:org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393)网址:org.attoparser.MarkupParser.parse(MarkupParser.java:257)网址:org.thymelaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplate Parser.java:230)…还有48由以下原因引起:org.themeleaf.exceptions.TemplateProcessingException:评估SpringEL表达式时出现异常:"#fields.errors('mail')";(模板:"loginform"-第28行,第11列)网址:org.thymelaf.spring5.expression.SPELVariableExpressionEvaluator.eevaluate(SPELVariableExpression Evaluator.java:292)网址:org.thymelaf.standard.exexpression.VariableExpression.executeVariableExpression(VariableExpression.java:166)网址:org.thymelaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:66)网址:org.thymelaf.standard.expression.expression.execute(expression.java:109)网址:org.thymelaf.standard.expression.expression.execute(expression.java:138)网址:org.thymelaf.standard.expression.expression.execute(expression.java:125)网址:org.thymelaf.standard.processor.StandardEachTagProcessor.doProcess(StandardEachTagProcesser.java:73)网址:org.thymelaf.processer.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcess.java:74)网址:org.thymelaf.processor.element.AbstractElementTagProcessor.procedure(AbstractElementTagProcesser.java:95)网址:org.thymelaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633)网址:org.thymelaf.engine.ProcessorTemplateHandler.handleOpenElement(ProcessorTemplateHandler.java:1314)位于org.thymelaf.engine.TemplateHandlerAdapterMarkupHandler.handleOpenElementEnd(TemplateHandlerAdapter MarkupHandler.java:304)网址:org.thymelaf.templatesepser.markup.InlinedOutputExpressionMarkupHandler$InlineMarkupAdapterPreProcessorHandler.handleOpenElementEnd(InlinedOutputExpression MarkupHandler.java:278)网址:org.thymelaf.standard.inline.OutputExpressionInlinePreProcessorHandler.handleOpenElementEnd(OutputExpressionInlinePreProcessorHandler.java:186)网址:org.thymelaf.templateepaser.markup.InlinedOutputExpressionMarkupHandler.handleOpenElementEnd(InlinedOutputExpression MarkupHandler:124)网址:org.attoparser.HtmlElement.handleOpenElementEnd(HtmlElement.java:109)网址:org.attoparser.HtmlMarkupHandler.handleOpenElementEnd(HtmlMarkupHandler.java:297)网址:org.attoparser.MarkupEventProcessorHandler.handleOpenElementEnd(MarkupEventProcessorHandler.java:402)网址:org.attoparser.ParsingElementMarkupUtil.parseOpenElement(ParsingElementMarkupUtil.java:159)网址:org.attoparser.MarkupParser.parseBuffer(MarkupParser.java:710)网址:org.attoparser.MarkupParser.parseDocument(MarkupParser.java:301)…50多引起原因:java.lang.IllegalStateException:bean名称"User"的BindingResult和纯目标对象都不可用作请求属性网址:org.springframework.web.servlet.support.BindStatus.(BindStatus.java:153)网址:org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903)网址:org.thymeef.spring5.context.webmvc.SpringWebMvcThymeeafRequestContext.getBindStatus(SpringWebMVCThymeeaf RequestContext.java:227)位于org.thymelaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:306)网址:org.thymelaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:253)网址:org.thymelaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:227)网址:org.thymelaf.spring5.util.FieldUtils.computeErrors(FieldUtils.java:98)网址:org.thymelaf.spring5.util.FieldUtils.errors(FieldUtils.java:85)网址:org.thymelaf.spring5.expression.Fields.errors(Fields.java:74)位于java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)位于java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)位于java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)位于java.base/java.lang.reflect.Method.ioke(Method.java:566)网址:org.springframework.exexpression.spel.support.ReflectiveMethodExecutor.execute(ReflectiveMethodExecutor.java:129)位于org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:139)网址:org.springframework.expression.spel.ast.MethodReference.access$000(MethodReference.java:55)位于org.springframework.expression.spel.ast.MethodReference$MethodValueRef.getValue(MethodReference.java:387)位于org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:92)位于org.springframework.exexpression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:112)网址:org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:337)网址:org.thymelaf.spring5.expression.SPELVariableExpressionEvaluator.eevaluate(SPELVariableExpression Evaluator.java:265)…再增加70个

您的get方法不完整。通过th:object=${user}定义的对象在模型属性映射中不存在。

在这种情况下,错误是明确的:

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'User' available as request attribute at org.springframework.web.servlet.support.BindStatus.(BindStatus.java:153)

修改获取映射:

@GetMapping("/form")
public ModelAndView form(ModelAndView modelAndView) {
User user = new User(); // or however you want to fetch the user entity / dto
modelAndView.addObject("user", user);
modelAndView.setViewName("loginform");
return modelAndView;
}

相关内容

  • 没有找到相关文章

最新更新