복붙노트

[SCALA] 속도 템플릿 리소스를 찾을 수 없습니다

SCALA

속도 템플릿 리소스를 찾을 수 없습니다

받는다는 구조를 기반으로 단순한 속도 독립 실행 형 응용 프로그램. 다음 코드는 $ {BASEDIR} 폴더 / SRC / 메인 / 자원의 템플릿 helloworld.vm을 렌더링하는 스칼라 작성 니펫 :

com.ggd543.velocitydemo

import org.apache.velocity.app.VelocityEngine
import org.apache.velocity.VelocityContext
import java.io.StringWriter

/**
 * @author ${user.name}
 */
object App {

  def main(args: Array[String]) {
    //First , get and initialize an engine
    val ve = new VelocityEngine();
    ve.init();

    //Second, get the template
    val resUrl = getClass.getResource("/helloworld.vm")
    val t = ve.getTemplate("helloworld.vm");   // not work 
//    val t = ve.getTemplate("/helloworld.vm");  // not work
//    val t = ve.getTemplate(resUrl.toString);  // not work yet
    //Third, create a context and add data
    val context = new VelocityContext();
    context.put("name", "Archer")
    context.put("site", "http://www.baidu.com")
    //Finally , render the template into a StringWriter
    val sw = new StringWriter
    t.merge(context, sw)
    println(sw.toString);
  }

}

컴파일하고 프로그램을 실행하면, 다음과 같은 오류가 발생했습니다 :

