You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

自定义TagSupport标签中<fmt:message>输出为空的问题求助

解决自定义标签中<fmt:message>内容为空的问题

问题根源

你直接通过out.print()输出包含<fmt:message>标签的字符串时,这段内容会被当成纯文本发送到前端,JSP引擎不会再解析其中的JSTL标签。因为自定义标签的执行阶段在JSP标签解析阶段之后,此时JSP已经完成了所有标签的编译解析,后续输出的字符串不会再被处理。而直接在JSP页面中使用<fmt:message>时,JSP在编译阶段就会将其转换为对应的Java代码执行,所以能正常显示内容。

解决方案

直接调用JSTL fmt的底层API获取本地化消息,避免输出未解析的标签字符串:

public class RoleTag extends TagSupport {
    
    public int doStartTag() throws JspException {       
        try {
            JspWriter out = pageContext.getOut();
            
            // 获取JSTL的本地化上下文(消息源)
            MessageSource messageSource = (MessageSource) pageContext.getAttribute("javax.servlet.jsp.jstl.fmt.localizationContext");
            // 获取当前请求的Locale
            Locale locale = pageContext.getRequest().getLocale();
            
            // 直接获取解析后的消息文本
            String roleFood1 = messageSource.getMessage("roleFood1", null, locale);
            String roleFood2 = messageSource.getMessage("roleFood2", null, locale);
            
            // 拼接HTML并输出
            String outPrint = "<div><span>" + roleFood1 + "</span><span>" + roleFood2 + "</span></div>";
            out.print(outPrint);
        } catch (java.io.IOException e) {
            throw new JspTagException(e.getMessage());
        }
        return SKIP_BODY;
    }
    
}

补充说明

如果你的本地化配置使用了自定义的MessageSource,只需要替换对应的获取逻辑即可。这种方式直接跳过了JSTL标签解析步骤,直接获取最终的本地化文本,确保输出内容正确显示。

内容的提问来源于stack exchange,提问作者Francesco Tozzi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 14:57:10