1. 序章

Velocity は、Apache Software Foundationのテンプレートエンジンであり、通常のテキストファイル、SQL、XML、Javaコード、およびその他の多くのタイプを処理できます。

この記事では、典型的なSpringMVCWebアプリケーションでVelocityを利用することに焦点を当てます。

2. Mavenの依存関係

次の依存関係を使用して、Velocityサポートを有効にすることから始めましょう。

<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity</artifactId>
    <version>1.7</version>
</dependency>
        
<dependency>
    <groupId>org.apache.velocity</groupId>
    <artifactId>velocity-tools</artifactId>
    <version>2.0</version>
</dependency>

両方の最新バージョンは、velocityおよびvelocity-toolsにあります。

3. 構成

3.1. Web構成

web.xml を使用したくない場合は、Javaと初期化子を使用してWebプロジェクトを構成しましょう。

public class MainWebAppInitializer implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext sc) throws ServletException {
        AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
        root.register(WebConfig.class);

        sc.addListener(new ContextLoaderListener(root));

        ServletRegistration.Dynamic appServlet = 
          sc.addServlet("mvc", new DispatcherServlet(new GenericWebApplicationContext()));
        appServlet.setLoadOnStartup(1);
    }
}

または、もちろん、従来のweb.xmlを使用することもできます。

<web-app ...>
    <display-name>Spring MVC Velocity</display-name>
    <servlet>
        <servlet-name>mvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/mvc-servlet.xml</param-value>
     </init-param>
     <load-on-startup>1</load-on-startup>
    </servlet>
    
    <servlet-mapping>
        <servlet-name>mvc</servlet-name>
    <url-pattern>/*</url-pattern>
    </servlet-mapping>
 
    <context-param>
        <param-name>contextConfigLocation</param-name>
    <param-value>/WEB-INF/spring-context.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>

サーブレットを「/*」パスにマッピングしたことに注意してください。

3.2. SpringConfig

ここで、単純なSpring構成について見ていきましょう。ここでも、Javaから始めます。

@Configuration
@EnableWebMvc
@ComponentScan(basePackages= {
  "com.baeldung.mvc.velocity.controller",
  "com.baeldung.mvc.velocity.service" }) 
public class WebConfig extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry
          .addResourceHandler("/resources/**")
          .addResourceLocations("/resources/");
    }
 
    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }

    @Bean
    public ViewResolver viewResolver() {
        VelocityLayoutViewResolver bean = new VelocityLayoutViewResolver();
        bean.setCache(true);
        bean.setPrefix("/WEB-INF/views/");
        bean.setLayoutUrl("/WEB-INF/layouts/layout.vm");
        bean.setSuffix(".vm");
        return bean;
    }
    
    @Bean
    public VelocityConfigurer velocityConfig() {
        VelocityConfigurer velocityConfigurer = new VelocityConfigurer();
        velocityConfigurer.setResourceLoaderPath("/");
        return velocityConfigurer;
    }
}

また、構成のXMLバージョンについても簡単に見てみましょう。

<beans ...>
    <context:component-scan base-package="com.baeldung.mvc.velocity.*" />
    <context:annotation-config /> 
    <bean id="velocityConfig" 
      class="org.springframework.web.servlet.view.velocity.VelocityConfigurer">
        <property name="resourceLoaderPath">
            <value>/</value>
        </property>
    </bean> 
    <bean id="viewResolver"
      class="org.springframework.web.servlet.view.velocity.VelocityLayoutViewResolver">
        <property name="cache" value="true" />
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="layoutUrl" value="/WEB-INF/layouts/layout.vm" />
        <property name="suffix" value=".vm" />
    </bean>
</beans>

ここでは、注釈付きのBean定義を探す場所をSpringに指示しています。

<context:component-scan base-package="com.baeldung.mvc.velocity.*" />

次の行を使用して、プロジェクトでアノテーション駆動型構成を使用することを示しています。

<context:annotation-config />

velocityConfig」および「viewResolver」Beanを作成することにより、 VelocityConfigurer にテンプレートの検索場所、VelocityLayoutViewResolverビューの検索場所を指示します。とレイアウト。

4. 速度テンプレート

最後に、共通のヘッダーから始めて、テンプレートを作成しましょう。

<div style="...">
    <div style="float: left">
        <h1>Our tutorials</h1>
    </div>
</div>

とフッター:

<div style="...">
    @Copyright baeldung.com
</div>

そして、次のコードで parse を使用して、上記のフラグメントを使用するサイトの一般的なレイアウトを定義しましょう。

<html>
    <head>
        <title>Spring & Velocity</title>  
    </head>
    <body>
        <div>
            #parse("/WEB-INF/fragments/header.vm")
        </div>  
        <div>
            <!-- View index.vm is inserted here -->
            $screen_content
        </div>  
        <div>
            #parse("/WEB-INF/fragments/footer.vm")
        </div>
    </body>
</html>

$screen_content変数にページのコンテンツが含まれていることを確認できます。

最後に、メインコンテンツのテンプレートを作成します。

<h1>Index</h1>
 
<h2>Tutorials list</h2>
<table border="1">
    <tr>
        <th>Tutorial Id</th>
        <th>Tutorial Title</th>
        <th>Tutorial Description</th>
        <th>Tutorial Author</th>
    </tr>
    #foreach($tut in $tutorials)
    <tr>
        <td>$tut.tutId</td>
        <td>$tut.title</td>
        <td>$tut.description</td>
        <td>$tut.author</td>
    </tr>
    #end
</table>

5. コントローラ側

チュートリアルのリストを、入力するレイアウトのコンテンツとして返す単純なコントローラーを作成しました。

@Controller
@RequestMapping("/")
public class MainController {
 
    @Autowired
    private ITutorialsService tutService;

    @RequestMapping(value ="/", method = RequestMethod.GET)
    public String defaultPage() {
        return "index";
    }

    @RequestMapping(value ="/list", method = RequestMethod.GET)
    public String listTutorialsPage(Model model) { 
        List<Tutorial> list = tutService.listTutorials();
        model.addAttribute("tutorials", list);
        return "index";
    }
}

最後に、この単純な例にローカルでアクセスできます。たとえば、 localhost:8080 / spring-mvc-velocity /

6. 結論

この簡単なチュートリアルでは、Velocityテンプレートエンジンを使用してSpringMVCWebアプリケーションを構成しました。

このチュートリアルの完全なサンプルコードは、GitHubリポジトリにあります。