Java 带有注释的 Spring MVC 3 验证 - 不显示表单:错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9673610/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-16 05:59:25  来源:igfitidea点击:

Spring MVC 3 validation with annotations - not showing form:errors

javaspringspring-mvc

提问by AdrianS

I've been stuck with this about one hour, this is not the first time i am doing this but I cant figure it out.

我已经坚持了大约一个小时,这不是我第一次这样做,但我无法弄清楚。

It should show me the form errors, instead it throws this exception.

它应该向我显示表单错误,而不是抛出此异常。

LE: i managed to solve the exception in the meantime, but i still cant see the errors. they are not rendered

LE:同时我设法解决了异常,但我仍然看不到错误。他们没有被渲染

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 errors Field error in object 'category' on field 'name': rejected value [jk]; codes [Range.category.name,Range.name,Range.java.lang.String,Range]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [category.name,name]; arguments []; default message [name],25,3]; default message [gfhghj] org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789) javax.servlet.http.HttpServlet.service(HttpServlet.java:637) javax.servlet.http.HttpServlet.service(HttpServlet.java:717) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:311) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.invoke(FilterSecurityInterceptor.java:116) org.springframework.security.web.access.intercept.FilterSecurityInterceptor.doFilter(FilterSecurityInterceptor.java:83) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) org.springframework.security.web.access.ExceptionTranslationFilter.doFilter(ExceptionTranslationFilter.java:113) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) org.springframework.security.web.session.SessionManagementFilter.doFilter(SessionManagementFilter.java:101) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) org.springframework.security.web.authentication.AnonymousAuthenticationFilter.doFilter(AnonymousAuthenticationFilter.java:113) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter.doFilter(SecurityContextHolderAwareRequestFilter.java:54) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) org.springframework.security.web.savedrequest.RequestCacheAwareFilter.doFilter(RequestCacheAwareFilter.java:45) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) org.springframework.security.web.authentication.www.BasicAuthenticationFilter.doFilter(BasicAuthenticationFilter.java:150) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:182) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:105) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:87) org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:323) org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:173) org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:346) org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:259) org.springframework.web.filter.HiddenHttpMethodFilter.doFilterInternal(HiddenHttpMethodFilter.java:77) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76) org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:88) org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:76)

org.springframework.web.util.NestedServletException:请求处理失败;嵌套异常是 org.springframework.validation.BindException: org.springframework.validation.BeanPropertyBindingResult: 1 个错误字段“名称”上的对象“类别”中的字段错误:拒绝值 [jk];代码 [Range.category.name,Range.name,Range.java.lang.String,Range]; 参数 [org.springframework.context.support.DefaultMessageSourceResolvable: 代码 [category.name,name]; 参数 []; 默认消息 [名称],25,3]; 默认消息 [gfhghj] org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:894) org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:789) javax.servlet.http.HttpServlet.service (HttpServlet.java:637) javax.servlet.http.HttpServlet.service(HttpServlet.

@Controller
@RequestMapping("/category")
public class CategoryController {

@Autowired
StockGateway stockGateway;

@RequestMapping(value = "add", method = RequestMethod.POST)
public String addCategory(@Valid @ModelAttribute("category") CategoryAdd category, ModelMap model,
        BindingResult binding) {

    if (binding.hasErrors()) {
        return "category.add";
    }
    CategoryDTO dto = Converter.toCategory(category);
    try {
        stockGateway.createCategory(dto);
    } catch (StockGatewayException e) {
        e.printStackTrace();
    }
    return "redirect:/category/add";

}

@RequestMapping(value = "add", method = RequestMethod.GET)
public String initView(ModelMap model) {
    model.put("category", new CategoryAdd());
    return "category.add";
}

}

}

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<div xmlns:jsp="http://java.sun.com/JSP/Page" 
xmlns:spring="http://www.springframework.org/tags"
 xmlns:c="http://java.sun.com/jsp/jstl/core" 
 xmlns:security = "http://www.springframework.org/security/tags"
 xmlns:util="urn:jsptagdir:/WEB-INF/tags/util"
 xmlns:form="http://www.springframework.org/tags/form"
 version="2.0">

<security:authorize access="hasRole('ROLE_STOCK')" var="isStock">
    <form:form modelAttribute="category"  method="POST" action="add"  >
            <table>
            <tr>
                <td>Name  :</td> <td> <form:input path="name" /></td>
            </tr>
            <tr>
                <td></td> <td> <form:errors path="name" cssClass="error" /></td>
            </tr>
            </table>
            <form:button>Add</form:button>
    </form:form>
</security:authorize>

public class CategoryAdd {

@Range(min= 3 , max = 25, message="gfhghj")
private String name;



public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

采纳答案by Felby

There seems to be a dependency on the order in which the parameters must be listed in the mapped controller method.
For example:

参数在映射控制器方法中必须列出的顺序似乎存在依赖性。
例如:

public String addCategory(@Valid CategoryAdd category,BindingResult result, 
Map map)

Will work, whereas:

将工作,而:

public String addCategory(@Valid CategoryAdd category, Map map, 
BindingResult result)

Will not. I don't full understand why this is, especially as it compiles without any issues.

将不会。我不完全明白为什么会这样,特别是因为它编译没有任何问题。

回答by AdrianS

So complete solution is:

所以完整的解决方案是:

public String addCategory(@Valid CategoryAdd category,BindingResult result,
        Map map
        ) {

    if (result.hasErrors()) {
        map.put("categoryAdd", (CategoryAdd)result.getTarget());
        return "category.add";
    }
    CategoryDTO dto = Converter.toCategory(category);
    try {
        stockGateway.createCategory(dto);
    } catch (StockGatewayException e) {
        e.printStackTrace();
    }
    return "redirect:/category/add";

Notice i changed parameter ModelMap with Map, and if the result has errors i put back the model from the result.

请注意,我使用 Map 更改了参数 ModelMap,如果结果有错误,我会从结果中放回模型。

Now the WTF: The BindingResult has a field objectName, which has the value the name of the class. You have to set the modelAttribute/commandName to that. To be the same as objectName in BindingResult, or else it wont render the errors. So to match it:

现在 WTF:BindingResult 有一个字段 objectName,它的值是类的名称。您必须将 modelAttribute/commandName 设置为该名称。与 BindingResult 中的 objectName 相同,否则不会呈现错误。所以要匹配它:

    <form:form modelAttribute="categoryAdd" commandName="categoryAdd"  method="POST" action="add"  >

Does anyone know how can we change the objectName from the BindingResult? By default it will take the name of the class.

有谁知道我们如何从 BindingResult 更改 objectName?默认情况下,它将采用类的名称。