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

时间:2014-07-10 19:42:02

标签: java spring spring-mvc

嗨这是我的第一个问题

我是SPRING的新手。目前,我正在使用注释进行弹簧验证

这是我的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
}

在我的控制器中,我正在使用此代码

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

这是我的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>

当我尝试创建帐户时,我希望它根据验证显示错误消息,例如:用户名不能为空。

然而,它抛出异常

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)

提前致谢

2 个答案:

答案 0 :(得分:1)

您已在处理程序方法

中使用了密钥"user"
model.addAttribute("user", new User());

但JSP中的"User"

method="post" commandName="User">

两者应该匹配。您还必须修改

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

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

因为该方法转发到同一视图,但没有明确设置模型属性的名称。默认情况下,它将使用第一个字母小写的类型名称,在这种情况下为user

答案 1 :(得分:0)

看起来弹簧形式无法在Controller返回的模型中找到任何属性名称为&#34; User&#34;的内容。

您想要的是将@ModelAttribute预先添加到控制器方法中的User bean参数中。这样Spring就会自动将它添加到隐式模型中(与BindingResult一起)。

确保检查您的bean命名。如果你将modelAttribute注释用于&#34; user&#34;那么我希望spring命名bean名称。 (注意小写开头)。

最终你想要的是:

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