Struts2 - The list key couldn't be resolved - java

am working on Struts 2 radio button. I want to retrieve the list from my action class but it is giving following error
These are my files:
struts.xml -
<action name="radioButtonAction"
class="com.mkyong.common.action.RadioButtonAction" method="display">
<result name="none">/radiobutton.jsp</result>
</action>
<action name="resultAction" class="com.mkyong.common.action.RadioButtonAction">
<result name="success">/result.jsp</result>
</action>
radiobutton.jsp -
<body>
<h1>Struts 2 radio button example</h1>
<s:form action="resultAction" namespace="/">
<h2>
<s:radio label="Gender" name="yourGender" list="genders" value="defaultGenderValue" />
<s:radio label="Gender" name="yourLanguage" list="languages"
listKey="languageCode" listValue="languageDisplay" value="defaultLanguageValue" />
<s:radio label="Answer" name="yourAnswer" list="#{'1':'Yes','2':'No'}" value="2" />
</h2>
<s:submit value="submit" name="submit" />
</s:form>
</body>
RadioButtonAction.java --
package com.mkyong.common.action;
import java.util.ArrayList;
import java.util.List;
import com.mkyong.common.model.Language;
import com.opensymphony.xwork2.ActionSupport;
public class RadioButtonAction extends ActionSupport{
private List<String> genders;
private List<Language> languages ;
private String yourGender;
private String yourAnswer;
private String yourLanguage;
private static final String MALE = "male";
private static final String FEMALE = "female";
private static final String UNKNOWN = "unknown";
public RadioButtonAction(){
genders = new ArrayList<String>();
genders.add(MALE);
genders.add(FEMALE);
genders.add(UNKNOWN);
languages = new ArrayList<Language>();
languages.add( new Language("EN", "English") );
languages.add( new Language("FR", "France") );
languages.add( new Language("CN_ZH", "Chinese") );
languages.add( new Language("DE", "German") );
}
//return default gender value
public String getDefaultGenderValue(){
return UNKNOWN;
}
//return default language value
public String getDefaultLanguageValue(){
return "CN_ZH";
}
public String execute() {
return SUCCESS;
}
public String display() {
return NONE;
}
//getter ad setter methods
}
Languge.java --
package com.mkyong.common.model;
public class Language{
private String languageCode;
private String languageDisplay;
//getter and setter methods
public Language(String languageCode, String languageDisplay) {
this.languageCode = languageCode;
this.languageDisplay = languageDisplay;
}
}
Anything I did, still the same error persists,I know why this is happening...
SCHWERWIEGEND: Servlet.service() for servlet [jsp] in context with path [/RadioButton] threw exception [An exception occurred processing [radiobutton.jsp] at line [13]
10:
11: <h2>
12: <s:radio label="Gender" name="yourGender" list="genders" value="defaultGenderValue" />
13:
14: <s:radio label="Gender" name="yourLanguage" list="languages"
15: listKey="languageCode" listValue="languageDisplay" value="defaultLanguageValue" />
16:
Stacktrace:] with root cause
tag 'radio', field 'list', name 'yourGender': The requested list key 'genders' could not be resolved as a collection/array/map/enumeration/iterator type. Example: people or people.{name} - [unknown location]
at org.apache.struts2.components.Component.fieldError(Component.java:257)
at org.apache.struts2.components.Component.findValue(Component.java:353)
at org.apache.struts2.components.ListUIBean.evaluateExtraParams(ListUIBean.java:81)
at org.apache.struts2.components.Radio.evaluateExtraParams(Radio.java:70)
at org.apache.struts2.components.UIBean.evaluateParams(UIBean.java:884)
at org.apache.struts2.components.UIBean.end(UIBean.java:533)
at org.apache.struts2.views.jsp.ComponentTagSupport.doEndTag(ComponentTagSupport.java:39)
at org.apache.jsp.radiobutton_jsp._jspx_meth_s_005fradio_005f0(radiobutton_jsp.java:249)
at org.apache.jsp.radiobutton_jsp._jspx_meth_s_005fform_005f0(radiobutton_jsp.java:192)
at org.apache.jsp.radiobutton_jsp._jspService(radiobutton_jsp.java:143)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:386)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:330)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter.doFilter(StrutsPrepareAndExecuteFilter.java:138)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:199)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:668)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:791)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1417)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
how can fix this ... Anyone has an idea?

You need getter methods for genders and languages.
public List getGenders() {
return genders;
}
Same for languages.

Related

Binding result gives Whitelabel Error Page

