表格验证未执行,弹簧启动

时间:2017-01-19 10:43:04

标签: spring validation spring-boot spring-security

也许我错过了一些小而愚蠢的东西。但是我有一个带有6个复选框的表单,您可以同时检查这些复选框中的最多4个,这是在验证器的validate方法内。我的验证器类如下:

@Component
public class GraficiUserFormValidator implements Validator {

    @Override
    public boolean supports(Class<?> arg0) {
        return arg0.equals(GraficiUserForm.class);
    }

    @Override
    public void validate(Object arg0, Errors arg1) {
        GraficiUserForm form = (GraficiUserForm) arg0;
        validateCheckBoxes(arg1, form);

    }

    private void validateCheckBoxes(Errors arg1, GraficiUserForm form) {
        if ((form.getG1().equals("on") && form.getG2().equals("on") && form.getG3().equals("on") && form.getG4().equals("on") &&
                form.getG5().equals("on") && form.getG6().equals("on")) ||(form.getG1().equals("on") && form.getG2().equals("on") && form.getG3().equals("on") && form.getG4().equals("on") &&
                form.getG5().equals("on"))||(form.getG1().equals("on") && form.getG2().equals("on") && form.getG3().equals("on") && form.getG4().equals("on") &&
                form.getG6().equals("on"))||(form.getG1().equals("on") && form.getG2().equals("on") && form.getG3().equals("on") && form.getG5().equals("on") &&
                form.getG6().equals("on"))||(form.getG1().equals("on") && form.getG2().equals("on") && form.getG4().equals("on") && form.getG5().equals("on") &&
                form.getG6().equals("on"))||(form.getG1().equals("on") && form.getG3().equals("on") && form.getG4().equals("on") && form.getG5().equals("on") &&
                form.getG6().equals("on"))||(form.getG2().equals("on") && form.getG3().equals("on") && form.getG4().equals("on") && form.getG5().equals("on") &&
                form.getG6().equals("on"))
                ){
            arg1.reject("grafici.tooMany", "Troppi grafici selezionati, si possono selezionare solo 4 grafici");
        }

    }

}

然后我将验证器自动连接到Controller:

@Controller
public class UsersController {

    private static final Logger LOGGER = LoggerFactory.getLogger(UsersController.class);
    private final UserService userService;
    private final SitoService sitoService;
    private final ClusterService clusterService;
    private final GraficiUserFormValidator graficiUserFormValidator;

    @Autowired
    public UsersController(UserService userService, ClusterService clusterService, SitoService sitoService, GraficiUserFormValidator graficiUserFormValidator) {
        this.userService = userService;
        this.sitoService = sitoService;
        this.clusterService = clusterService;
        this.graficiUserFormValidator = graficiUserFormValidator;
    }

    @InitBinder("form")
    public void initBinder(WebDataBinder binder) {
        binder.addValidators(graficiUserFormValidator);
    }

我构建了在同一个控制器中处理表单的方法:

@PreAuthorize("hasAuthority('ADMIN') or hasAuthority('CLUSTERADMIN') or hasAuthority('SITEADMIN')")
    @RequestMapping(value = "/update/settings", method = RequestMethod.POST)
    public String updateSettingsGraphs(@Valid GraficiUserForm form, HttpSession session, HttpServletRequest request, BindingResult result, 
            Model model, Long id){
        SecurityContextHolderAwareRequestWrapper wrapper = new SecurityContextHolderAwareRequestWrapper(request, null);

        if (result.hasErrors()) {
            if (wrapper.isUserInRole("ADMIN")) {
                result.reject("graphs.tooMany", "Puoi selezionare solo quattro grafici alla volta");
                Collection<User> users = userService.getAllUsers();
                model.addAttribute("users", users);


                for (User user : users) {
                    model.addAttribute("form"+user.getId().toString(), new GraficiUserForm());
                }

                return "users";
            }

            else if (wrapper.isUserInRole("CLUSTERADMIN")) {
                result.reject("graphs.tooMany", "Puoi selezionare solo quattro grafici alla volta");
                Collection<User> users = clusterService.getAllByCluster(id);
                model.addAttribute("users", users);


                for (User user : users) {
                    model.addAttribute("form"+user.getId().toString(), new GraficiUserForm());
                }
                return "users-cluster";
            }

            else {
                result.reject("graphs.tooMany", "Puoi selezionare solo quattro grafici alla volta");
                Collection<User> users = sitoService.getAllBySite(id);
                model.addAttribute("users", users);


                for (User user : users) {
                    model.addAttribute("form"+user.getId().toString(), new GraficiUserForm());
                }
                return "users-site";
            }
        }
        User user = userService.getUserById(form.getUserid());
        if("on".equals(form.getG1())){
            user.setG1("S");
        } else {
            user.setG1("N");
        }
        if("on".equals(form.getG2())){
            user.setG2("S");
        } else {
            user.setG2("N");
        }
        if("on".equals(form.getG3())){
            user.setG3("S");
        } else {
            user.setG3("N");
        }
        if("on".equals(form.getG4())){
            user.setG4("S");
        } else {
            user.setG4("N");
        }
        if("on".equals(form.getG5())){
            user.setG5("S");
        } else {
            user.setG5("N");
        }
        if("on".equals(form.getG6())){
            user.setG6("S");
        } else {
            user.setG6("N");
        }
        user = userService.save(user);
        if (wrapper.isUserInRole("ADMIN")) {
            return "redirect:/users";
        }

        else if (wrapper.isUserInRole("CLUSTERADMIN")) {
            return "redirect:/users-cluster";
        }

        else {
            return "redirect:/users-site";
        }

    }

}

