gpt4 book ai didi

java - 如何在 Spring mvc 中访问枚举值

转载 作者:行者123 更新时间:2023-12-02 07:38:36 25 4
gpt4 key购买 nike

性别.java

public enum Gender {
Male("male"), Female("Female");

String gender;

private Gender(String gender) {
this.gender = gender;
}

public String getGender() {
return this.gender;
}

}

我是初学者,以前没有使用过枚举。这是获取枚举值的正确方法吗?

学生.java

public class Student {



private String firstName, lastName;
private Gender gender;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}

}

Controller

@RequestMapping(value = "/", method = RequestMethod.GET)
public String home( Model model) {


model.addAttribute("enums",Gender.values());

System.out.println(Gender.values());
return "home";
}

这是获取枚举值的正确方法吗???

jsp文件

<form>
<select>
<c:forEach items="${enums} " var="key">
<option value="${key}">${key}</option>
</c:forEach>
</select>
</form>

当我尝试填充值时,它只是 null 或空。如何解决这个问题?

最佳答案

将 @Controller 代码枚举值更改为列表。我想这可能对你有帮助。

@RequestMapping(value = "/", method = RequestMethod.GET)
public String home( Model model) {
List<Gender> enums = Arrays.asList(Gender.values());
model.addAttribute("enums",enums);
System.out.println(enums.size());
return "home";
}

关于java - 如何在 Spring mvc 中访问枚举值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38761287/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com