如何让 Struts 返回 manifest.json 并设置 MIME 类型?
解读
在国内银行、运营商、政务云等老系统改造项目中,manifest.json 常被用作 PWA 离线缓存清单,但 Struts 默认拦截所有后缀,容易把静态资源当 Action 解析,导致 404 或下载提示。面试官想确认两点:
- 你能否绕过 Struts 过滤器,让请求直达静态文件;
- 若必须走 Action(需动态拼接内容、做权限、埋日志),你能否在代码里显式设置 MIME 类型并禁用模板渲染,避免浏览器把响应当成普通文本或 HTML。
回答时要兼顾“安全合规”与“老框架限制”,体现对生产环境的敬畏。
知识点
- struts.action.excludePattern 常量:Struts 2 的过滤器放行正则,官方推荐的静态资源隔离手段。
- struts.mime.types 配置:在 struts.xml 或 default.properties 中追加映射,服务器级别生效,无需改代码。
- <result-type="stream">:Action 级别返回二进制或文本流,contentType、contentDisposition、inputName 三要素必须配齐。
- @Result(type = "stream"):注解方式同样支持,适合 REST 风格的轻量控制器。
- OGNL 与模板引擎默认拦截:若忘记设置 contentType,FreeMarker 会把 JSON 当 HTML 转义,导致浏览器解析失败。
- Nginx / Apache 前置代理:国内政企单位普遍采用前置静态服务器,让 .json 后缀直接走 CDN,减轻 WebLogic/Tomcat 压力,此时只需保证代理层 MIME 配置正确即可。
答案
生产环境推荐两步走:
-
静态文件方案(性能最优、代码零侵入)
把 manifest.json 放到 webapp/static/pwa/ 目录,在 struts.xml 根部加一行:<constant name="struts.action.excludePattern" value=".*\.(json|ico|png|js|css)$"/>然后在 Tomcat conf/web.xml 或 Spring Boot 的 application.properties 里确认:
mime.mapping.manifest.json=application/manifest+json重启后访问 https://域名/static/pwa/manifest.json,**响应头**里能看到:
Content-Type: application/manifest+json;charset=UTF-8即可被 Chrome 识别为 PWA 清单。
-
动态 Action 方案(需要鉴权或灰度发布)
新建 ManifestAction.java:public class ManifestAction extends ActionSupport { private InputStream inputStream; public String execute() { String json = buildDynamicManifest(); // 可带版本号、CDN 域名 inputStream = new ByteArrayInputStream(json.getBytes(StandardCharsets.UTF_8)); return SUCCESS; } public InputStream getInputStream() { return inputStream; } }struts.xml 中配置:
<action name="manifest" class="com.xxx.ManifestAction"> <result name="success" type="stream"> <param name="contentType">application/manifest+json</param> <param name="inputName">inputStream</param> <param name="contentDisposition">inline;filename="manifest.json"</param> </result> </action>关键点:type 必须是 stream,contentType 必须写全,不可省略 charset,否则安卓 Chrome 会报“MIME 类型不正确”。
拓展思考
- 如果客户环境是WebLogic 12c 与 Struts 2.3 共存,且 web.xml 里还有旧版 FilterDispatcher,记得把排除正则写到最靠前的过滤器之前,否则会被二次拦截。
- 对于等保 2.0 场景,manifest.json 里不能出现敏感路径,Action 方案可在返回前过滤 start_url、scope 字段,防止内网地址泄露。
- 当项目已迁移到Spring Boot + Struts 2.5 混合栈,可用 WebMvcConfigurer.addResourceHandlers 把 /pwa/** 映射到 classpath:/static/pwa/,完全绕过 Struts 核心过滤器,同时利用 Spring 的 ResourceHttpRequestHandler 自动设置 MIME,实现零 XML 配置。