我的网页由freemarker构建,如下所示:

<#-- @ftlvariable name="users" type="java.util.List<it.energyway.application.domain.User>" -->
<#-- @ftlvariable name="_csrf" type="org.springframework.security.web.csrf.CsrfToken" -->
<#list users as user>
<#-- @ftlvariable name="form${user.id}" type="it.energyway.application.domain.GraficiUserForm" -->
</#list>
<#import "/spring.ftl" as spring>
<!DOCTYPE html>
<html lang="it">
<head>
    <meta charset="utf-8">
    <title>List of Users</title>
</head>
<body>

<nav role="navigation">
    <ul>
        <li><a href="/">Dashboard</a></li>
        <li><a href="/user/create">Create a new user</a></li>
        <li>Amministrazione
            <ul>
                <li><a href="/users">Gestione  Utenti e Permessi</a></li>
            </ul>
        </li>
    </ul>
</nav>

<h1>Utenti</h1>

<table>
    <thead>
    <tr>
        <th>E-mail</th>
        <th>Role</th>
        <th>Grafico 1</th>
        <th>Grafico 2</th>
        <th>Grafico 3</th>
        <th>Grafico 4</th>
        <th>Grafico 5</th>
        <th>Grafico 6</th>
        <th>Cambio</th>
    </tr>
    </thead>
    <tbody>
    <#list users as user>
    <form role="form${user.id}" name="form${user.id}" action="/update/settings" method="post">
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>
    <input type="hidden" name="userid" id="userid" value="${user.id}"/>
    <tr>
        <td><a href="/user/${user.id}">${user.email}</a></td>
        <td>${user.role}</td>
        <td><input class="graphs" type="checkbox" name="g1" <#if (user.g1 == "S")>checked=true<#else></#if></td>
        <td><input class="graphs" type="checkbox" name="g2" <#if (user.g2 == "S")>checked=true<#else></#if></td>
        <td><input class="graphs" type="checkbox" name="g3" <#if (user.g3 == "S")>checked=true<#else></#if></td>
        <td><input class="graphs" type="checkbox" name="g4" <#if (user.g4 == "S")>checked=true<#else></#if></td>
        <td><input class="graphs" type="checkbox" name="g5" <#if (user.g5 == "S")>checked=true<#else></#if></td>
        <td><input class="graphs" type="checkbox" name="g6" <#if (user.g6 == "S")>checked=true<#else></#if></td>
        <td><button type="submit">Save</button></td>
    </tr>
    </form>
    </#list>
    </tbody>
</table>
<#list users as user>
    <@spring.bind "form${user.id}" />
</#list>
<#if (spring.status.error)??>
<ul>
    <#list spring.status.errorMessages as error>
        <li>${error}</li>
    </#list>
</ul><#else>
</#if>
</body>
</html>

当我选择4个以上的复选框时,它不会在输出中抛出任何错误... 任何人都知道为什么?

1 个答案:

答案 0 :(得分:1)

尝试在控制器方法中首先添加它:

ValidationUtils.invokeValidator(userFormValidator, form, result);

@Valid注释将使用JSR-303 / JSR-349(Bean Validation API)约束和验证器触发验证,但上面指定的验证器是Spring验证器。

更新 M。 Deinum 在评论中指出,@Valid也应该与Spring验证器一起使用,如果BindingResult跟随@Valid的参数并且您使用{注册验证器{1}}。好吧,我在使用Spring验证器时已经成功使用了上述方法,我想我没有找到将JSR-303/349注释与Spring验证器混合的逻辑。