简体   繁体   English

Spring验证注释不显示错误消息

[英]Spring validation annotations not displaying error messages

Hi This is my first question 嗨,这是我的第一个问题

I am new to SPRING.Currently , i am doing spring validations using annotations 我是SPRING的新手。目前,我正在使用批注进行春季验证

This is my DAO class 这是我的DAO班

public class User {

    @NotBlank(message="Username cannot be blank.")
    @Size(min=8, max=15, message="Username must be between 8 and 15 characters long.")
    @Pattern(regexp="^\\w{8,}$", message="Username can only consist of numbers, letters and the underscore character.")
    private String username;

    @NotBlank(message="Password cannot be blank.")
    @Pattern(regexp="^\\S+$", message="Password cannot contain spaces.")
    @Size(min=8, max=15, message="Password must be between 8 and 15 characters long.")
    private String password;

    @ValidEmail(message="This does not appear to be a valid  address.")
    private String email;

   INCLUDES GETTER AND SETTERS
}

In my Controller , I am using this code 在我的控制器中,我正在使用此代码

@RequestMapping("/newaccount")
    public String showNewAccount(Model model) {

        model.addAttribute("User", new User());
        return "newaccount";
    }


@RequestMapping(value="/createaccount", method=RequestMethod.POST)
    public String createAccount(@Valid User user, BindingResult result) {

        if(result.hasErrors()) {
            return "newaccount";
        }

        user.setAuthority("user");
        user.setEnabled(true);

        usersService.create(user);

        return "accountcreated";
    }
}

This is my newaccount.jsp 这是我的newaccount.jsp

<%-- <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%> --%>
<%@ page language="java" contentType="text/html; charset=US-ASCII"
    pageEncoding="US-ASCII"%>
<%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">


<html>
<head>
<link href="${pageContext.request.contextPath}/static/style.css"
    rel="stylesheet" type="text/css">

<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Create Account</title>

</head>
<body>
    <sf:form action="${pageContext.request.contextPath}/createAcoount"
        method="post" commandName="User">
        <table class="formtable">
            <tr>
                <td class="label">User Name</td>
                <td><sf:input class="control" name="username" path="username"
                        type="text"></sf:input><br></br>
                <sf:errors path="username"></sf:errors></td>
            </tr>
            <tr>
                <td class="label">Email</td>
                <td><sf:input class="control" name="email" path="email"
                        type="text"></sf:input><br></br>
                <sf:errors path="email" cssClass="error"></sf:errors></td>
            </tr>
            <tr>
                <td class="label">Password</td>
                <td><sf:input class="control" name="password" path="password"
                        type="text"></sf:input><br></br>
                <sf:errors path="password" cssClass="error"></sf:errors></td>
            </tr>
            <tr>
            <td class="label"></td>
            <td><input type="submit" value="Submit"></td>
            </tr>
        </table>

    </sf:form>
</body>
</html>

When i am trying to create an account , i am expecting that it shows me error messages as per validations Like : Username cannot be blank. 当我尝试创建一个帐户时,我希望它根据验证之类的错误消息向我显示:用户名不能为空。

However , its throwing an exception 但是,它引发了异常

java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'User' available as request attribute
    org.springframework.web.servlet.support.BindStatus.<init>(BindStatus.java:144)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getBindStatus(AbstractDataBoundFormElementTag.java:168)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getPropertyPath(AbstractDataBoundFormElementTag.java:188)
    org.springframework.web.servlet.tags.form.AbstractDataBoundFormElementTag.getName(AbstractDataBoundFormElementTag.java:154)

Thanks in advance 提前致谢

You've used the key "user" in your handler method 您已在处理程序方法中使用键"user"

model.addAttribute("user", new User());

but "User" in your JSP 但是您的JSP中的"User"

method="post" commandName="User">

The two should match. 两者应该匹配。 You'll also have to modify 您还必须修改

public String createAccount(@Valid User user, BindingResult result) {

to

public String createAccount(@Valid @ModelAttribute("whatever you chose") User user, BindingResult result) {

since the method forwards to the same view, but doesn't explicitly set the name of the model attribute. 因为该方法转发到相同的视图,但未显式设置model属性的名称。 By default, it will use the name of the type with the first letter in lowercase, ie user in this case. 默认情况下,它将使用类型名,首字母小写,即在这种情况下为user

Looks like spring forms can't find anything in the model returned from the Controller with the attribute name of "User". 看起来Spring表单在从Controller返回的属性名称为“ User”的模型中找不到任何内容。

What you want is probably to prepend @ModelAttribute to the User bean parameter in your controller method. 您可能想要在控制器方法中将@ModelAttribute附加到User bean参数。 That way Spring will automatically add it to the implicit model (together with the BindingResult). 这样,Spring将自动将其添加到隐式模型中(与BindingResult一起)。

Make sure to check your bean naming. 确保检查您的bean命名。 I'd expect the bean name to be inferred by spring if you use the modelAttribute annotation to something like "user" (note the lowercase start). 如果您将modelAttribute批注用于“ user”之类的话,我希望bean的名称能够在spring之前被推断出来(注意小写的开头)。

What you want in the end is something like: 您最终想要的是这样的:

public String createAccount(
        @Valid @ModelAttribute User user, 
        BindingResult result) { 
    // ....
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM