【问题标题】:grails call taglib from quartz jobgrails 从石英作业中调用 taglib
【发布时间】:2016-05-11 22:37:24
【问题描述】:

我有一个调用 joda taglib 的石英作业(但可以是任何其他的)。

我是这样做的:

def joda = grailsApplication.mainContext.getBean('grails.plugin.jodatime.taglib.FormattingTagLib')

def formatDate = joda.format(value:event.startDate, style:"SS", locale:user.locale, zone:user.timeZone)

但我明白了:

org.quartz.JobExecutionException: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request. [See nested exception: java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet/DispatcherPortlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.]

这绝对是有道理的,因为石英作业不受请求约束,因为它是由时间触发的,而不是由请求触发的。

我四处寻找,但找不到合适的解决方案。有人可以给我提示吗?

【问题讨论】:

    标签: grails quartz-scheduler


    【解决方案1】:

    问题是joda.format() 尝试获取当前请求,正如您所说,这是不可能的。

    但更根本的是,标签库是为 GSP 服务的。在 GSP 之外调用它们并不是一个好的做法,因为它超出了标记库的用例。幸运的是,解决方案很简单:直接使用 joda 时间格式化程序:

    import org.joda.time.format.DateTimeFormat
    
    def formatter = DateTimeFormat.forStyle('SS').withLocale(user.locale).withZone(user.timeZone)
    def formatDate = formatter.print(event.startDate)
    

    https://github.com/gpc/joda-time/blob/grails2/grails-app/taglib/grails/plugin/jodatime/taglib/FormattingTagLib.groovy

    如何从石英作业中调用taglib的答案是根本不这样做。

    【讨论】:

    • 感谢您的回答。我还通过使用 DateTimeFormatter 提出了解决方案。但我不能接受你的回答,因为你给了我的问题(一个很好的)解决方案,但问题是我如何在石英工作中调用 TagLib
    • 另外,尝试获取当前请求的不是 joda TagLib(因为我正在传递语言环境属性,因此从不使用该请求)。它是所有 TagLibs 的普遍问题。他们只是没有进入代码块。如果我在 TagLib 方法的最开始执行 log.debug 事件
    • 我对此的回答是,你根本不知道。我确信这是可能的,但这就像拔牙一样,因为你必须注入一个请求,以便 taglib 认为它在正常情况下运行。至少对于自定义标签库来说,更好的解决方案是将公共代码放在其他地方,例如服务,并从作业和标签库中调用它。对于第三方标签库,不幸的是你会有一些代码重复。再一次,如何从石英作业中调用 taglib 的答案是根本不这样做。
    • 好的。你说的对。从 gsp 之外的任何其他地方调用 TagLib 对体系结构来说都是错误的。请把最后一句话放在你的答案中来回答这个问题。我会将其标记为已接受
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多