在身份验证之前访问枚举

Access to an enum before authentication

我有一个帐户申请表(在身份验证之前),它应该显示国家列表 (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 名称 'country' 的 BindingResult 和普通目标对象都不能用作请求属性

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

感谢您的关心

此问题与authentication/authorization无关。错误“Bean 名称 'country' 的 BindingResult 和普通目标对象均不可用作为请求属性”表明这是 Spring 绑定的问题。我认为问题不在枚举中,而在 select:

 <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;">

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

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

如果您有一个指向此视图的控制器并想使用 th:object,那么您需要在 [=46] 中包含 th:object =] 形成并添加您要在控制器模型中使用的对象。

如果您没有控制器或其他东西来注入对象,请从您的 select 中删除 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 这样的东西,但这个决定取决于你和你想要实现的目标。如果你确实想使用对象绑定,你应该使用控制器 class.