简体   繁体   中英

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

This is my DAO class

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

<%-- <%@ 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

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

but "User" in your JSP

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. By default, it will use the name of the type with the first letter in lowercase, ie user in this case.

Looks like spring forms can't find anything in the model returned from the Controller with the attribute name of "User".

What you want is probably to prepend @ModelAttribute to the User bean parameter in your controller method. That way Spring will automatically add it to the implicit model (together with the BindingResult).

Make sure to check your bean naming. 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).

What you want in the end is something like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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