如何自定义 ContentTypeInterceptor 实现根据请求头返回不同格式?
解读
在国内一线互联网或金融外包的 Java 岗面试中,这道题表面问“自定义拦截器”,实则考察三层能力:
- 对 Struts2 拦截器生命周期 的源码级理解;
- 对 Content-Type / Accept 请求头 的准确解析与线程安全处理;
- 对 Struts2 Result 模块扩展点 的掌握,能否在不改 Action 的前提下切换 JSON、XML、Excel 等不同视图。
面试官通常会在你给出思路后追问:“如果前端同时传了 Accept=application/json 和 Content-Type=multipart/form-data,你的拦截器优先级怎么定?” 因此答案必须体现防御式编程和配置优于约定的思想。
知识点
- 拦截器接口 com.opensymphony.xwork2.interceptor.Interceptor 与 AbstractInterceptor 的差异;
- ActionInvocation.getInvocationContext() 得到 ActionContext,进而拿到 HttpServletRequest 与 HttpServletResponse;
- Accept 头解析算法:按 q 值排序,兼容中文浏览器经常出现的 /;
- Struts2 常量 struts.action.extension 与 struts.content.type.disposition 对后续 Result 的影响;
- 线程安全:拦截器实例为单例,绝不能出现可变成员变量;
- Result 的自动切换技巧:把计算出的格式字符串写入 invocation.getInvocationContext().put("format", calculatedFormat),然后在 struts.xml 里用 ${format} 做动态 Result 名;
- 国内安全基线:必须过滤 Content-Type 中的非法字符(如换行),防止 HTTP 响应拆分攻击。
答案
- 创建 ContentTypeInterceptor,继承 AbstractInterceptor,保证无状态:
public class ContentTypeInterceptor extends AbstractInterceptor {
private static final Map<String, String> MEDIA_MAPPING = new HashMap<>();
static {
MEDIA_MAPPING.put("json", "json");
MEDIA_MAPPING.put("xml", "xml");
MEDIA_MAPPING.put("excel", "excel");
}
@Override
public String intercept(ActionInvocation invocation) throws Exception {
ActionContext ctx = invocation.getInvocationContext();
HttpServletRequest request = (HttpServletRequest) ctx.get(StrutsStatics.HTTP_REQUEST);
HttpServletResponse response = (HttpServletResponse) ctx.get(StrutsStatics.HTTP_RESPONSE);
// 1. 解析 Accept 头,按 q 值降序
String accept = request.getHeader("Accept");
String format = parseAccept(accept); // 返回 json / xml / excel 或 null
// 2. 兜底策略:取 URI 后缀
if (format == null) {
String uri = request.getRequestURI();
int dot = uri.lastIndexOf('.');
if (dot > 0) {
String ext = uri.substring(dot + 1).toLowerCase();
format = MEDIA_MAPPING.getOrDefault(ext, "json");
}
}
// 3. 写入上下文,供动态 Result 使用
ctx.put("format", format);
// 4. 设置响应头,避免中文乱码
response.setCharacterEncoding("UTF-8");
return invocation.invoke();
}
private String parseAccept(String accept) {
if (accept == null) return null;
// 简化实现:只取第一个匹配
if (accept.contains("application/json")) return "json";
if (accept.contains("application/xml") || accept.contains("text/xml")) return "xml";
if (accept.contains("application/vnd.ms-excel")) return "excel";
return null;
}
}
- 在 struts.xml 中声明拦截器栈:
<package name="api" extends="json-default" namespace="/api">
<interceptors>
<interceptor name="contentType" class="com.xxx.interceptor.ContentTypeInterceptor"/>
<interceptor-stack name="apiStack">
<interceptor-ref name="contentType"/>
<interceptor-ref name="defaultStack"/>
</interceptor-stack>
</interceptors>
<default-interceptor-ref name="apiStack"/>
<!-- 动态 Result -->
<action name="user" class="com.xxx.action.UserAction">
<result name="success" type="stream" parse="true">
<param name="contentType">${format == 'excel' ? 'application/vnd.ms-excel' : (format == 'xml' ? 'application/xml' : 'application/json')}</param>
<param name="inputName">inputStream</param>
</result>
</action>
</package>
- 在 Action 中提供 getInputStream(),根据 format 字段生成对应字节流即可。
- 部署后验证:
curl -H "Accept: application/json" http://host/api/user → JSONcurl -H "Accept: application/xml" http://host/api/user → XMLcurl http://host/api/user.excel → Excel 下载
关键点:拦截器必须无状态、提前设置 format、利用 ${} OGNL 动态决定 Result,全程不侵入业务 Action。
拓展思考
- 如果产品要求根据登录用户的个人偏好决定返回格式,可把偏好存入 Session,在拦截器里读取后回写 format;注意集群环境下 Session 复制带来的延迟。
- 面对大型银行老旧系统仍使用 Struts2 2.3.x,需验证 Content-Type 头中的 CRLF 注入,否则可能被监管扫描工具判为中危漏洞。
- 当接口需要流式返回 10 万条数据时,JSON 体积过大,可扩展拦截器逻辑:若 Accept 包含 application/x-ndjson,则切换为 Newline Delimited JSON,降低内存占用。
- 国内等保 2.0 要求敏感数据出口必须加密,可在拦截器里根据 format 决定是否强制开启 HTTPS 并附加 JWT 加密响应体,实现安全与内容协商一体化。