Apache Velocity 샘플 코드를 이동할 때까지

Apache Velocity 샘플 코드를 이동할 때까지



자신의 메모로 기재합니다.
공식 사이트를 읽으면서 Velocity의 거동을 확인하는 환경을 원했기 때문에 만들었습니다.
※「Velocity가 움직이면 OK」라는 느낌으로 환경 구축했기 때문에, 잘못 등이 있으면 지적해 주시면 기쁩니다.

필요한 것


  • Tomcat 9 (서블릿 컨테이너)
  • Eclipse (통합 개발 환경)

  • 소스 코드 세트



    아래의 순서로 작성한 소스 코드 세트의 Git 리포지토리입니다.
    htps : // 기주 b. 이 m/ゔぃc보 s1002/ゔぇぉしty_さ mpぇ

    절차


  • Tomcat 설치
  • Tomcat을 Eclipse에 서버로 구성
  • Eclipse에서 Maevn 프로젝트 만들기
  • Maven에서 종속 라이브러리 다운로드
  • Velocity 템플릿 파일을 브라우저에 표시합니다
  • Java에서 Velocity 컨텍스트로 변수를 전달하고 표시합니다.

    Tomcat 설치



    아래 사이트에서 32-bit/64-bit Windows Service Installer를 다운로드하여 설치했습니다.
    htps : // 및 m 또는 t. 아파치. 오 rg / 도 w 응 아 d 90. c기


    Tomcat을 Eclipse에 서버로 설정



  • Window > Preferences > Server > Runtime Environment 열기



  • Eclipse로 Maven 프로젝트 만들기



  • File > New > Maven Project를 선택합니다.


  • Select an Archetype에서 maven-archetype-webapp를 선택합니다.


  • GroupId, ArtifactId를 지정하여 Maven 프로젝트 만들기



  • Maven에서 종속 라이브러리 다운로드



  • pom.xml에서 종속 라이브러리에 다음을 지정합니다

  • pom.xml
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.velocity.tools</groupId>
        <artifactId>velocity-tools-generic</artifactId>
        <version>3.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.velocity.tools</groupId>
        <artifactId>velocity-tools-view</artifactId>
        <version>3.0</version>
    </dependency>
    <dependency>
        <groupId>org.apache.velocity.tools</groupId>
        <artifactId>velocity-tools-view-jsp</artifactId>
        <version>3.0</version>
    </dependency>
    <dependency>
        <groupId>com.republicate</groupId>
        <artifactId>webapp-slf4j-logger</artifactId>
        <version>1.3</version>
    </dependency>
    

  • 프로젝트 > Run As > Maven build 실행



  • Velocity 템플릿 파일을 브라우저에 표시


  • web.xml에 VelocityViewServlet 설정 추가
    여기의 설명에 따라 web.xml에 VelocityViewServlet 설정을 추가합니다.

  • web.xml
    <!-- ログ出力の設定 -->
    <context-param>
        <param-name>webapp-slf4j-logger.level</param-name>
        <param-value>debug</param-value>
    </context-param>
    <context-param>
        <param-name>webapp-slf4j-logger.format</param-name>
        <param-value>%logger [%level] [%ip] %message</param-value>
    </context-param>
    <servlet>
        <servlet-name>velocity</servlet-name>
        <servlet-class>
            org.apache.velocity.tools.view.VelocityViewServlet
        </servlet-class>
    
        <!-- Unless you plan to put your tools.xml and velocity.properties under 
            different folders or give them different names, then these two init-params 
            are unnecessary. The VelocityViewServlet will automatically look for these 
            files in the following locations. -->
        <init-param> 
            <param-name>org.apache.velocity.toolbox</param-name> 
            <param-value>/WEB-INF/tools.xml</param-value> 
        </init-param> 
        <init-param> 
            <param-name>org.apache.velocity.properties</param-name> 
            <param-value>/WEB-INF/velocity.properties</param-value> 
        </init-param>
    </servlet>
    
    <!-- Map *.vm files to Velocity -->
    <servlet-mapping>
        <servlet-name>velocity</servlet-name>
        <url-pattern>*.vm</url-pattern>
    </servlet-mapping>
    

  • 프로젝트 루트 > src 바로 아래에 템플릿 파일 만들기


  • sample.vm
    #set($text = "Velocity World!")
    Hello $text
    
  • Eclipse의 서버 뷰에서 Tomcat을 시작합니다.
  • 브라우저를 통해 sample.vm 보기 확인
    브라우저 URL에 http://localhost:8080/velocity_sample/sample.vm를 입력하고 표시

  • 이것으로 완료됩니다.
    sample.vm에 기술한 Velocity의 처리가 실행되어 내용이 표시되고 있는 것을 확인할 수 있었습니다.

    Java에서 Velocity 컨텍스트로 변수를 전달하고 표시


  • VelictyViewServlet 의 서브 클래스를 작성합니다.

  • MyVelocityViewServlet.java
    public class MyVelocityViewServlet extends VelocityViewServlet {
        private static final long serialVersionUID = 1L;
        protected Template handleRequest(HttpServletRequest request,
                HttpServletResponse response,
                Context ctx)
        {
    
            ctx.put("boolTrue", true);
            ctx.put("boolFalse", false);
            ctx.put("number", 1234);
            ctx.put("string", "abcd");
            ctx.put("list", Arrays.asList("a", "b", "c", "d"));
    
            Map<String, String> map = new HashMap<>();
            map.put("key1", "value1");
            map.put("key2", "value2");
            ctx.put("map", map);
            return super.handleRequest(request, response, ctx);
        }
    }
    
  • web.xml 을 다음과 같이 VelictyViewServlet 의 서브 클래스용으로 재기록합니다.

  • web.xml
    <servlet>
        <servlet-name>velocity</servlet-name>
    <!--        <servlet-class> -->
    <!--            org.apache.velocity.tools.view.VelocityViewServlet -->
    <!--        </servlet-class> -->
        <servlet-class>velocity_sample.MyVelocityViewServlet</servlet-class>
    
        <!-- Unless you plan to put your tools.xml and velocity.properties under 
            different folders or give them different names, then these two init-params 
            are unnecessary. The VelocityViewServlet will automatically look for these 
            files in the following locations. -->
        <init-param>
            <param-name>org.apache.velocity.toolbox</param-name>
            <param-value>/WEB-INF/tools.xml</param-value>
        </init-param>
        <init-param>
            <param-name>org.apache.velocity.properties</param-name>
            <param-value>/WEB-INF/velocity.properties</param-value>
        </init-param>
    </servlet>
    
  • Java로 설정된 변수를 호출하는 템플릿 파일을 작성합니다.

    sample_of_context.vm
    \${boolTrue}: ${boolTrue}<br/>
    \${boolFalse}: ${boolFalse}<br/>
    \${number}: ${number}<br/>
    \${string}: ${string}<br/>
    \${list}: ${list}<br/>
    \${map}: ${map}<br/>
    

    다음과 같이 출력된다.
  • 좋은 웹페이지 즐겨찾기