我尝试使用spring boot 2.2和thymeleaf进行表单验证,如文档示例所示(https://spring.io/guides/gs/validating-form-input/)但当提交错误的值时,我有一个白色标签错误页面,而我应该在表单视图中绑定这些错误。如何解决这个问题?
我的控制器操作代码:
@Controller
public class TodoController {
@RequestMapping(value = "/todo/create", method = RequestMethod.GET)
public String tplTodoCreate(Model model) {
TodoForm todoForm = new TodoForm();
return "v-todo-create";
}
@RequestMapping(value = "/todo/create", method = RequestMethod.POST)
public String tplTodoCreatePost(@ModelAttribute(name="formTodo") @Valid TodoForm todoForm, RedirectAttributes redirAttrs, BindingResult result) {
if(result.hasErrors()) {
return "v-todo-create";
}
todoRepository.save(todoForm);
redirAttrs.addFlashAttribute("msgNotices", "Todo task created successfuly.");
return "redirect:/todos";
}
}
和视图:
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout" layout:decorator="tpl-default">
<head>
<title th:text="#{ctl-todo.create.meta.title}">Create New Todo</title>
<link th:href="@{/css/todo/create.css}" rel="stylesheet" />
</head>
<body>
<div id="wrapper" layout:fragment="content">
<h2 class="page-header" th:text="#{ctl-todo.create.00001strid}">Add Todo</h2>
<form name="todo" method="post" action="#" th:action="@{/todo/create}" th:object="${todoForm}" class="my-form-class">
<div id="form">
<div>
<label for="form_name" class="required" th:text="#{ctl-todo.create.00002strid}">Name</label>
<p th:if="${#fields.hasErrors('name')}" th:errors="*{name}"></p>
<input type="text" th:field="*{name}" id="form_name" name="name" min="1" max="30" required="required" class="form-control" style="margin-bottom:15px;" />
</div>
<div>
<button type="submit" id="form_save" name="save" class="btn btn-primary" style="margin-bottom:15px;" th:text="#{ctl-todo.create.00013strid}">Create Todo</button>
</div>
</div>
</form>
<hr />
<a class="btn btn-default" href="/todos"><span class="glyphicon glyphicon-floppy-remove"></span> <span th:text="#{ctl-todo.create.00014strid}">Back to todos list</span></a>
</div>
</body>
</html>
堆栈跟踪是:
2020-01-06 21:47:30.780 WARN 12140 --- [nio-8080-exec-8] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'formTodo' on field 'name': rejected value [a]; codes [Size.formTodo.name,Size.name,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [formTodo.name,name]; arguments []; default message [name],30,2]; default message [size must be between 2 and 30]]
Whiteblabel错误页面为:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Tue Jan 07 10:08:07 GMT+01:00 2020
There was an unexpected error (type=Bad Request, status=400).
Validation failed for object='formTodo'. Error count: 1
org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'formTodo' on field 'name': rejected value [a]; codes [Size.formTodo.name,Size.name,Size.java.lang.String,Size]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [formTodo.name,name]; arguments []; default message [name],30,2]; default message [size must be between 2 and 30]
at org.springframework.web.method.annotation.ModelAttributeMethodProcessor.resolveArgument(ModelAttributeMethodProcessor.java:164)
at org.springframework.web.method.support.HandlerMethodArgumentResolverComposite.resolveArgument(HandlerMethodArgumentResolverComposite.java:121)
at org.springframework.web.method.support.InvocableHandlerMethod.getMethodArgumentValues(InvocableHandlerMethod.java:167)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:134)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:888)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:793)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1040)
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:660)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
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.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:526)
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:367)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:860)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1591)
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:830)
典型情况下,name字段的min属性等于1,但TodoForm实体的size约束为min=2且max=30。当我测试仅提交一个字符的值时,检测到好错误,但返回错误为白色标签页面,而不是带有错误的视图。
编辑:问题已解决。这是由参数进入tplTodoCreatePost()方法和@modeltribute(name=“formTodo”)的顺序引起的。方法签名被修改为公共字符串tplTodoCreatePost(@Valid-TodoForm-TodoForm,BindingResult,RedirectAttributes-redirAttrs)
作为参考,我已经删除了@modeldattribute(name=“formTodo”),因为使用它时不会显示错误。
@RequestMapping(value = "/todo/create", method = RequestMethod.POST)
public String tplTodoCreatePost(@Valid TodoForm todoForm, BindingResult result, RedirectAttributes redirAttrs) {
if(result.hasErrors()) {
return "v-todo-create";
}
todoRepository.save(todoForm);
redirAttrs.addFlashAttribute("msgNotices", "Todo task created successfuly.");
return "redirect:/todos";
}
我会尝试向模型添加一个参数。但是没有堆栈跟踪很难排除故障。你能把它附加到你的帖子上吗?控制器的其余部分,带有GET方法映射在这里可能会有所帮助。
编辑:
我认为问题在于tplTodoCreatePost方法的参数顺序。请尝试将BindingResult移动到Model之前,如下所示:
public String tplTodoCreatePost(@Valid TodoForm todoForm, BindingResult result, @ModelAttribute(name="formTodo"), RedirectAttributes redirAttrs, ) {
// method body
}
所以我在我的Rails应用程序中使用简单表单,我需要去掉简单表单附带的每个输入上的标签。 我尝试了:<%=f.input:email,class:“login-field”,label:“”%>将标签留空,但这不起作用。 谢谢你。
对于错误的响应,是否可能在响应中返回验证注释消息?我认为这是可能的,但我注意到我们的项目没有给出详细的不良请求信息。 如果请求缺少IDField,我希望返回“IDField is required”。我用的是泽西2.0。我看到的回应是...
我不知道如何解决这个问题 spring端:role.java 因此,如果我现在尝试inline=“javascript”: 当我运行它时,我得到这样的响应: 白标签错误页
当我运行spring boot MVC应用程序时,得到以下白标签错误页面。 白标签错误页 此应用程序没有/error的显式映射,因此您将其视为一种后退。 Wed Apr 13 15:45:59 IST 2016出现意外错误(Type=内部服务器错误,Status=500)。循环视图路径[home]:将再次发送回当前处理程序URL[/rewards/web/home]。检查您的ViewResolve
我在学春靴。我创建了这个超级简单的项目,但当我试图返回带有@GetMapping注释的HTML页面时,我不断得到一个404白标签错误页面。 这是我唯一的控制器: 这是Spring应用程序: 这是目录 这是你好。html页面: 你好。html页面在resources/templates文件夹中,我不知道发生了什么。我从另一个工作项目中复制了这个结构完全相同的部分,但我的部分只是给了我这个白标签错误页
当我在本地执行“java-jar target/loginmodel-0.0.1-snapshot.jar”并尝试在浏览器上看到它时,它工作得很好,没有任何错误。我只是在尝试在docker容器上运行应用程序时才得到错误。到底错在哪里?