I have a thymeleaf form where i can add a subcategory to a parent category:
<div th:if="${parentCategories.size() == 0}">
<span>There are no categories, please, add some categories!</span>
</div>
<div th:unless="${parentCategories.size() == 0}">
<label for="subcategoryForm">Add a subcategory</label>
<form id="subcategoryForm" th:action="#{/category/add-subcategory}" th:object="${category}" method="post">
<label for="name">Category name</label>
<input id="name" type="text" th:field="*{categoryName}"/>
<span th:if="${#fields.hasErrors('categoryName')}" th:errors="*{categoryName}" th:errorclass="error"></span>
<label for="selectParentCategory">Enter a parent category</label>
<select id="selectParentCategory" th:field="*{parentCategoryName}">
<option th:each="category : ${parentCategories}"
th:value="${category.categoryName}"
th:text="${category.categoryName}"/>
<span th:if="${#fields.hasErrors('parentCategoryName')}" th:errors="*{parentCategoryName}" th:errorclass="error"></span>
</select>
<button type="submit">Add category</button>
</form>
</div>
I have a CategoryDTO:
#Setter
#Getter
public class CategoryDTO {
#CategoryValidator
private String categoryName;
#ParentCategoryValidator
private String parentCategoryName;
}
That #CategoryValidator is validated by CategoryValidatorImpl:
#Autowired
private CategoryRepository categoryRepository;
#Override
public boolean isValid(String value, ConstraintValidatorContext context) {
if(value.isBlank()){
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("{categoryDTO.blank}").addConstraintViolation();
return false;
}
Optional<Category> optionalCategory = categoryRepository.findByName(value);
if (optionalCategory.isPresent()) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("{categoryDTO.alreadyExists}").addConstraintViolation();
return false;
}
Pattern pattern = Pattern.compile("[a-zA-Z\\s]*");
Matcher matcher = pattern.matcher(value);
if (!matcher.matches()) {
context.disableDefaultConstraintViolation();
context.buildConstraintViolationWithTemplate("{categoryDTO.name.invalid}").addConstraintViolation();
return false;
}
return true;
}
And a part of CategoryController:
#GetMapping("/subcategory-form")
public String getSubcategoryForm(Model model){
List<CategoryDTO> listOfParentCategories = categoryService.getParentCategories();
model.addAttribute("category", new CategoryDTO());
model.addAttribute("parentCategories", listOfParentCategories);
return "add-subcategory-form";
}
#PostMapping("/add-subcategory")
public String addSubcategory(#Valid #ModelAttribute("category") CategoryDTO categoryDTO, BindingResult bindingResult){
if(bindingResult.hasErrors()){
return "add-subcategory-form";
}
categoryService.add(categoryDTO);
return "redirect:/category/subcategory-form";
}
In the input field when i enter a blank, the validator discovers it properly using hasErrors in the controller, but when i'm returning the form after discovering the blank and returning false, it gives this:
Whitelabel Error Page This application has no explicit mapping for
/error, so you are seeing this as a fallback.
Wed Nov 18 13:45:26 EET 2020 There was an unexpected error
(type=Internal Server Error, status=500). An error happened during
template parsing (template: "class path resource
[templates/add-subcategory-form.html]")
org.thymeleaf.exceptions.TemplateInputException: An error happened
during template parsing (template: "class path resource
[templates/add-subcategory-form.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:362)
at
org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:189)
at
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1373)
at
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118)
at
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057)
at
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
at
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:652) at
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733) at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
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:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
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:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.springframework.boot.actuate.metrics.web.servlet.WebMvcMetricsFilter.doFilterInternal(WebMvcMetricsFilter.java:93)
at
org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at
org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
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:193)
at
org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at
org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at
org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at
org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at
org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
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:343)
at
org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at
org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at
org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at
org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at
org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at
java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at
java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
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: "parentCategories.size() == 0" (template:
"add-subcategory-form" - line 13, col 10) 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)
... 52 more Caused by:
org.thymeleaf.exceptions.TemplateProcessingException: Exception
evaluating SpringEL expression: "parentCategories.size() == 0"
(template: "add-subcategory-form" - line 13, col 10) at
org.thymeleaf.spring5.expression.SPELVariableExpressionEvaluator.evaluate(SPELVariableExpressionEvaluator.java:290)
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.StandardIfTagProcessor.isVisible(StandardIfTagProcessor.java:59)
at
org.thymeleaf.standard.processor.AbstractStandardConditionalVisibilityTagProcessor.doProcess(AbstractStandardConditionalVisibilityTagProcessor.java:61)
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) ...
54 more Caused by:
org.springframework.expression.spel.SpelEvaluationException: EL1011E:
Method call: Attempted to call method size() on null context object
at
org.springframework.expression.spel.ast.MethodReference.throwIfNotNullSafe(MethodReference.java:154)
at
org.springframework.expression.spel.ast.MethodReference.getValueRef(MethodReference.java:83)
at
org.springframework.expression.spel.ast.CompoundExpression.getValueRef(CompoundExpression.java:70)
at
org.springframework.expression.spel.ast.CompoundExpression.getValueInternal(CompoundExpression.java:91)
at
org.springframework.expression.spel.ast.OpEQ.getValueInternal(OpEQ.java:42)
at
org.springframework.expression.spel.ast.OpEQ.getValueInternal(OpEQ.java:32)
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:263)
... 75 more
The thing is, for the other form of mine where i have to add just parent categories, if i add a blank, it returns the thymeleaf and prints the error message i wrote, but i can't figure this out for this form.
The stacktrace has the following hints on the problem:
Exception evaluating SpringEL expression: "parentCategories.size() == 0" (template: "add-subcategory-form" - line 13, col 10)
and:
Attempted to call method size() on null context object at
This means that parentCategories is not present anymore in the Thymeleaf context.
You need to re-add the parentCategories in the model again when there are errors:
#PostMapping("/add-subcategory")
public String addSubcategory(#Valid #ModelAttribute("category") CategoryDTO categoryDTO, BindingResult bindingResult) {
if(bindingResult.hasErrors()){
List<CategoryDTO> listOfParentCategories = categoryService.getParentCategories();
model.addAttribute("parentCategories", listOfParentCategories);
return "add-subcategory-form";
}
categoryService.add(categoryDTO);
return "redirect:/category/subcategory-form";
}

An error happened during template parsing (template: "class path resource [templates/index.html]")

I'm trying to open my html page but I'm stuck with these error whenever I try to get access to localhost.
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Aug 11 18:24:14 CEST 2020
There was an unexpected error (type=Internal Server Error, status=500).
An error happened during template parsing (template: "class path resource [templates/index.html]")
org.thymeleaf.exceptions.TemplateInputException: An error happened during template parsing (template: "class path resource [templates/index.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:362)
at org.thymeleaf.spring5.view.ThymeleafView.render(ThymeleafView.java:189)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1373)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1118)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1057)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:943)
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:626)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
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:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
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:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
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:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1589)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:832)
Caused by: org.attoparser.ParseException: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "index" - line 9, col 36)
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: Error during execution of processor 'org.thymeleaf.spring5.processor.SpringInputGeneralFieldTagProcessor' (template: "index" - line 9, col 36)
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:117)
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.handleStandaloneElement(ProcessorTemplateHandler.java:918)
at org.thymeleaf.engine.TemplateHandlerAdapterMarkupHandler.handleStandaloneElementEnd(TemplateHandlerAdapterMarkupHandler.java:260)
at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler$InlineMarkupAdapterPreProcessorHandler.handleStandaloneElementEnd(InlinedOutputExpressionMarkupHandler.java:256)
at org.thymeleaf.standard.inline.OutputExpressionInlinePreProcessorHandler.handleStandaloneElementEnd(OutputExpressionInlinePreProcessorHandler.java:169)
at org.thymeleaf.templateparser.markup.InlinedOutputExpressionMarkupHandler.handleStandaloneElementEnd(InlinedOutputExpressionMarkupHandler.java:104)
at org.attoparser.HtmlElement.handleStandaloneElementEnd(HtmlElement.java:79)
at org.attoparser.HtmlMarkupHandler.handleStandaloneElementEnd(HtmlMarkupHandler.java:241)
at org.attoparser.MarkupEventProcessorHandler.handleStandaloneElementEnd(MarkupEventProcessorHandler.java:327)
at org.attoparser.ParsingElementMarkupUtil.parseStandaloneElement(ParsingElementMarkupUtil.java:96)
at org.attoparser.MarkupParser.parseBuffer(MarkupParser.java:706)
at org.attoparser.MarkupParser.parseDocument(MarkupParser.java:301)
... 50 more
Caused by: org.springframework.beans.NotReadablePropertyException: Invalid property 'fullName' of bean class [com.example.demo.domain.User]: Bean property 'fullName' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:622)
at org.springframework.beans.AbstractNestablePropertyAccessor.getPropertyValue(AbstractNestablePropertyAccessor.java:612)
at org.springframework.validation.AbstractPropertyBindingResult.getActualFieldValue(AbstractPropertyBindingResult.java:104)
at org.springframework.validation.AbstractBindingResult.getFieldValue(AbstractBindingResult.java:228)
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:129)
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:258)
at org.thymeleaf.spring5.util.FieldUtils.getBindStatus(FieldUtils.java:227)
at org.thymeleaf.spring5.processor.AbstractSpringFieldTagProcessor.doProcess(AbstractSpringFieldTagProcessor.java:174)
at org.thymeleaf.processor.element.AbstractAttributeTagProcessor.doProcess(AbstractAttributeTagProcessor.java:74)
... 63 more
I will attach the files involved:
Home controller:
#Controller
public class HomeController {
#RequestMapping("/")
public String home(Model model) {
model.addAttribute("formData", new User());
return "index";
}
#RequestMapping(value = "/create", method = RequestMethod.POST)
public String processFormData(User user) {
return "results";
}
}
User domain class:
public class User {
private String fullName;
private int age;
private boolean employed;
private String gender;
public User() {}
public User(String full_name, int age, boolean employed, String gender) {
super();
this.fullName = full_name;
this.age = age;
this.employed = employed;
this.gender = gender;
}
// GETTER AND SETTERS HERE
}
index.html:
<!doctype html>
<html lang="en" xmlns:th="https://www.thymeleaf.org/">
<head>
<meta charset="UTF-8" />
<title>Home page</title>
</head>
<body>
<form action="/create" method="POST" th:object="${formData}">
<p>Full name: <input type="text" th:field="${formData.fullName}" /></p>
<p>Age: <input type="text" th:field="${formData.age}" /></p>
<p>Employed: <input type="checkbox" th:field="${formData.employed}" th:value="true"/></p>
<p>
Gender: <br>
Male <input type="radio" th:field="${formData.gender}" th:value="Male" />
Female <input type="radio" th:field="${formData.gender}" th:value="Female" />
</p>
<p>
<input type="submit" value="Submit"/>
<input type="reset" value="Reset"/>
</p>
</form>
</body>
</html>
Invalid property 'fullName' of bean class [com.example.demo.domain.User]: Bean property 'fullName' is not readable or has an invalid getter method
Thymeleaf can only access the properties of objects via getters. Also if you were to use object binding with Thymeleaf you would have to make sure you have setters and default constructor.
In general whenever you work with Thymeleaf it is a good idea to define all the getters, setters and default constructor for all objects being passed to thymeleaf.
you should change the visibility of the user's properties to public.
and it's done.
greetings from El salvador

