`
zhangwei_david
  • 浏览: 469558 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

#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 类型,而是一个枚举类。
 
0
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics