#springMessage 错误分析

在 项目中使用#springMessage进行错误码解析为错误消息,可是在特定的场景下出现了

      $springMacroRequestContext.getMessage($code)

 

#springMessage      是在org/springframework/web/servlet/view/velocity/spring.vm 文件中定义了一个宏。其内容是:

 

#**
 * springMessage
 *
 * Macro to translate a message code into a message.
 *#
#macro( springMessage $code )$springMacroRequestContext.getMessage($code)#end
 
 springMacroRequestContext 又是什么呢?
分析Spring 的代码可以发现:
这个是值在AbastractTemplateView中北定义了
public abstract class AbstractTemplateView extends AbstractUrlBasedView {

    /**
     * Variable name of the RequestContext instance in the template model,
     * available to Spring's macros: e.g. for creating BindStatus objects.
     */
    public static final String SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE = "springMacroRequestContext";
 
if (this.exposeSpringMacroHelpers) {
			if (model.containsKey(SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE)) {
				throw new ServletException(
						"Cannot expose bind macro helper '" + SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE +
						"' because of an existing model object of the same name");
			}
			// Expose RequestContext instance for Spring macros.
			model.put(SPRING_MACRO_REQUEST_CONTEXT_ATTRIBUTE,
					new RequestContext(request, response, getServletContext(), model));
		}
 至此我们可以发现 这个对象就是org.springframework.web.servlet.support.RequestContext 对象。
 最终被调用的方法是:
	/**
	 * Retrieve the message for the given code, using the "defaultHtmlEscape" setting.
	 * @param code code of the message
	 * @return the message
	 * @throws org.springframework.context.NoSuchMessageException if not found
	 */
	public String getMessage(String code) throws NoSuchMessageException {
		return getMessage(code, null, isDefaultHtmlEscape());
	}
 
   可是最终发现页面上显示的是:
         $springMacroRequestContext.getMessage($code)
通过这个输出可以发现其原因是该宏未定义。 为什么会是未定义,仔细考虑一下发现原来是在异常的时候传入的code 不是一个String 类型,而是一个枚举类。
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值