JSP Error in ForEach Loop and PropertyNotFoundExceptions

I am new to java and im using Eclipse IDE. Im doing a project where Admin is adding employees to the system. and i need to display the list of the employees by retrieving the data from the database and view it in a separate table (separate jsp page). even though the data is added to the database im not able to retrieve it. and i have used a for each loop in the jsp page. when the view page jspPropertyNotFoundException is being called .
Model classes
public class Person {
private String Nic;
private String Name;
private String Email;
private String Phone;
private String Address;
public Person(String Nic, String Name, String Email, String Phone, String Address) {
this.Nic = Nic;
this.Name = Name;
this.Email = Email;
this.Phone = Phone;
this.Address = Address;
}
public void setNic(String Nic) {
this.Nic = Nic;
}
public String getNic() {
return Nic;
}
public class Employee extends Person {
private String YearsOfExperience;
private String Specialization;
private String Salary;
public Employee(String Nic, String Name, String Email, String Phone, String Address, String YearsOfExperience,
String Specialization, String Salary) {
super(Nic, Name, Email, Phone, Address);
this.YearsOfExperience = YearsOfExperience;
this.Specialization = Specialization;
this.Salary = Salary;
}
public String getYearsOfExperience() {
return YearsOfExperience;
}
jsp page i want display the data (EmployeeList.jsp)
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<table>
<c:forEach var="emp" items="${employeeDetails}">
<c:set var="Nic" value="${emp.Nic}"/>
<c:set var="Name" value="${emp.Name}"/>
<c:set var="Email" value="${emp.Email}"/>
<c:set var="Phone" value="${emp.Phone}"/>
<c:set var="Address" value="${emp.Address}"/>
<c:set var="YearsOfExperience" value="${emp.YearsOfExperience}"/>
<c:set var="Specialization" value="${emp.Specialization}"/>
<c:set var="Salary" value="${emp.Salary}"/>
<tbody>
<tr>
<td>${emp.Nic}</td>
<td>${emp.Name}</td>
<td>${emp.Email}</td>
<td>${emp.Phone}</td>
<td>${emp.Address}</td>
<td>${emp.YearsOfExperience}</td>
<td>${emp.Specialization}</td>
<td>${emp.Salary}</td>
</tr>
</tbody>
</c:forEach>
</table>
addEmployee Servlet
#WebServlet("/addEmployeeServlet")
public class addEmployeeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String Nic= request.getParameter("Nic");
String Name= request.getParameter("Name");
String Email= request.getParameter("Email");
String Phone= request.getParameter("Phone");
String Address= request.getParameter("Address");
String YearsOfExperience= request.getParameter("YearsOfExperience");
String Specialization = request.getParameter("Specialization");
String Salary= request.getParameter("Salary");
boolean isTrue;
isTrue = EmployeeDBUtil.AddEmployee(Nic,Name,Email,Phone,Address,YearsOfExperience,Specialization,Salary);
//if inserted to database
if(isTrue == true) {
List <Employee> employeeDetails = EmployeeDBUtil.viewAllEmployee();
request.setAttribute("employeeDetails",employeeDetails);
RequestDispatcher dis1 =request.getRequestDispatcher("EmployeeList.jsp");
dis1.forward(request, response);
}
else {
RequestDispatcher dis2 =request.getRequestDispatcher("Unsuccess.jsp");
dis2.forward(request, response);
}
}
EmployeeDBUtil
public class EmployeeDBUtil {
private static Connection con= null;
private static Statement stmt = null;
private static ResultSet rs = null;
private static boolean isSuccess;
// data from the database
public static List<Employee> viewAllEmployee() {
ArrayList <Employee> emp = new ArrayList<>();
try {
con = DBconnection.getConnection();
stmt = con.createStatement();
String sql = "Select * from employee";
rs= stmt.executeQuery(sql);
while(rs.next()) {
String Nic= rs.getString(1);
String Name = rs.getString(2);
String Email = rs.getString(3);
String Phone =rs.getString(4);
String Address =rs.getString(5);
String YearsOfExperience =rs.getString(6);
String Specialization =rs.getString(7);
String Salary =rs.getString(8);
Employee e = new Employee(Nic,Name,Email,Phone,Address,YearsOfExperience,Specialization,Salary);
emp.add(e);
System.out.println("im here");
}
}catch(Exception e){
e.printStackTrace();
}
return emp;
}
Web Xml file
?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>AddEmployee</servlet-name>
<servlet-class>com.carepoint.servlet.addEmployeeServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>AddEmployee</servlet-name>
<url-pattern>/Add</url-pattern>
</servlet-mapping>
</web-app>
when i add an employee to the system and it goes to the EmployeeList.jsp page but it does show the table or the list . Though the Nic is in person model. This is the error that is shown .
May 09, 2020 7:04:31 PM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet [jsp] threw exception
org.apache.jasper.el.JspPropertyNotFoundException: /EmployeeList.jsp(315,9) '${emp.Nic}' Property [Nic] not found on type [com.carepoint.model.Employee]
at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:120)
at org.apache.jsp.EmployeeList_jsp._jspx_meth_c_005fset_005f0(EmployeeList_jsp.java:659)
at org.apache.jsp.EmployeeList_jsp._jspx_meth_c_005fforEach_005f0(EmployeeList_jsp.java:558)
at org.apache.jsp.EmployeeList_jsp._jspService(EmployeeList_jsp.java:441)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
at com.carepoint.servlet.addEmployeeServlet.doPost(addEmployeeServlet.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
May 09, 2020 7:04:31 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [AddEmployee] in context with path [/Care-Point-Service-Station] threw exception [An exception occurred processing [/EmployeeList.jsp] at line [315]
312:
313: <c:forEach var="emp" items="${employeeDetails}">
314:
315: <c:set var="Nic" value="${emp.Nic}"/>
316: <c:set var="Name" value="${emp.Name}"/>
317: <c:set var="Email" value="${emp.Email}"/>
318: <c:set var="Phone" value="${emp.Phone}"/>
Stacktrace:] with root cause
org.apache.jasper.el.JspPropertyNotFoundException: /EmployeeList.jsp(315,9) '${emp.Nic}' Property [Nic] not found on type [com.carepoint.model.Employee]
at org.apache.jasper.el.JspValueExpression.getValue(JspValueExpression.java:120)
at org.apache.jsp.EmployeeList_jsp._jspx_meth_c_005fset_005f0(EmployeeList_jsp.java:659)
at org.apache.jsp.EmployeeList_jsp._jspx_meth_c_005fforEach_005f0(EmployeeList_jsp.java:558)
at org.apache.jsp.EmployeeList_jsp._jspService(EmployeeList_jsp.java:441)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:71)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:477)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
at com.carepoint.servlet.addEmployeeServlet.doPost(addEmployeeServlet.java:48)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:660)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:541)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:690)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:373)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:868)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1590)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
why cant i retrieve the data ?
Address the following things in your code:
Follow Java naming conventions e.g. Nic should be named as nic. You have violated the convention for all your variables.
Since you have already used the annotation, #WebServlet, you do not need to declare mapping in web.xml.
Given below is the Minimal, Complete, and Verifiable example:
Person.java:
package beans;
public class Person {
private String nic;
private String name;
private String email;
private String phone;
private String address;
public Person(String nic, String name, String email, String phone, String address) {
this.nic = nic;
this.name = name;
this.email = email;
this.phone = phone;
this.address = address;
}
public String getNic() {
return nic;
}
public void setNic(String nic) {
this.nic = nic;
}
}
Employee.java:
package beans;
public class Employee extends Person {
private String yearsOfExperience;
private String specialization;
private String salary;
public Employee(String nic, String name, String email, String phone, String address, String yearsOfExperience,
String specialization, String salary) {
super(nic, name, email, phone, address);
this.yearsOfExperience = yearsOfExperience;
this.specialization = specialization;
this.salary = salary;
}
}
AddEmployeeServlet.java:
package servlets;
import java.io.IOException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import beans.Employee;
#WebServlet("/addEmployeeServlet")
public class AddEmployeeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
List<Employee> employeeDetails = List.of(new Employee("123", null, null, null, null, null, null, null),
new Employee("456", null, null, null, null, null, null, null));
request.setAttribute("employeeDetails", employeeDetails);
request.getRequestDispatcher("employees.jsp").forward(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
}
employees.jsp:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<table>
<c:forEach var="emp" items="${employeeDetails}">
<tr>
<td>${emp.nic}</td>
</tr>
</c:forEach>
</table>
Output:

