Displaying validation Errors in form with Spring M

2019-07-27 07:10发布

问题:

I've searched through several tutorials and answers to this forum to try to solve my problem: I want to show the validation errors from my bean in my form using spring MVC.

No matter what I try, I can't get it to work. Im not using redirections, my binding results are directly after the model class and so on.

Here's what I have so far:

Login Class:

public class LoginUser implements Serializable {

    @NotNull
    @Column(name="username", unique=true)
    @Size(min=5)
    private String username;

    @NotNull
    @Size(min=5)
    private String password;

Login Controller:

@Transactional
@Controller
public class LoginController {

    @Autowired
    UserDao dao;

    @RequestMapping(value = "enter", method = RequestMethod.POST)
    public String doLogin(@ModelAttribute("user") @Valid LoginUser user, BindingResult result, HttpSession session) {
        if (result.hasErrors()) {
            return "login/loginForm";
        } else {
            if (dao.authenticate(user)) {
                session.setAttribute("userLoggedIn", user.getUsername());
                return "forward:index";
            } else {
                return "redirect:login";
            }
        }

    }

Login Form:

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<script type="text/javascript" src="resources/js/bootstrap.js"></script>
<script type="text/javascript" src="resources/js/jquery-3.1.0.min.js"></script>
<link rel="stylesheet" href="resources/css/bootstrap.css">
<title><spring:message code="title.login" /></title>
</head>
<body>
    <spring:message code="login.message.login" />
    <form:form action="enter" commandName="loginForm" method="POST">
        <spring:message code="username.login" />
        <input type="text" name="username" id="username" /><br />
        <form:errors path="username" />
        <spring:message code="password.login" />
        <input type="password" name="password" id="password" /><br /> <input
            type="submit" value="<spring:message code='button.login'/>"><br />
        <spring:message code="does.not.have.account.login" />
        <a href="register"><spring:message code="register.link.login" /></a>
    </form:form>
</body>
</html>

Ohh, I forgot to add - I have a messages.properties configured (working fine, tested) and the messages are comming from there. Here is the line related to the form:

messages_en.Properties

NotEmpty.loginForm.username= Please fill the username field

By the way, it may be worth to note that my view is mounted trough a composite view (made of JSP includes of header, mainpage and footer) that overrides the customary viewloading in Sping-MVC.

回答1:

You are using RedirectAttributes but you are not redirecting user any where. Try to use "redirect:/<register_path>" or just add Model model to method params and use model.addAtribute("someName", result);



回答2:

Try below code..

<form:form action="enter" commandName="loginForm" method="POST">

commandName is loginForm so @ModelAttribute("loginForm").

@RequestMapping(value = "enter", method = RequestMethod.POST)
    public String doLogin( @Valid  @ModelAttribute("loginForm") LoginUser user, BindingResult result, Map<String, Object> model,  HttpSession session) {
        if (result.hasErrors()) {
            return "login/loginForm";
        } else {
            if (dao.authenticate(user)) {
                session.setAttribute("userLoggedIn", user.getUsername());
                return "forward:index";
            } else {
                return "redirect:login";
            }
        }
    }

UPDATE :

You are using NotEmpty.loginForm.username= Please fill the username field which is wrong,It should be NotNull.loginForm.username= Please fill the username field

And also

@NotNull will not validate for empty string..Request from the front end will be "" which is not null.So use @NotEmpty instead.

If you still want to use @NotNull add InitBinder in your controller as shown below

@InitBinder
public void initBinder(WebDataBinder binder) {
    binder.registerCustomEditor(String.class, new StringTrimmerEditor(true));
}

Then it will validate for empty string.

That is the reason you are getting size error directly and since you have not mentioned any message for that no message is displaying.