2012-1-29 14:03:59 org.apache.velocity.runtime.log.JdkLogChute log
严重: ResourceManager : unable to find resource '/helloworld.vm' in any resource loader.
Exception in thread "main" org.apache.velocity.exception.ResourceNotFoundException: Unable to find resource '/helloworld.vm'
    at org.apache.velocity.runtime.resource.ResourceManagerImpl.loadResource(ResourceManagerImpl.java:474)
    at org.apache.velocity.runtime.resource.ResourceManagerImpl.getResource(ResourceManagerImpl.java:352)
    at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1533)
    at org.apache.velocity.runtime.RuntimeInstance.getTemplate(RuntimeInstance.java:1514)
    at org.apache.velocity.app.VelocityEngine.getTemplate(VelocityEngine.java:373)
    at com.ggd543.velocitydemo.App$.main(App.scala:20)
    at com.ggd543.velocitydemo.App.main(App.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

Process finished with exit code 1

해결법

  1. ==============================

    1.좋은 질문 - 이클립스를 사용하여 다음과 같이 오늘은 내 문제를 해결 :

    좋은 질문 - 이클립스를 사용하여 다음과 같이 오늘은 내 문제를 해결 :

    우리가 클래스 경로에보고 VelocityEngine에게 방법을 먼저 참조하십시오. 이 없이는 어디에서 찾아야하는지 모르겠다.

  2. ==============================

    2.나는 SRC / 메인 / 자원 / 템플릿에서 내 .vm을 넣어, 다음 코드는 다음과 같습니다

    나는 SRC / 메인 / 자원 / 템플릿에서 내 .vm을 넣어, 다음 코드는 다음과 같습니다

    Properties p = new Properties();
    p.setProperty("resource.loader", "class");
    p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
    Velocity.init( p );       
    VelocityContext context = new VelocityContext();           
    Template template = Velocity.getTemplate("templates/my.vm");
    

    이 웹 프로젝트에서 작동합니다.

    일식 Velocity.getTemplate에서 ( "my.vm")은 SRC / 메인 / 자원 / 또는 SRC의 .vm 파일을 찾습니다 속도 때문에 작동 / 메인은 / 자원 / 템플릿,하지만 웹 프로젝트에서, 우리는 사용 Velocity.getTemplate에 있습니다 ( "템플릿 / my.vm");

  3. ==============================

    3.당신은 다음과 같이 사용할 수 있습니다 :

    당신은 다음과 같이 사용할 수 있습니다 :

    Template t = ve.getTemplate("./src/main/resources/templates/email_html_new.vm");
    

    효과가있다.

  4. ==============================

    4.나는 인 IntelliJ IDEA와 비슷한 문제에 직면했다. 당신은이를 사용할 수 있습니다

    나는 인 IntelliJ IDEA와 비슷한 문제에 직면했다. 당신은이를 사용할 수 있습니다

     VelocityEngine ve = new VelocityEngine();
        Properties props = new Properties();
        props.put("file.resource.loader.path", "/Users/Projects/Comparator/src/main/resources/");
        ve.init(props);
    
        Template t = ve.getTemplate("helloworld.vm");
        VelocityContext context = new VelocityContext();
    
  5. ==============================

    5.당신이 적절히 구성된 자원 로더를 확인합니다. 참조 속도 도움말 선택에 대한 문서 및 리소스 로더를 구성 : http://velocity.apache.org/engine/releases/velocity-1.7/developer-guide.html#resourceloaders

    당신이 적절히 구성된 자원 로더를 확인합니다. 참조 속도 도움말 선택에 대한 문서 및 리소스 로더를 구성 : http://velocity.apache.org/engine/releases/velocity-1.7/developer-guide.html#resourceloaders

  6. ==============================

    6.당신은이 코드를 추가 할 수 있습니다 :

    당신은이 코드를 추가 할 수 있습니다 :

    VelocityEngine ve = new VelocityEngine();
    String vmPath = request.getSession().getServletContext().getRealPath("${your dir}");
    Properties p = new Properties();
    p.setProperty("file.resource.loader.path", vmPath+"//");
    ve.init(p);
    

    나는이 작업을 수행하고, 합격!

  7. ==============================

    7.

    VelocityEngine velocityEngin = new VelocityEngine();
    velocityEngin.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
    velocityEngin.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
    
    velocityEngin.init();
    
    Template template = velocityEngin.getTemplate("nameOfTheTemplateFile.vtl");
    

    당신은 속도 템플릿의 속성을 설정하려면 위의 코드를 사용할 수 있습니다. 템플릿을 초기화 할 때 그런 다음 tempalte 파일의 이름을 줄 수 있으며 클래스 경로에있는 경우가 있습니다.

    위의 모든 클래스는 패키지 org.apache.velocity에서 온 *

  8. ==============================

    8.속성 webapp.resource.loader.path 슬래시해야 시작 부두 내장 사용하는 동안 :

    속성 webapp.resource.loader.path 슬래시해야 시작 부두 내장 사용하는 동안 :

    webapp.resource.loader.path=/templates
    

    그렇지 않으면 템플릿은 ../webapp/templates에서 찾을 수 없습니다

  9. ==============================

    9.당신은 또한 대신 SRC / 메인 / 자바의 SRC / 메인 / 자원에서 폴더 템플릿을 넣을 수 있습니다. 나를 위해 작동 및 템플릿 자바 소스하지 않기 때문에 그것은 바람직한 위치.

    당신은 또한 대신 SRC / 메인 / 자바의 SRC / 메인 / 자원에서 폴더 템플릿을 넣을 수 있습니다. 나를 위해 작동 및 템플릿 자바 소스하지 않기 때문에 그것은 바람직한 위치.

  10. ==============================

    10.나는 비슷한 문제에 직면했다. 내가 잘못 폴더에 속도 엔진 메일 템플릿을 복사했다. JavaMailSender 및 VelocityEngine이 MailService 인터페이스에서 자원으로 선언되어 있기 때문에, 그 프로젝트에 대한 선언 자원 폴더 아래의 템플릿을 추가해야합니다.

    나는 비슷한 문제에 직면했다. 내가 잘못 폴더에 속도 엔진 메일 템플릿을 복사했다. JavaMailSender 및 VelocityEngine이 MailService 인터페이스에서 자원으로 선언되어 있기 때문에, 그 프로젝트에 대한 선언 자원 폴더 아래의 템플릿을 추가해야합니다.

    나는 변경을하고 일했다. 같은 템플릿을 넣어

    src/main/resources/templates/<package>/sampleMail.vm
    
  11. ==============================

    11.나는 미래의 참조를 위해이 작업 코드를 뒀다. 코드 샘플이 포함 된 부두와 아파치 속도 1.7 버전으로 작성되었습니다.

    나는 미래의 참조를 위해이 작업 코드를 뒀다. 코드 샘플이 포함 된 부두와 아파치 속도 1.7 버전으로 작성되었습니다.

    속도 템플릿 경로는 자원 폴더 email_templates 하위 폴더에 있습니다.

    자바 코드 조각 (조각 이클립스와 항아리 안에 모두 실행 일을하고 있습니다)

        ...
        templateName = "/email_templates/byoa.tpl.vm"
        VelocityEngine ve = new VelocityEngine();
        ve.setProperty(RuntimeConstants.RESOURCE_LOADER, "classpath");
        ve.setProperty("classpath.resource.loader.class", ClasspathResourceLoader.class.getName());
        ve.init();
        Template t = ve.getTemplate(this.templateName);
        VelocityContext velocityContext = new VelocityContext();
        velocityContext.put("","") // put your template values here
        StringWriter writer = new StringWriter();
        t.merge(this.velocityContext, writer);
    
    System.out.println(writer.toString()); // print the updated template as string
    

    OSGI를 들어 코드 조각을 연결.

    final String TEMPLATE = "resources/template.vm // located in the resource folder
    Thread current = Thread.currentThread();
           ClassLoader oldLoader = current.getContextClassLoader();
           try {
              current.setContextClassLoader(TemplateHelper.class.getClassLoader()); // TemplateHelper is a class inside your jar file
              Properties p = new Properties();
              p.setProperty("resource.loader", "class");
              p.setProperty("class.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
              Velocity.init( p );       
              VelocityEngine ve = new VelocityEngine();
              Template template = Velocity.getTemplate( TEMPLATE );
              VelocityContext context = new VelocityContext();
              context.put("tc", obj);
              StringWriter writer = new StringWriter();
              template.merge( context, writer );
            return writer.toString() ;  
           }  catch(Exception e){
              e.printStackTrace();
           } finally {
              current.setContextClassLoader(oldLoader);
           }
    
  12. ==============================

    12.받는다는 구조를 기반으로 단순한 속도 독립 실행 형 응용 프로그램. 여기에 템플릿 helloworld.vm을 렌더링하는 스칼라로 작성된 코드입니다

    받는다는 구조를 기반으로 단순한 속도 독립 실행 형 응용 프로그램. 여기에 템플릿 helloworld.vm을 렌더링하는 스칼라로 작성된 코드입니다

    ${basedir}/src/main/resources folder:
    
  13. from https://stackoverflow.com/questions/9051413/unable-to-find-velocity-template-resources by cc-by-sa and MIT license