Neither BindingResult nor plain target object for bean name 'searchPhrase' available as request attribute

I am trying to implement a search functionality.
However I keep ending up with the above error.
I have tried solutions to similar problems posted on this forum, they do not seem to work.
SearchController
#Controller
public class SearchController {
#Autowired
private TrainingService service;
#ModelAttribute("searchPhrase")
public SearchPhrase getSearchPhrase()
{
System.out.println("wjxjedxkedhxkhklxhkldxhljel");
return new SearchPhrase();
}
#RequestMapping(value="/trainingSearch", method=RequestMethod.POST)
public String displayTrainings(#ModelAttribute("searchPhrase") SearchPhrase p, Model model)
{
System.out.println("wjxjedxkedhxkhklxhkldxhljel");
model.addAttribute("title", "Trainings");
//Create flight bean
List<Training> trainings=service.search(p.getPhrase());;
model.addAttribute("trainings", trainings);
//View Selection
return "displayTrainings";
}
}
home.jsp - This obtains search phrase from the user
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="f" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Search</title>
</head>
<body>
<div class="container">
<f:form method="POST" action="trainingSearch" modelAttribute="searchPhrase">
<div class="form-group">
<label for="phrase">Search Phrase</label>
<f:input type="text" id="phrase" path="phrase" class="form-control" />
</div>
<button type="submit" class="btn btn-primary">Search</button>
</f:form>
</div>
</body>
</html>
SearchPhrase Class - Used to store modelAttribute
public class SearchPhrase {
private String phrase;
public SearchPhrase() {
}
public SearchPhrase(String phrase) {
super();
this.phrase = phrase;
}
public String getPhrase() {
return phrase;
}
public void setPhrase(String phrase) {
this.phrase = phrase;
}
}
search functionality implementation
#Override
#Transactional
public List<Training> search(String phrase) {
Session session = sessionFactory.getCurrentSession();
Criteria crit = session.createCriteria(Training.class);
crit.add(Restrictions.eq("status","true"));
crit.add(Restrictions.ilike("techstack",phrase,MatchMode.ANYWHERE));
List<Training> results = crit.list();
session.close();
return results;
// return null;
}
Errors:
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'searchPhrase' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:177)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:198)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:163)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:122)
at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:459)
at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:356)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:86)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:83)
at org.apache.jsp.WEB_002dINF.views.home_jsp._jspx_meth_f_005finput_005f0(home_jsp.java:239)
at org.apache.jsp.WEB_002dINF.views.home_jsp._jspx_meth_f_005fform_005f0(home_jsp.java:190)
at org.apache.jsp.WEB_002dINF.views.home_jsp._jspService(home_jsp.java:140)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:998)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:890)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:875)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Aug 27, 2019 4:29:50 AM org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet [jsp] threw exception
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'searchPhrase' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:177)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:198)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:163)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:122)
at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:459)
at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:356)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:86)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:83)
at org.apache.jsp.WEB_002dINF.views.home_jsp._jspx_meth_f_005finput_005f0(home_jsp.java:239)
at org.apache.jsp.WEB_002dINF.views.home_jsp._jspx_meth_f_005fform_005f0(home_jsp.java:190)
at org.apache.jsp.WEB_002dINF.views.home_jsp._jspService(home_jsp.java:140)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:998)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:890)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:875)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
Aug 27, 2019 4:29:50 AM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [dispatcher] in context with path [/trainingbroadcast] threw exception [An exception occurred processing [/WEB-INF/views/home.jsp] at line [15]
12: <f:form method="POST" action="trainingSearch" modelAttribute="searchPhrase">
13: <div class="form-group">
14: <label for="phrase">Search Phrase</label>
15: <f:input type="text" id="phrase" path="phrase" class="form-control" />
16: </div>
17: <button type="submit" class="btn btn-primary">Search</button>
18: </f:form>
Stacktrace:] with root cause
java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'searchPhrase' available as request attribute
at org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:153)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:177)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:198)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:163)
at org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.writeDefaultAttributes(AbstractDataBoundFormElementTag.java:122)
at org.springframework.web.servlet.tags.form.AbstractHtmlElementTag.writeDefaultAttributes(AbstractHtmlElementTag.java:459)
at org.springframework.web.servlet.tags.form.InputTag.writeTagContent(InputTag.java:356)
at org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:86)
at org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:83)
at org.apache.jsp.WEB_002dINF.views.home_jsp._jspx_meth_f_005finput_005f0(home_jsp.java:239)
at org.apache.jsp.WEB_002dINF.views.home_jsp._jspx_meth_f_005fform_005f0(home_jsp.java:190)
at org.apache.jsp.WEB_002dINF.views.home_jsp._jspService(home_jsp.java:140)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:476)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:712)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:459)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:384)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:312)
at org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:170)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:998)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:890)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:875)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:678)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:853)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1587)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
On browser
org.apache.jasper.JasperException: An exception occurred processing [/WEB-INF/views/home.jsp] at line [15]
12: <f:form method="POST" action="trainingSearch" modelAttribute="searchPhrase">
13: <div class="form-group">
14: <label for="phrase">Search Phrase</label>
15: <f:input type="text" id="phrase" path="phrase" class="form-control" />
16: </div>
17: <button type="submit" class="btn btn-primary">Search</button>
18: </f:form>
Problem Solved.
The pronlem was that, modelAttribute("searchPhrase") is initialized after it has been accessed, thereby leading to the error.

