如何将 HTTP 参数 user.address.city 绑定到 Action 中 User 对象的 Address 属性?
解读
这是国内 Java 后端面试中“参数级联绑定”高频考点,考察候选人对 OGNL(Object-Graph Navigation Language) 在 Struts2 内部运行机制的掌握。
面试官通常会在白板上写出 user.address.city,追问“需不需要额外配置?空指针怎么办?类型转换失败如何处理?”
回答时务必围绕 OGNL 栈、拦截器执行顺序、空值安全、类型转换器 四个维度展开,体现“源码级”理解,而不是简单一句“写个 setUser 就行”。
知识点
- OGNL 表达式解析顺序:参数进入 Struts2 后,由 ParametersInterceptor 把 user.address.city 拆成三段,依次调用 getUser().getAddress().setCity(...)。
- 空路径自动实例化:只要 User 与 Address 均提供无参构造方法,OGNL 会用 OgnlRuntime#createObject 反射创建中间对象,无需手动 new。
- 拦截器顺序:ModelDriven 拦截器 在 ParametersInterceptor 之前,若 Action 实现了 ModelDriven,则先压入模型栈顶,参数绑定会优先落在模型而非 Action 本身。
- 类型转换失败处理:若 city 字段需要自定义类型(如枚举),需编写 StrutsTypeConverter 并在 xwork-conversion.properties 注册,失败信息由 ConversionErrorInterceptor 封装进 fieldError。
- 安全加固:生产环境必须打开 struts.ognl.allowStaticMethodAccess=false 与 RegexPatternMatcher,防止 OGNL 注入。
答案
步骤一:保证对象图可导航
public class User implements Serializable {
private Address address; // 提供 getAddress()
public User() { // **无参构造**
if (address == null) {
address = new Address(); // 防御式写法,避免并发时空指针
}
}
}
public class Address {
private String city;
// public Address() {} // **必须有无参构造**
public void setCity(String city) { this.city = city; }
public String getCity() { return city; }
}
步骤二:Action 中声明 User 属性
public class ProfileAction extends ActionSupport {
private User user; // 属性名必须与参数前缀一致
public User getUser() { return user; }
public void setUser(User user) { this.user = user; }
public String execute() {
System.out.println(user.getAddress().getCity()); // 可直接取值
return SUCCESS;
}
}
步骤三:前端参数名保持 OGNL 风格
POST /profile.action
Content-Type: application/x-www-form-urlencoded
user.address.city=北京
步骤四:验证与容错
- 若 Address 为 null,OGNL 会自动实例化,但建议在 getUser() 里做双重检查锁定,防止高并发下重复 new。
- 若出现 conversionError,在 struts.xml 开启
<result name="input">/error.jsp</result>并由 conversionAnnotation 输出提示,符合国内企业对“友好报错”的硬性要求。
拓展思考
- 深层级绑定极限:OGNL 默认支持 256 级属性导航,超过会抛出 OgnlException,可通过 struts.ognl.expressionMaxLength 调整,但面试时建议回答“业务上不超过 5 级,防止性能与可读性恶化”。
- 集合嵌套绑定:若参数为 user.addressList[0].city,Address 需实现 Comparable 并在 Action 中初始化 List,OGNL 会调用 OgnlUtil#addElement 自动扩容,索引越界时返回 null 而非异常,这是国内金融系统常用的“动态行录入”技巧。
- 与 Spring 集成后的作用域:当 Action 由 Spring 管理并设为 prototype 时,Spring 代理会覆盖 Struts2 的 ObjectFactory,此时必须保证 User、Address 也在 Spring 扫描路径且提供 CGLIB 友好构造,否则 OGNL 自动实例化会失败,抛出 InstantiationError,该坑在一线互联网厂出现过线上故障。