Home > Back-end >  Thymeleaf each loop giving errors
Thymeleaf each loop giving errors

Time:12-11

I am trying to print errors on webpage loginform.html but th:each="e:${#fields.errors('email')}" th:text="${e}"

here is my loginform.html code

<!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 >
    <label for="username2">User name</label>
    <input type="text"  id="username2" placeholder="username" name="username"/>
    <!-- <div  th:each="e : ${#fields.errors('username')}" th:text="${e}"  >
          
        </div> -->   
  </div>
  <div >
    <label for="exampleInputEmail1">Email address</label>
    <input type="email"  name="email" aria-describedby="emailHelp" placeholder="Enter email">
    <small id="emailHelp" >We'll never share your email with anyone else.</small>
      <p  th:each="e:${#fields.errors('email')}" th:text="${e}"></p>
  </div>
  
  <div >
    <input type="checkbox"   name="agreed">
    <label  for="exampleCheck1">Check me out</label>
  </div>
  <button type="submit" >Submit</button>
</form>
    
</body>
</html>

Controller code :

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 code:

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

}

and Error is: Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback.

Wed Dec 08 11:15:55 IST 2021 There was an unexpected error (type=Internal Server Error, status=500). An error happened during template parsing (template: "class path resource [templates/loginform.html]") org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/loginform.html]") at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:241) at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parseStandalone(AbstractMarkupTemplateParser.java:100) at org.thymeleaf.engine.TemplateManager.parseAndProcess(TemplateManager.java:666) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1098) at org.thymeleaf.TemplateEngine.process(TemplateEngine.java:1072) at org.thymeleaf.spring5.view.ThymeleafView.renderFragment(ThymeleafView.java:366) at org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:190) at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1400) at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1145) at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1084) at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:963) at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006) at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898) at javax.servlet.http.HttpServlet.service(HttpServlet.java:655) at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883) at javax.servlet.http.HttpServlet.service(HttpServlet.java:764) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201) at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189) at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162) at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:197) at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97) at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:540) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:135) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92) at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78) at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357) at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:382) at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65) at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:895) at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1722) at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49) at org.apache.tomcat.util.threads.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1191) at org.apache.tomcat.util.threads.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:659) at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) at java.base/java.lang.Thread.run(Thread.java:834) Caused by: org.attoparser.ParseException: Exception evaluating SpringEL expression: "#fields.errors('email')" (template: "loginform" - line 28, col 11) at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:393) at org.attoparser.MarkupParser.parse(MarkupParser.java:257) at org.thymeleaf.templateparser.markup.AbstractMarkupTemplateParser.parse(AbstractMarkupTemplateParser.java:230) ... 48 more Caused by: org.thymeleaf.exceptions.TemplateProcessingException: Exception evaluating SpringEL expression: "#fields.errors('email')" (template: "loginform" - line 28, col 11) at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:292) at org.thymeleaf.standard.expression.VariableExpression.executeVariableExpression(VariableExpression.java:166) at org.thymeleaf.standard.expression.SimpleExpression.executeSimple(SimpleExpression.java:66) at org.thymeleaf.standard.expression.Expression.execute(Expression.java:109) at org.thymeleaf.standard.expression.Expression.execute(Expression.java:138) at org.thymeleaf.standard.expression.Expression.execute(Expression.java:125) at org.thymeleaf.standard.processor.StandardEachTagProcessor.doProcess(StandardEachTagProcessor.java:73) at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74) at org.thymeleaf.processor.element.AbstractElementTagProcessor.process(AbstractElementTagProcessor.java:95) at org.thymeleaf.util.ProcessorConfigurationUtils$ElementTagProcessorWrapper.process(ProcessorConfigurationUtils.java:633) at org.thymeleaf.engine.ProcessorTemplateHandler.handleOpenElement(ProcessorTemplateHandler.java:1314) at org.thymeleaf.engine.TemplateHandlerAdapterMarkupHandler.handleOpenElementEnd(TemplateHandlerAdapterMarkupHandler.java:304) at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler$InlineMarkupAdapterPreProcessorHandler.handleOpenElementEnd(InlinedOutputExpressionMarkupHandler.java:278) at org.thymeleaf.standard.inline.OutputExpressionInlinePreProcessorHandler.handleOpenElementEnd(OutputExpressionInlinePreProcessorHandler.java:186) at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler.handleOpenElementEnd(InlinedOutputExpressionMarkupHandler.java:124) at org.attoparser.HtmlElement.handleOpenElementEnd(HtmlElement.java:109) at org.attoparser.HtmlMarkupHandler.handleOpenElementEnd(HtmlMarkupHandler.java:297) at org.attoparser.MarkupEventProcessorHandler.handleOpenElementEnd(MarkupEventProcessorHandler.java:402) at org.attoparser.ParsingElementMarkupUtil.parseOpenElement(ParsingElementMarkupUtil.java:159) at org.attoparser.MarkupParser.parseBuffer(MarkupParser.java:710) at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:301) ... 50 more Caused by: 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) at org.springframework.web.servlet.support.RequestContext.getBindStatus(RequestContext.java:903) at org.thymeleaf.spring5.context.webmvc.SpringWebMvcThymeleafRequestContext.getBindStatus(SpringWebMvcThymeleafRequestContext.java:227) at org.thymeleaf.spring5.util.FieldUtils.getBindStatusFromParsedExpression(FieldUtils.java:306) at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:253) at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:227) at org.thymeleaf.spring5.util.FieldUtils.computeErrors(FieldUtils.java:98) at org.thymeleaf.spring5.util.FieldUtils.errors(FieldUtils.java:85) at org.thymeleaf.spring5.expression.Fields.errors(Fields.java:74) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at java.base/java.lang.reflect.Method.invoke(Method.java:566) at org.springframework.expression.spel.support.ReflectiveMethodExecutor.execute(ReflectiveMethodExecutor.java:129) at org.springframework.expression.spel.ast.MethodReference.getValueInternal(MethodReference.java:139) at org.springframework.expression.spel.ast.MethodReference.access$000(MethodReference.java:55) at org.springframework.expression.spel.ast.MethodReference$MethodValueRef.getValue(MethodReference.java:387) at org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:92) at org.springframework.expression.spel.ast.SpelNodeImpl.getValue(SpelNodeImpl.java:112) at org.springframework.expression.spel.standard.SpelExpression.getValue(SpelExpression.java:337) at org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:265) ... 70 more

CodePudding user response:

Your get method is incomplete. Your object that you are defining via th:object=${user}, does not exist in the model attribute map.

The error is explicit in this case:

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)

Modify the get mapping:

@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;
}
  • Related