MustacheException: No method or field with name 'Id' on line 15. Whitelabel Error Page

I'm using MySQL Ver 15.1 Distrib 10.1.38-MariaDB, for debian-linux-gnu (x86_64).
Open-JDK 1.8.0
Spring Boot 2.1.4 RELEASE
Accessing my application I got this stacktrace on my whitelable page:
This application has no explicit mapping for /error, so you are seeing
this as a fallback.
Mon May 27 16:12:06 AZOST 2019
There was an unexpected error (type=Internal Server Error, status=500).
No method or field with name 'id' on line 15
com.samskivert.mustache.MustacheException$Context: No method or field
with name 'id' on line 15
at com.samskivert.mustache.Template.checkForMissing(Template.java:326)
at com.samskivert.mustache.Template.getValue(Template.java:234)
at com.samskivert.mustache.Template.getValueOrDefault(Template.java:279)
at com.samskivert.mustache.Mustache$VariableSegment.execute(Mustache.java:802)
at com.samskivert.mustache.Mustache$BlockSegment.executeSegs(Mustache.java:845)
at com.samskivert.mustache.Mustache$SectionSegment.execute(Mustache.java:881)
at com.samskivert.mustache.Template.executeSegs(Template.java:157)
at com.samskivert.mustache.Template.execute(Template.java:134)
at org.springframework.boot.web.servlet.view.MustacheView.renderMergedTemplateModel(MustacheView.java:81)
at org.springframework.web.servlet.view.AbstractTemplateView.renderMergedOutputModel(AbstractTemplateView.java:178)
at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:316)
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1370)
at org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:1116)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1055)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:942)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1005)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:634)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:741)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:231)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:92)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:200)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:193)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:166)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:200)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:96)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:490)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:139)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:74)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:343)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:408)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:66)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:834)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1415)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:748)
This is my code:
main.mustache
<html>
<body>
<div>
<form method="POST">
<input type ="text" name="text" placeholder="Введите сообщение" />
<input type ="text" name="tag" placeholder="Тег"/>
<button type="submit">Добавить</button>
</form>
</div>
<div>Message list</div>
{{#messages}}
<div>
<b>{{id}}</b>
<span>{{text}}</span>
<i>{{tag}}</i>
</div>
{{/messages}}
This is my Controller:
GreetingController
package com.example.sweater;
import com.example.sweater.domain.Message;
import com.example.sweater.repos.MessageRepo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.Map;
#Controller
public class GreetingsController {
#Autowired
private MessageRepo messageRepo;
#RequestMapping("/greeting")
public String greeting(#RequestParam(name="name", required = false, defaultValue = "World") String name,
Map<String, Object> model)
{
model.put("name", name);
return "greeting";
}
#GetMapping
public String main(Map<String, Object> model){
Iterable<Message> messages = messageRepo.findAll();
model.put("messages", "messages");
return "main";
}
#PostMapping
public String add(#RequestParam String text, #RequestParam String tag, Map<String, Object> model){
Message message = new Message(text, tag);
messageRepo.save(message);
Iterable<Message> messages = messageRepo.findAll();
model.put("messages", messages);
return "main";
}
}
This is my project structure:
![ProjectStructure]: (https://lh3.googleusercontent.com/PKENYsmd29WxawAs-jMtrwBTBqDHNMoS3LWU_BTyDOjO7L5z8DrojsmB-pHfb03QE2Ce7Q3_xE4HrMk3PZax06Cd2b-NY42pB9e5DzCv-Uh6VlkbtebFb2W0HYq8u7WaG7WWU7uC7_7z5x8TXTXl65Wg-rMCes6HkQ8PTQ2_-QOMBW_I2yV8dXN2Xs2-vsHAWX5upPKw2oi3ZAtxOVvDKUm-znDD4czMIPAMKsDAfBXWWf5QbVpTysOEoE_rF7_7z9lWBf0ujZBYpllK5aXxsWB0OorsnnLb9XvmCMaGU-3xsOykLRFiq_LcYk5erFkEsBSkkobYT67ZPIPxrcnC3iGluBy5IYjDUrhwVpn-WPv76RsEID0qF0PYrAGO01M1Xb0QzhOJjx0wKsIKIDBRSEfxSRSLp-rGVW0rsDF_VIQeRXLs-Bvt45LznMXIBjCH_OLA3sg5p7RsgmiiRrjtsFhKmH-GOUds1GvrUTfpdpjlcySm_vpYK84WhyGfc64As45xB04w62mkD0LgZpw9pFcENbp8l9_MNhRlh0dLccB0Tku5H9h1-9H4FD3OzHYlw6SlsoNfYob_7BeZK3QXaTujtu1K7Hn-5zaxJ_oI4Ea_4P59BSmzAp6X_D6O0Rs9rZ8zPtSPNHiBzB6SP_vOuCfMuOAa8w=w340-h520-no)
I expected this code to display HTML code with empty fields waiting for me to fill in them, access the database and show all tuples which was typed into empty fields, but instead I ran into this stacktrace. What should i fix to make it work correctly?
From your stack trace it can be seen that you are passing messages to be iterated in the template :
There was an unexpected error (type=Internal Server Error, status=500).
No method or field with name 'id' on line 15
But the messages model being returned from the controller might be missing 'id' values . If we didn’t assign a value to a {{id}} on the Mustache’s page, the jmustache will throw the above error message.Can you please check if the data returned from the main method is returning correctly.Or mark the value as optional in the template.
If not check the following :
Ensure that you have configured mustache properly.Ensure that you have the following dependency added in pom :
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mustache</artifactId>
</dependency>
Also ensure that all your dynamic html content is kept in the directory :
src/main/resources/templates/
folder so that spring will take it up.

Categories

Resources