Spring MVC,Hibernate验证,表单请求未经过验证

时间:2017-10-24 14:05:55

标签: java spring hibernate spring-mvc

我需要一些关于spring mvc 4.3和hibernate验证的帮助。 我导入了“hibernate-validator-6.0.3.Final.jar”和“validation-api-2.0.0.Final.jar”(“hibernate-validator-6.0.3.Final.jar”的一部分)。

当我用数据(用户名和密码)填写表单时,用户名和密码未经验证,因此请求指向索引

User.java

package invoice.user;

import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class User {

    @NotNull(message = "required")
    @Size(min = 3, max = 50, message = "Username incorrect")
    private String username;

    @NotNull(message = "required")
    @Size(min = 3, max = 50, message = "Password incorrect")
    private String password;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    @Override
    public String toString() {
        return "User{" +
                "username='" + username + '\'' +
                ", password='" + password + '\'' +
                '}';
    }
}

UserController.java

package invoice.user;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import javax.validation.Valid;

@Controller
public class UserController {

    @RequestMapping("/")
    public String showLoginPage(@ModelAttribute("user") User user){
        return "user/user-login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String processLoginForm(@Valid @ModelAttribute("user") User user, BindingResult results){
        if(results.hasErrors()){
            return "user/user-login";
        }
            return "user/index";
    }
}

1 个答案:

答案 0 :(得分:0)

UserController 中, showLoginPage 将接受所有请求并返回user/user-login。删除此项然后检查

@Controller
public class UserController {

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String processLoginForm(@Valid @ModelAttribute("user") User user, BindingResult results){
        if(results.hasErrors()){
            return "user/user-login";
        }
            return "user/index";
    }
}