知識庫 / Spring / Spring MVC RSS 訂閱

Spring MVC 與 Velocity 快速指南

Spring MVC
HongKong
4
02:49 PM · Dec 06 ,2025

1. 簡介

Velocity 是 Apache 軟件基金會提供的模板引擎,它可以與普通文本文件、SQL、XML、Java 代碼以及許多其他類型的數據一起工作。

在本文中,我們將重點介紹如何使用 Velocity 與典型的 Spring MVC Web 應用程序一起使用。

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可以從這裏找到:velocityvelocity-tools

3. 配置

3.1. Web 配置

如果不想使用 web.xml,我們可以使用 Java 和初始化器 Initializer 來配置我們的 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>

請注意,我們已將servlet映射到“/*”路徑上。

3.2. Spring 配置

現在我們來回顧一個簡單的 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>

在這裏,我們告訴 Spring 在哪裏查找帶有註解的 Bean 定義。

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

我們通過以下行表明將在我們的項目中採用基於標註的配置:

<context:annotation-config />

通過創建 “velocityConfig” 和 “viewResolver” Bean,我們告訴 VelocityConfigurer 模板的查找位置,以及 VelocityLayoutViewResolver 查找視圖和佈局的位置。

4. Velocity 模板

最後,讓我們創建我們的模板——從一個常見的頭部開始:

<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. 結論

在本簡單教程中,我們已配置了 Spring MVC 應用程序以及 Velocity 模板引擎。

user avatar
0 位用戶收藏了這個故事!
收藏

發佈 評論

Some HTML is okay.