Grails扩展了HttpServletResponse元类

时间:2015-10-20 10:28:57

标签: grails groovy metaclass

我需要在response.setHeader()方法中添加一些功能而不创建子类。我像这样使用元类:

//grails bootstrap
  def overrideHttpResponse(){

    def old_impl = javax.servlet.http.HttpServletResponseWrapper.metaClass.&setHeader
    println "Get set HEaders"
    println net.bull.javamelody.CounterServletResponseWrapper.metaClass.methods.findAll { it.name == "setHeader" }.join("\n")
    println old_impl
    //output
    //Get set HEaders
    //public void javax.servlet.http.HttpServletResponseWrapper.setHeader(java.lang.String,java.lang.String)
    // org.codehaus.groovy.runtime.MethodClosure@6f62b062

    javax.servlet.http.HttpServletResponseWrapper.metaClass.setHeader = {String name, String value ->
      if(name == "Content-disposition"){
        value = value.replace(", "," ").replace(","," ")
      }
      println "In here"
      old_impl.invoke(name,value)
    }
  }
  //controller code
      withFormat {
      html result
      json {
        def map = exportService.getPackageMap(packageInstance, result.titlesList)

        def json = map as JSON

          response.setHeader("Content-disposition", "attachment; filename=\"${filename}.json\"")
          response.contentType = "application/json"
          println response.class
          //class net.bull.javamelody.CounterServletResponseWrapper
          render json
      }

为什么以上不起作用的任何建议?我已将打印输出添加为注释,但是不从metaClass中获取打印,内容处置值不会更改。我也尝试过这样:

println "Get set HEaders"
println response.class.metaClass.methods.findAll { it.name == "setHeader" }.join("\n")
def old_impl = javax.servlet.http.HttpServletResponseWrapper.metaClass.getMetaMethod("setHeader",[String,String] as Class[])
println old_impl
//Get set HEaders
//public void javax.servlet.http.HttpServletResponseWrapper.setHeader(java.lang.String,java.lang.String)
//public abstract void javax.servlet.http.HttpServletResponse.setHeader(java.lang.String,java.lang.String)

此外,在我的控制器内部,我已经尝试了这一点,同样没有对返回的文件名进行任何更改:

   def old_impl = response.class.metaClass.getMetaMethod("setHeader",[String,String] as Class[])
   println old_impl
   //public abstract void javax.servlet.http.HttpServletResponse.setHeader(java.lang.String,java.lang.String)

    response.class.metaClass.setHeader = {String name, String value ->
      if(name == "Content-disposition"){
        value = value.replace(", "," ").replace(","," ")
      }
      println "In here"
      old_impl.invoke(name,value)
    }

0 个答案:

没有答案