首页 > 解决方案 > 在身份验证之前访问枚举

问题描述

我有一个帐户申请表(在身份验证之前),它应该显示国家/地区列表(ISO)我在枚举中有这个列表,但我无法访问它,因为我既没有被授权也没有“提供”这个枚举的控制器

在我看来 :

<div class="form-group" style="padding-bottom: 10px;  display: flex;justify-content: 
left;margin-bottom:0;">
            <label style=" color:white;font-size:12px;margin-right: 10px;" 
for="countryInput"
                   th:text="#{modif.country}"></label>
            <select th:name="country"
                    type="text" th:field="*{country}" class="form-control" 
id="countryInput"
                    th:errorclass="invalid"
                    th:placeholder="#{modif.country}"
                    style="width: 200px;font-size:12px;margin-bottom:0;">
                <option th:each="country :${T(fr.model.enumeration.Country).values()}"
                        th:value="${country}" th:text="${country}"></option>
            </select>
            <div th:errors="*{country}" style="color: red">
                Error
            </div>
        </div>

枚举:

package fr.model.enumeration;

public enum Country {
France,
Afghanistan, Albania, Algeria, AmericanSamoa,
Andorra, Angola, Anguilla, Antarctica, ...
}

我收到此错误:bean name 'country' 的 BindingResult 和普通目标对象都不能用作请求属性

这对我来说完全有意义,但我希望能够使用此列表而无需经过身份验证

谢谢你的关心

标签: javaspringspring-security

解决方案


此问题与身份验证/授权无关。错误“Bean name 'country' 的 BindingResult 和普通目标对象都不能用作请求属性”表明这是 Spring 绑定的问题。我认为问题不在于枚举,而在于选择:

 <select th:name="country" type="text" th:field="*{country}" class="form-control" id="countryInput" th:errorclass="invalid" th:placeholder="#{modif.country}" style="width: 200px;font-size:12px;margin-bottom:0;">

如何检查问题是否出在选择中而不是枚举中?删除/注释 HTML 选项元素,您应该会看到完全相同的错误。如果是这种情况,我的解决方案是:

您正在使用th:field="*{country}",它与th:object一起使用。

如果您有一个指向该视图的控制器并且想要使用th:object,那么您需要在 HTML 表单中包含 th:object 并在控制器模型中添加您想要使用的对象。

如果您没有控制器或其他东西来注入对象,请从您的选择中删除th:field以及与对象绑定相关的所有内容。如果是这种情况,您可能甚至不需要th:field。在这种情况下,你会有这样的事情:

<div class="form-group" style="padding-bottom: 10px;  display: flex;justify-content: left;margin-bottom:0;">
<label style="color:white;font-size:12px;margin-right: 10px;" for="countryInput" th:text="#{modif.country}"></label>
<select class="form-control" id="countryInput" style="width: 200px;font-size:12px;margin-bottom:0;">
    <option th:each="country :${T(fr.model.enumeration.Country).values()}" th:value="${country}" th:text="${country}"></option>
</select>
</div>

在最后一个场景中,您将没有 Spring 绑定。您需要定义是否要使用对象绑定。如果您不使用对象绑定,您将无法使用诸如 th:errors 或 th:errorclass 之类的东西,但是这个目标取决于您和您想要实现的目标。如果您确实想使用对象绑定,则应该使用控制器类。


推荐阅读