Hibernate中JSP值与Entity类变量映射问题咨询
Hey there! Let's break down exactly why you're seeing these behaviors—this all comes down to how JSP's EL expressions (the ${} syntax) work with JavaBean getter/setter rules, not directly accessing your entity class's private member variables. Let's unpack each scenario step by step:
1. 为什么${tempCustomer.id}(小写i)能正常工作,而${tempCustomer.Id}会报错?
The key rule here is: EL doesn't care what your private field is named—it only looks for matching getter methods, and derives the "property name" from the getter's name.
Looking at your entity code:
// 私有变量名是大写I:Id private int Id; // Getter方法遵循JavaBean规范:getId() public int getId() { return Id; }
按照JavaBean的规范,EL是这样将getter映射到属性名的:
- 去掉getter方法名的
get前缀 →Id - 将剩余部分的首字母转为小写 →
id
这个推导出来的id就是EL能识别的属性名。所以当你写${tempCustomer.id}时,EL会自动调用tempCustomer.getId()获取值——完全和私有变量的名字Id无关。
而当你尝试${tempCustomer.Id}时,EL会把Id当作一个独立的属性名。由于EL对大小写是严格敏感的,它会去寻找类似get_Id()或getID()的方法(你的代码里并没有这些方法),所以就会抛出错误。
2. 为什么${tempCustomer.firstName}有效,改成${tempCustomer.firstname}就报错?
同样遵循JavaBean的属性名推导规则,只是针对多段式的属性名:
你的实体类里有这个getter方法:
public String getFirstName() { return firstName; }
按照规则推导:
- 去掉
get前缀 →FirstName - 首字母转小写 →
firstName
这意味着EL只认firstName作为合法的属性名。当你改成firstname时,EL会去寻找名为getFirstname()的方法——你的代码里并没有这个方法,所以自然会报错。
核心总结:EL与JavaBean的映射规则
为了避免以后再遇到类似困惑,咱们把关键规则整理一下:
- EL表达式完全依赖getter/setter方法来访问属性——私有变量的名字根本不重要(哪怕你把
Id改成customerId,只要getter还是getId(),用${tempCustomer.id}依然能拿到值)。 - 属性名由getter方法推导:
getXxx()→ 属性名是xxx(首字母小写,其余字母保持原大小写);布尔类型的属性则用isXxx()来推导。 - EL对属性名的大小写严格敏感,必须和推导出来的属性名完全匹配(比如
firstName不能写成firstname)。
举个额外的例子:如果你的getter方法是getURL(),推导后的属性名是URL(因为首两个字母都是大写,JavaBean规范有特殊处理),这时候EL里就得写${tempCustomer.URL}而不是${tempCustomer.url}。
内容的提问来源于stack exchange,提问作者Lehtia

